Commit c17b7e5d authored by Samarakoon S.M.A.D IT20233808's avatar Samarakoon S.M.A.D IT20233808

Merge branch 'feature/IT20233808/soilBasedCropRecommendation' into 'master'

Feature/it20233808/soil based crop recommendation

See merge request !9
parents d9bf3873 7e830b00
......@@ -2,8 +2,9 @@ import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ImageBackground } from 'react-native';
const HomePage = ({ navigation }) => {
const handleOptionSelect = (option) => {
// Handle navigation to the selected option
if (option === 'pestDisease') {
navigation.navigate('PestDiseasePage');
} else if (option === 'soilData') {
......
import BarleyImage from '../../assets/barley.png';
import WheatImage from '../../assets/wheat.png';
import RiceImage from '../../assets/rice.png';
import MaizeImage from '../../assets/maize.png';
import PotatoImage from '../../assets/potato.png';
import TomatoImage from '../../assets/tomato.png';
import CottonImage from '../../assets/cotton.png';
import SoybeanImage from '../../assets/soybean.jpg';
import CoconutImage from '../../assets/coconut.jpeg';
import PomagranateImage from '../../assets/pomagranate.jpeg';
import MangoImage from '../../assets/mango.jpeg';
const cropImages = {
Soybean: SoybeanImage,
Barley: BarleyImage,
Wheat: WheatImage,
Rice: RiceImage,
Maize: MaizeImage,
Potato: PotatoImage,
Tomato: TomatoImage,
Cotton: CottonImage,
coconut: CoconutImage,
pomegranate: PomagranateImage,
mango: MangoImage
};
export default cropImages;
......@@ -2,27 +2,9 @@ import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, ActivityIndicator, StyleSheet, ImageBackground, Image } from 'react-native';
import axios from 'axios';
import { useRoute } from '@react-navigation/native';
import BarleyImage from '../../assets/barley.png';
import WheatImage from '../../assets/wheat.png';
import RiceImage from '../../assets/rice.png';
import MaizeImage from '../../assets/maize.png';
import PotatoImage from '../../assets/potato.png';
import TomatoImage from '../../assets/tomato.png';
import CottonImage from '../../assets/cotton.png';
import SoybeanImage from '../../assets/soybean.jpg';
import BackgroundImage from '../../assets/backgroudManualData.jpg';
import cropImages from '../common/Images';
const cropImages = {
Soybean: SoybeanImage,
Barley: BarleyImage,
Wheat: WheatImage,
Rice: RiceImage,
Maize: MaizeImage,
Potato: PotatoImage,
Tomato: TomatoImage,
Cotton: CottonImage,
};
const MostSuitableCrops = () => {
const [cropData, setCropData] = useState(null);
......@@ -52,12 +34,13 @@ const MostSuitableCrops = () => {
useEffect(() => {
const fetchCropData = async () => {
try {
const response = await axios.post('http://127.0.0.1:5000/npk-data', {
const response = await axios.post('http://127.0.0.1:5000/predict', {
N: userNpkData['Nitrogen'],
P: userNpkData['Phosphorus'],
K: userNpkData['Potassium']
});
const responseData = response.data;
console.log("res data",responseData);
setCropData(responseData);
} catch (error) {
console.error('Error fetching crop data:', error);
......@@ -83,10 +66,10 @@ const MostSuitableCrops = () => {
<View style={styles.card}>
<Text style={styles.title}>Most Suitable Crops:</Text>
<View style={styles.cropContainer}>
{cropData.top_crops.map((cropName) => (
<View key={cropName} style={styles.cropItem}>
<Image source={cropImages[cropName]} style={styles.cropImage} />
<Text style={styles.cropText}>{cropName}</Text>
{cropData.top_three_crops.map((cropInfo) => (
<View key={cropInfo.crop} style={styles.cropItem}>
<Image source={cropImages[cropInfo.crop]} style={styles.cropImage} />
<Text style={styles.cropText}>{cropInfo.crop}</Text>
</View>
))}
</View>
......
......@@ -21,7 +21,8 @@
"react-native": "0.71.8",
"react-native-safe-area-context": "4.5.0",
"react-native-screens": "~3.20.0",
"react-native-svg": "^13.9.0"
"react-native-svg": "^13.9.0",
"react-native-web": "~0.18.11"
},
"devDependencies": {
"@babel/core": "^7.20.0"
......
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true
}
]
}
\ No newline at end of file
from flask import Flask, request, jsonify
import csv
app = Flask(__name__)
class Crop:
def __init__(self, name, nutrient_requirements):
self.name = name
self.nutrient_requirements = nutrient_requirements
# Function to calculate the suitability score for a crop
def calculate_suitability_score(crop, user_soil_nutrients, optimization_criteria):
score = 0
for nutrient in user_soil_nutrients:
nutrient_value = user_soil_nutrients[nutrient]
required_value = crop.nutrient_requirements.get(nutrient, 0)
weight = optimization_criteria[nutrient]
difference = abs(nutrient_value - required_value)
if required_value == 0:
if difference == 0:
suitability = 100.0
else:
suitability = 0.0
else:
suitability = (1 - difference / required_value) * 100.0
weighted_suitability = suitability * weight
score += weighted_suitability
return score
def convert_user_soil_nutrients(user_soil_nutrients):
return ', '.join(f"{key}: {value}" for key, value in user_soil_nutrients.items())
def append_crop_data(top_crops, user_soil_nutrients, optimization_criteria):
field_names = ['Crop Name', 'N', 'P', 'K']
csv_file_path = 'crop_data.csv'
with open(csv_file_path, mode='a', newline='') as file:
writer = csv.DictWriter(file, fieldnames=field_names)
is_file_empty = file.tell() == 0
if is_file_empty:
writer.writeheader()
user_soil_nutrients_str = convert_user_soil_nutrients(user_soil_nutrients)
for crop in top_crops:
crop_obj = Crop(crop, {})
crop_data = {
'Crop Name': crop,
'N': user_soil_nutrients.get('N', 0),
'P': user_soil_nutrients.get('P', 0),
'K': user_soil_nutrients.get('K', 0)
}
writer.writerow(crop_data)
@app.route('/npk-data', methods=['POST'])
def receive_npk_data():
npk_data = request.get_json()
user_soil_nutrients = npk_data
crops = [
Crop("Soybean", {'N': 0.4, 'P': 0.3, 'K': 0.4}),
Crop("Barley", {'N': 0.5, 'P': 0.4, 'K': 0.5}),
Crop("Wheat", {'N': 0.7, 'P': 0.4, 'K': 0.6}),
Crop("Rice", {'N': 0.1, 'P': 0.2, 'K': 0.1}),
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
}
crop_scores = []
for crop in crops:
suitability_score = calculate_suitability_score(crop, user_soil_nutrients, optimization_criteria)
crop_scores.append((crop, suitability_score))
crop_scores.sort(key=lambda x: x[1], reverse=True)
top_three_crops = []
for crop, score in sorted(crop_scores[:3], key=lambda x: x[1], reverse=True):
top_three_crops.append(crop.name)
append_crop_data(top_three_crops, user_soil_nutrients, optimization_criteria)
response_data = {
'top_crops': top_three_crops,
'highest_score': crop_scores[0][1]
}
return jsonify(response_data)
if __name__ == '__main__':
app.run()
Crop Name,N,P,K
Wheat,0.8,0.5,0.9
Tomato,0.8,0.5,0.9
Cotton,0.8,0.5,0.9
Soybean,0.2,0.1,0.3
Potato,0.2,0.1,0.3
Barley,0.2,0.1,0.3
Wheat,4.46,0.5,5.04
Tomato,4.46,0.5,5.04
Cotton,4.46,0.5,5.04
Wheat,4.46,0.5,5.04
Tomato,4.46,0.5,5.04
Cotton,4.46,0.5,5.04
Wheat,4.46,0.5,5.04
Tomato,4.46,0.5,5.04
Cotton,4.46,0.5,5.04
Wheat,4.46,0.5,5.04
Tomato,4.46,0.5,5.04
Cotton,4.46,0.5,5.04
Potato,0.3,0.2,0.5
Soybean,0.3,0.2,0.5
Barley,0.3,0.2,0.5
Wheat,4.52,0.11,5.38
Cotton,4.52,0.11,5.38
Tomato,4.52,0.11,5.38
Wheat,4.52,0.11,5.38
Cotton,4.52,0.11,5.38
Tomato,4.52,0.11,5.38
Wheat,4.52,0.11,5.38
Cotton,4.52,0.11,5.38
Tomato,4.52,0.11,5.38
Soybean,0,0,0
Barley,0,0,0
Wheat,0,0,0
Wheat,4.52,0.29,5.19
Cotton,4.52,0.29,5.19
Tomato,4.52,0.29,5.19
Wheat,4.57,0.11,5.33
Cotton,4.57,0.11,5.33
Tomato,4.57,0.11,5.33
Tomato,0,0.52,9.48
Wheat,0,0.52,9.48
Cotton,0,0.52,9.48
Wheat,4.52,0.11,5.38
Cotton,4.52,0.11,5.38
Tomato,4.52,0.11,5.38
Wheat,4.52,0.11,5.38
Cotton,4.52,0.11,5.38
Tomato,4.52,0.11,5.38
Wheat,4.52,0.11,5.38
Cotton,4.52,0.11,5.38
Tomato,4.52,0.11,5.38
Soybean,0.5,0.3,0.2
Barley,0.5,0.3,0.2
Maize,0.5,0.3,0.2
Potato,0.3,0.5,0.2
Barley,0.3,0.5,0.2
Tomato,0.3,0.5,0.2
Potato,0.3,0.5,0.2
Barley,0.3,0.5,0.2
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
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')
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)
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
input_data = request.get_json()
nitrogen = input_data['N']
phosphorus = input_data['P']
potassium = input_data['K']
predicted_crop = model.predict([[nitrogen, phosphorus, potassium]])
response = {
'crop': predicted_crop[0],
'accuracy': accuracy
}
return jsonify(response)
if __name__ == '__main__':
app.run()
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