Commit 22bbda52 authored by di-nethra's avatar di-nethra

expert advices component logic updated

parent e6faa9f4
No preview for this file type
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (soil-component-BE)" project-jdk-type="Python SDK" />
<component name="PyCharmProfessionalAdvertiser">
<option name="shown" value="true" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/soil-component-BE.iml" filepath="$PROJECT_DIR$/.idea/soil-component-BE.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/env" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>
\ No newline at end of file
......@@ -10,6 +10,7 @@ class Crop:
# Function to calculate the suitability score for a crop
def calculate_suitability_score(crop, user_soil_nutrients, optimization_criteria):
global suitability
score = 0
for nutrient in user_soil_nutrients:
nutrient_value = user_soil_nutrients[nutrient]
......@@ -21,9 +22,7 @@ def calculate_suitability_score(crop, user_soil_nutrients, optimization_criteria
if difference == 0:
suitability = 100.0
else:
suitability = 0.0
else:
suitability = (1 - difference / required_value) * 100.0
suitability = (1 - difference / required_value) * 100.0
weighted_suitability = suitability * weight
score += weighted_suitability
......@@ -72,13 +71,12 @@ def receive_npk_data():
Crop("Maize", {'N': 0.6, 'P': 0.4, 'K': 0.5}),
Crop("Potato", {'N': 0.3, 'P': 0.4, 'K': 0.5}),
Crop("Tomato", {'N': 0.6, 'P': 0.6, 'K': 0.6}),
Crop("Cotton", {'N': 0.6, 'P': 0.4, 'K': 0.6})
]
optimization_criteria = {
'N': 1,
'P': 1,
'K': 1
'P': 0.5,
'K': 0.25
}
crop_scores = []
......
......@@ -62,3 +62,9 @@ Tomato,0.3,0.5,0.2
Wheat,4.47,0.29,5.24
Cotton,4.47,0.29,5.24
Tomato,4.47,0.29,5.24
Tomato,30,50,20
Wheat,30,50,20
Cotton,30,50,20
Tomato,40,30,30
Wheat,40,30,30
Cotton,40,30,30
from flask import Flask, request, jsonify
import joblib
import pandas as pd
from sklearn.metrics import accuracy_score
model = joblib.load('./soil_crop_model.joblib')
import pymongo as pymongo
# Load your trained model
model = joblib.load('./random_forest_model_v2.joblib')
eval_data = pd.read_csv('soil_crop.csv')
eval_X = eval_data[['nitrogen', 'phosphorus', 'potassium']]
eval_y = eval_data['crop']
predicted_labels = model.predict(eval_X)
accuracy = accuracy_score(eval_y, predicted_labels)
# Predict probabilities for all classes
predicted_probabilities = model.predict_proba(eval_X)
app = Flask(__name__)
mongo_client = pymongo.MongoClient("mongodb+srv://anjana:8682123abc@cluster0.bhsdkyx.mongodb.net/?retryWrites=true&w=majority")
db = mongo_client["AgriExpertSolutions"]
collection = db["organic_solutions"]
# Function to calculate the mean N, P, K values for a given crop
def get_mean_values_for_crop(crop_name):
crop_data = eval_data[eval_data['crop'] == crop_name]
if not crop_data.empty:
mean_values = crop_data[['nitrogen', 'phosphorus', 'potassium']].mean()
return mean_values.to_dict()
else:
return None
@app.route('/predict', methods=['POST'])
def predict():
input_data = request.get_json()
......@@ -22,13 +36,111 @@ def predict():
phosphorus = input_data['P']
potassium = input_data['K']
predicted_crop = model.predict([[nitrogen, phosphorus, potassium]])
# Predict probabilities for the input data
predicted_probabilities = model.predict_proba([[nitrogen, phosphorus, potassium]])
# Get the classes (crops) and their corresponding probabilities
classes = model.classes_
probabilities = predicted_probabilities[0]
# Create a list to store crop information as objects
crop_info = []
for crop, probability in zip(classes, probabilities):
crop_info.append({
'crop': crop,
'probability': probability
})
# Sort the crops by probability in descending order
sorted_crops = sorted(crop_info, key=lambda x: x['probability'], reverse=True)
# Get the top three crops
top_three_crops = sorted_crops[:3]
response = {
'crop': predicted_crop[0],
'accuracy': accuracy
'top_three_crops': top_three_crops,
'accuracy': accuracy_score(eval_y, model.predict(eval_X)) # Calculate accuracy on evaluation data
}
return jsonify(response)
@app.route('/mean_values/<crop_name>', methods=['GET'])
def get_mean_values(crop_name):
mean_values = get_mean_values_for_crop(crop_name)
if mean_values is not None:
return jsonify(mean_values)
else:
return jsonify({'error': 'Crop not found'}), 404
@app.route('/balancesoil', methods=['POST'])
def balance_soil():
input_data = request.get_json()
nitrogen_soil = input_data['N']
phosphorus_soil = input_data['P']
potassium_soil = input_data['K']
crop = input_data['crop']
# Get the mean nutrient values for the specified crop
mean_values = get_mean_values_for_crop(crop)
if mean_values is not None:
# Calculate the differences between soil values and mean values
nitrogen_diff = mean_values['nitrogen'] - nitrogen_soil
phosphorus_diff = mean_values['phosphorus'] - phosphorus_soil
potassium_diff = mean_values['potassium'] - potassium_soil
# Create a dictionary to store the lacking nutrient values
lacking_nutrients = {}
# Fetch the instructions for each nutrient deficiency from the database
if nitrogen_diff > 0:
nitrogen_instructions = list(collection.find({"target_nutrient": "Nitrogen"}))
lacking_nutrients['nitrogen'] = nitrogen_diff
lacking_nutrients['nitrogen_instructions'] = [{'description': ins['description'], 'recommendedApplication': ins['recommendedApplication']} for ins in nitrogen_instructions]
if phosphorus_diff > 0:
phosphorus_instructions = list(collection.find({"target_nutrient": "Phosphorus"}))
lacking_nutrients['phosphorus'] = phosphorus_diff
lacking_nutrients['phosphorus_instructions'] = [{'description': ins['description'], 'recommendedApplication': ins['recommendedApplication']} for ins in phosphorus_instructions]
if potassium_diff > 0:
potassium_instructions = list(collection.find({"target_nutrient": "Potassium"}))
lacking_nutrients['potassium'] = potassium_diff
lacking_nutrients['potassium_instructions'] = [{'description': ins['description'], 'recommendedApplication': ins['recommendedApplication']} for ins in potassium_instructions]
return jsonify(lacking_nutrients)
else:
return jsonify({'error': 'Crop not found'}), 404
@app.route('/add_solution', methods=['POST'])
def add_solution():
input_data = request.get_json()
print(input_data)
# Extract data from the request
name = input_data.get('name')
description = input_data.get('description')
target_nutrient = input_data.get('target_nutrient')
recommended_application = input_data.get('recommended_application')
# Insert the data into the MongoDB collection
new_solution = {
'name': name,
'description': description,
'target_nutrient': target_nutrient,
'recommendedApplication': recommended_application
}
# Insert the document into the collection
result = collection.insert_one(new_solution)
if result.inserted_id:
return jsonify({'message': 'Solution added successfully'})
else:
return jsonify({'message': 'Failed to add solution'}), 500
if __name__ == '__main__':
app.run()
import pandas as pd
# Read the CSV file into a Pandas DataFrame
df = pd.read_csv('soil_crop.csv')
# Divide the values in the "nitrogen," "phosphorus," and "potassium" columns by 10
df['nitrogen'] = df['nitrogen'] / 10
df['phosphorus'] = df['phosphorus'] / 10
df['potassium'] = df['potassium'] / 10
# Save the new dataset to a new CSV file
df.to_csv('new_soil_data.csv', index=False)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment