samarth-kamble commited on
Commit
2efb262
·
verified ·
1 Parent(s): 77f0c07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -63
app.py CHANGED
@@ -1,17 +1,99 @@
1
- from flask import Flask, render_template, request
2
- import joblib
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import pandas as pd
4
- import google.generativeai as genai
5
  import os
 
6
 
 
 
 
7
 
8
- app = Flask(__name__)
9
-
10
- # Load the trained Random Forest models
11
- rf_ferti_name = joblib.load('rf_ferti_name.pkl')
12
- rf_ferti_value = joblib.load('rf_ferti_value.pkl')
13
-
14
- # Manually define the encodings based on the provided dictionaries
15
  soil_type_encodings = {'Black': 0, 'Clayey': 1, 'Loamy': 2, 'Red': 3, 'Sandy': 4}
16
  crop_type_encodings = {'Barley': 0, 'Cotton': 1, 'Ground Nuts': 2, 'Maize': 3, 'Millets': 4,
17
  'Oil seeds': 5, 'Other Variety': 6, 'Paddy': 7, 'Pulses': 8, 'Sugarcane': 9,
@@ -22,62 +104,75 @@ fertilizer_name_encodings = {'10-26-26': 0, '14-35-14': 1, '15-15-15': 2, '17-17
22
  'Potassium chloride/Muriate of potash (MOP)': 13, 'Potassium sulfate/Sulfate of potash (SOP)': 14,
23
  'Rock phosphate (RP)': 15, 'Single superphosphate (SSP)': 16, 'Triple superphosphate (TSP)': 17,
24
  'Urea': 18, 'Zinc sulfate': 19}
 
25
 
26
-
27
- # AI configuration
28
- api_key=os.getenv('GEMINI_API')
29
- genai.configure(api_key=api_key)
30
  model = genai.GenerativeModel("gemini-1.5-flash")
31
 
32
- def generate_ai_suggestions(pred_fertilizer_name):
33
  prompt = (
34
- f"For {pred_fertilizer_name} fertlizer, generate 3-4 sentences each on a new line, note text shoudl be jsutidied should not contian anyu special character"
 
35
  )
36
  response = model.generate_content(prompt)
37
- return response.text
38
-
39
-
40
-
41
- @app.route('/', methods=['GET', 'POST'])
42
- def index():
43
- if request.method == 'POST':
44
- # Retrieve form data
45
- temperature = float(request.form['temperature'])
46
- humidity = float(request.form['humidity'])
47
- moisture = float(request.form['moisture'])
48
- soil_type = request.form['soil_type']
49
- crop_type = request.form['crop_type']
50
- nitrogen = float(request.form['nitrogen'])
51
- potassium = float(request.form['potassium'])
52
- phosphorous = float(request.form['phosphorous'])
53
-
54
- # Encode categorical data
55
- soil_type_encoded = soil_type_encodings.get(soil_type, -1)
56
- crop_type_encoded = crop_type_encodings.get(crop_type, -1)
57
-
58
- # Create a DataFrame for the input
59
- user_input = pd.DataFrame({
60
- 'Temperature': [temperature],
61
- 'Humidity': [humidity],
62
- 'Moisture': [moisture],
63
- 'Nitrogen': [nitrogen],
64
- 'Potassium': [potassium],
65
- 'Phosphorous': [phosphorous],
66
- 'Soil Type': [soil_type_encoded],
67
- 'Crop Type': [crop_type_encoded]
68
- })
69
-
70
- # Predict Fertilizer Name
71
- pred_fertilizer_name = rf_ferti_name.predict(user_input)[0]
72
- pred_fertilizer_name = [name for name, value in fertilizer_name_encodings.items() if value == pred_fertilizer_name][0]
73
-
74
- # Predict Fertilizer Quantity
75
- pred_fertilizer_qty = rf_ferti_value.predict(user_input)[0]
76
- pred_info = generate_ai_suggestions(pred_fertilizer_name)
77
-
78
- return render_template('index.html', prediction=True, fertilizer_name=pred_fertilizer_name,
79
- fertilizer_qty=pred_fertilizer_qty, optimal_usage=pred_fertilizer_qty,pred_info=pred_info)
80
- return render_template('index.html', prediction=False)
81
-
82
- if __name__ == '__main__':
83
- app.run(port=7860,host='0.0.0.0')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from flask import Flask, render_template, request
2
+ # import joblib
3
+ # import pandas as pd
4
+ # import google.generativeai as genai
5
+ # import os
6
+
7
+
8
+ # app = Flask(__name__)
9
+
10
+ # # Load the trained Random Forest models
11
+ # rf_ferti_name = joblib.load('rf_ferti_name.pkl')
12
+ # rf_ferti_value = joblib.load('rf_ferti_value.pkl')
13
+
14
+ # # Manually define the encodings based on the provided dictionaries
15
+ # soil_type_encodings = {'Black': 0, 'Clayey': 1, 'Loamy': 2, 'Red': 3, 'Sandy': 4}
16
+ # crop_type_encodings = {'Barley': 0, 'Cotton': 1, 'Ground Nuts': 2, 'Maize': 3, 'Millets': 4,
17
+ # 'Oil seeds': 5, 'Other Variety': 6, 'Paddy': 7, 'Pulses': 8, 'Sugarcane': 9,
18
+ # 'Tobacco': 10, 'Wheat': 11}
19
+ # fertilizer_name_encodings = {'10-26-26': 0, '14-35-14': 1, '15-15-15': 2, '17-17-17': 3, '20-20': 4,
20
+ # '20-20-20': 5, '28-28': 6, 'Ammonium sulfate': 7, 'Biofertilizer (e.g., Rhizobium)': 8,
21
+ # 'Calcium nitrate': 9, 'DAP': 10, 'Ferrous sulfate': 11, 'Magnesium sulfate': 12,
22
+ # 'Potassium chloride/Muriate of potash (MOP)': 13, 'Potassium sulfate/Sulfate of potash (SOP)': 14,
23
+ # 'Rock phosphate (RP)': 15, 'Single superphosphate (SSP)': 16, 'Triple superphosphate (TSP)': 17,
24
+ # 'Urea': 18, 'Zinc sulfate': 19}
25
+
26
+
27
+ # # AI configuration
28
+ # api_key=os.getenv('GEMINI_API')
29
+ # genai.configure(api_key=api_key)
30
+ # model = genai.GenerativeModel("gemini-1.5-flash")
31
+
32
+ # def generate_ai_suggestions(pred_fertilizer_name):
33
+ # prompt = (
34
+ # f"For {pred_fertilizer_name} fertlizer, generate 3-4 sentences each on a new line, note text shoudl be jsutidied should not contian anyu special character"
35
+ # )
36
+ # response = model.generate_content(prompt)
37
+ # return response.text
38
+
39
+
40
+
41
+ # @app.route('/', methods=['GET', 'POST'])
42
+ # def index():
43
+ # if request.method == 'POST':
44
+ # # Retrieve form data
45
+ # temperature = float(request.form['temperature'])
46
+ # humidity = float(request.form['humidity'])
47
+ # moisture = float(request.form['moisture'])
48
+ # soil_type = request.form['soil_type']
49
+ # crop_type = request.form['crop_type']
50
+ # nitrogen = float(request.form['nitrogen'])
51
+ # potassium = float(request.form['potassium'])
52
+ # phosphorous = float(request.form['phosphorous'])
53
+
54
+ # # Encode categorical data
55
+ # soil_type_encoded = soil_type_encodings.get(soil_type, -1)
56
+ # crop_type_encoded = crop_type_encodings.get(crop_type, -1)
57
+
58
+ # # Create a DataFrame for the input
59
+ # user_input = pd.DataFrame({
60
+ # 'Temperature': [temperature],
61
+ # 'Humidity': [humidity],
62
+ # 'Moisture': [moisture],
63
+ # 'Nitrogen': [nitrogen],
64
+ # 'Potassium': [potassium],
65
+ # 'Phosphorous': [phosphorous],
66
+ # 'Soil Type': [soil_type_encoded],
67
+ # 'Crop Type': [crop_type_encoded]
68
+ # })
69
+
70
+ # # Predict Fertilizer Name
71
+ # pred_fertilizer_name = rf_ferti_name.predict(user_input)[0]
72
+ # pred_fertilizer_name = [name for name, value in fertilizer_name_encodings.items() if value == pred_fertilizer_name][0]
73
+
74
+ # # Predict Fertilizer Quantity
75
+ # pred_fertilizer_qty = rf_ferti_value.predict(user_input)[0]
76
+ # pred_info = generate_ai_suggestions(pred_fertilizer_name)
77
+
78
+ # return render_template('index.html', prediction=True, fertilizer_name=pred_fertilizer_name,
79
+ # fertilizer_qty=pred_fertilizer_qty, optimal_usage=pred_fertilizer_qty,pred_info=pred_info)
80
+ # return render_template('index.html', prediction=False)
81
+
82
+ # if __name__ == '__main__':
83
+ # app.run(port=7860,host='0.0.0.0')
84
+
85
+
86
+ import gradio as gr
87
  import pandas as pd
88
+ import joblib
89
  import os
90
+ import google.generativeai as genai
91
 
92
+ # Load models
93
+ rf_ferti_name = joblib.load("rf_ferti_name.pkl")
94
+ rf_ferti_value = joblib.load("rf_ferti_value.pkl")
95
 
96
+ # Encodings
 
 
 
 
 
 
97
  soil_type_encodings = {'Black': 0, 'Clayey': 1, 'Loamy': 2, 'Red': 3, 'Sandy': 4}
98
  crop_type_encodings = {'Barley': 0, 'Cotton': 1, 'Ground Nuts': 2, 'Maize': 3, 'Millets': 4,
99
  'Oil seeds': 5, 'Other Variety': 6, 'Paddy': 7, 'Pulses': 8, 'Sugarcane': 9,
 
104
  'Potassium chloride/Muriate of potash (MOP)': 13, 'Potassium sulfate/Sulfate of potash (SOP)': 14,
105
  'Rock phosphate (RP)': 15, 'Single superphosphate (SSP)': 16, 'Triple superphosphate (TSP)': 17,
106
  'Urea': 18, 'Zinc sulfate': 19}
107
+ inv_fert_name_encodings = {v: k for k, v in fertilizer_name_encodings.items()}
108
 
109
+ # Gemini AI config
110
+ genai.configure(api_key=os.getenv("GEMINI_API"))
 
 
111
  model = genai.GenerativeModel("gemini-1.5-flash")
112
 
113
+ def generate_ai_suggestions(fertilizer_name):
114
  prompt = (
115
+ f"For {fertilizer_name} fertilizer, generate 34 short suggestions. "
116
+ "Each on a new line. Text should be justified and not contain special characters."
117
  )
118
  response = model.generate_content(prompt)
119
+ return response.text.strip()
120
+
121
+ def predict_fertilizer(temp, humidity, moisture, soil_type, crop_type, nitrogen, potassium, phosphorous):
122
+ # Encode categorical
123
+ soil_encoded = soil_type_encodings.get(soil_type, -1)
124
+ crop_encoded = crop_type_encodings.get(crop_type, -1)
125
+
126
+ # Prepare input
127
+ input_df = pd.DataFrame([{
128
+ "Temperature": temp,
129
+ "Humidity": humidity,
130
+ "Moisture": moisture,
131
+ "Nitrogen": nitrogen,
132
+ "Potassium": potassium,
133
+ "Phosphorous": phosphorous,
134
+ "Soil Type": soil_encoded,
135
+ "Crop Type": crop_encoded,
136
+ }])
137
+
138
+ # Predict fertilizer name
139
+ pred_name_encoded = rf_ferti_name.predict(input_df)[0]
140
+ fert_name = inv_fert_name_encodings[pred_name_encoded]
141
+
142
+ # Predict quantity
143
+ fert_qty = rf_ferti_value.predict(input_df)[0]
144
+
145
+ # AI suggestions
146
+ ai_info = generate_ai_suggestions(fert_name)
147
+
148
+ return (
149
+ f"🌾 Recommended Fertilizer: **{fert_name}**\n"
150
+ f"📦 Estimated Quantity: **{fert_qty:.2f} units**\n\n"
151
+ f"📘 AI Suggestions:\n{ai_info}"
152
+ )
153
+
154
+ # Gradio UI
155
+ soil_list = list(soil_type_encodings.keys())
156
+ crop_list = list(crop_type_encodings.keys())
157
+
158
+ interface = gr.Interface(
159
+ fn=predict_fertilizer,
160
+ inputs=[
161
+ gr.Slider(0, 50, label="Temperature (°C)"),
162
+ gr.Slider(0, 100, label="Humidity (%)"),
163
+ gr.Slider(0, 100, label="Moisture (%)"),
164
+ gr.Dropdown(soil_list, label="Soil Type"),
165
+ gr.Dropdown(crop_list, label="Crop Type"),
166
+ gr.Number(label="Nitrogen"),
167
+ gr.Number(label="Potassium"),
168
+ gr.Number(label="Phosphorous"),
169
+ ],
170
+ outputs=gr.Markdown(label="Result"),
171
+ title="🌿 Fertilizer Recommendation System",
172
+ description="Enter environmental and soil parameters to get the optimal fertilizer recommendation and AI-generated suggestions.",
173
+ )
174
+
175
+ # API Launch
176
+ if __name__ == "__main__":
177
+ interface.launch()
178
+