Daksh3 commited on
Commit
d31d29b
·
verified ·
1 Parent(s): 069191d

Create code.py

Browse files
Files changed (1) hide show
  1. code.py +281 -0
code.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
4
+ from sklearn.ensemble import RandomForestClassifier
5
+ import gradio as gr
6
+ import matplotlib.pyplot as plt
7
+ import seaborn as sns
8
+ from io import BytesIO
9
+ import requests
10
+
11
+ # Load and preprocess data
12
+ file_path = '/content/DSV Project Final Spreadsheet.csv'
13
+ data = pd.read_csv(file_path)
14
+
15
+
16
+ # Convert string columns to numeric
17
+ for col in ['N', 'P', 'K']:
18
+ data[col] = pd.to_numeric(data[col], errors='coerce')
19
+
20
+ # Encode categorical variables
21
+ le_soil = LabelEncoder()
22
+ le_season = LabelEncoder()
23
+ data['Soil Type'] = le_soil.fit_transform(data['Soil Type'])
24
+ data['Season'] = le_season.fit_transform(data['Season'])
25
+
26
+ # Features and target variables
27
+ features = ['N', 'P', 'K', 'temperature', 'humidity', 'ph', 'rainfall', 'Soil Moisture Level (%)', 'Soil Type', 'Season']
28
+ X = data[features]
29
+
30
+ # Encode target variables
31
+ le_crop = LabelEncoder()
32
+ le_fertilizer = LabelEncoder()
33
+ le_water_pump = LabelEncoder()
34
+ le_fire = LabelEncoder()
35
+
36
+ y_crop = le_crop.fit_transform(data['Crop Name'])
37
+ y_fertilizer = le_fertilizer.fit_transform(data['Fertilizer Recommendations'])
38
+ y_water_pump = le_water_pump.fit_transform(data['Water Pump Status (ON/OFF)'])
39
+ y_fire = le_fire.fit_transform(data['Fire Detection (YES/NO)'])
40
+
41
+ # Scale features
42
+ scaler = StandardScaler()
43
+ X_scaled = scaler.fit_transform(X)
44
+
45
+ # Create models
46
+ crop_model = RandomForestClassifier(n_estimators=100, random_state=42)
47
+ crop_model.fit(X_scaled, y_crop)
48
+
49
+ fertilizer_model = RandomForestClassifier(n_estimators=100, random_state=42)
50
+ fertilizer_model.fit(X_scaled, y_fertilizer)
51
+
52
+ water_pump_model = RandomForestClassifier(n_estimators=100, random_state=42)
53
+ water_pump_model.fit(X_scaled, y_water_pump)
54
+
55
+ fire_model = RandomForestClassifier(n_estimators=100, random_state=42)
56
+ fire_model.fit(X_scaled, y_fire)
57
+
58
+ # Prediction function for the UI
59
+ def predict_crop(n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season):
60
+ # Check if soil_type and season are within bounds
61
+ if not (0 <= soil_type <= 4):
62
+ return {"Error": "Please enter a valid Soil Type (0 -> Alluvial, 1 -> Black, 2 -> Clayey, 3 -> Laterite, 4 -> Sandy)"}
63
+
64
+ if not (0 <= season <= 3):
65
+ return {"Error": "Please enter a valid Season (0 -> Autumn, 1 -> Spring, 2 -> Summer, 3 -> Winter)"}
66
+
67
+ # Create input array
68
+ input_data = pd.DataFrame([[n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season]],
69
+ columns=features)
70
+ input_scaled = scaler.transform(input_data)
71
+
72
+ # Make predictions
73
+ crop_pred = le_crop.inverse_transform(crop_model.predict(input_scaled))[0]
74
+ fertilizer_pred = le_fertilizer.inverse_transform(fertilizer_model.predict(input_scaled))[0]
75
+ water_pump_pred = le_water_pump.inverse_transform(water_pump_model.predict(input_scaled))[0]
76
+ fire_pred = le_fire.inverse_transform(fire_model.predict(input_scaled))[0]
77
+
78
+ return {
79
+ "Recommended Crop": crop_pred,
80
+ "Fertilizer Recommendation": fertilizer_pred,
81
+ "Water Pump Status": water_pump_pred,
82
+ "Fire Detection": fire_pred
83
+ }
84
+
85
+ # Visualization function
86
+ def visualize_predictions(n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season, show_crop, show_fertilizer, show_water_pump, show_fire):
87
+ input_data = pd.DataFrame([[n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season]],
88
+ columns=features)
89
+ input_scaled = scaler.transform(input_data)
90
+
91
+ # Predictions
92
+ crop_pred = le_crop.inverse_transform(crop_model.predict(input_scaled))[0]
93
+ fertilizer_pred = le_fertilizer.inverse_transform(fertilizer_model.predict(input_scaled))[0]
94
+ water_pump_pred = le_water_pump.inverse_transform(water_pump_model.predict(input_scaled))[0]
95
+ fire_pred = le_fire.inverse_transform(fire_model.predict(input_scaled))[0]
96
+
97
+ # Plot
98
+ fig, ax = plt.subplots()
99
+
100
+ labels = []
101
+ values = []
102
+
103
+ if show_crop:
104
+ labels.append("Recommended Crop")
105
+ values.append(crop_pred)
106
+ if show_fertilizer:
107
+ labels.append("Fertilizer")
108
+ values.append(fertilizer_pred)
109
+ if show_water_pump:
110
+ labels.append("Water Pump Status")
111
+ values.append(water_pump_pred)
112
+ if show_fire:
113
+ labels.append("Fire Detection")
114
+ values.append(fire_pred)
115
+
116
+ ax.barh(labels, [1]*len(labels), color=['#4CAF50', '#FF9800', '#2196F3', '#F44336'])
117
+
118
+ for i, v in enumerate(values):
119
+ ax.text(1.05, i, str(v), color='black', fontweight='bold')
120
+
121
+ ax.set_xlim(0, 1.5)
122
+
123
+ plt.tight_layout()
124
+ return fig
125
+
126
+ # Data Insight function
127
+ def data_insight(visualization_type, predicted_outcome, input1, input2, input3):
128
+ plt.figure(figsize=(12, 10))
129
+
130
+ if visualization_type == "Scatter Plot":
131
+ if predicted_outcome == "Recommended Crop":
132
+ target = data['Crop Name']
133
+ elif predicted_outcome == "Fertilizer Recommendation":
134
+ target = data['Fertilizer Recommendations']
135
+ elif predicted_outcome == "Water Pump Status":
136
+ target = data['Water Pump Status (ON/OFF)']
137
+ else:
138
+ target = data['Fire Detection (YES/NO)']
139
+
140
+ plt.scatter(data[input1], data[input2], c=data[input3], cmap='viridis', alpha=0.6)
141
+ plt.colorbar(label=input3)
142
+ plt.xlabel(input1)
143
+ plt.ylabel(input2)
144
+ plt.title(f"Scatter Plot: {predicted_outcome}\n{input1} vs {input2}, color intensity: {input3}")
145
+
146
+ elif visualization_type == "Correlation Plot":
147
+ numeric_data = data[features + ['Soil Moisture Level (%)']]
148
+ corr = numeric_data.corr()
149
+ sns.heatmap(corr, annot=True, cmap="coolwarm", fmt=".2f")
150
+ plt.title("Correlation Plot of Numeric Features")
151
+
152
+ elif visualization_type == "Pair Plot":
153
+ sns.pairplot(data[features], diag_kind="kde")
154
+ plt.suptitle("Pair Plot of Input Features", y=1.02)
155
+
156
+ elif visualization_type == "Box Plot":
157
+ plt.figure(figsize=(15, 6))
158
+ sns.boxplot(data=data[features])
159
+ plt.title("Box Plot of Input Features")
160
+ plt.xticks(rotation=45)
161
+
162
+ elif visualization_type == "Violin Plot":
163
+ plt.figure(figsize=(15, 6))
164
+ sns.violinplot(data=data[features])
165
+ plt.title("Violin Plot of Input Features")
166
+ plt.xticks(rotation=45)
167
+
168
+ plt.tight_layout()
169
+ return plt
170
+
171
+ # Function to update input options based on predicted outcome
172
+ def update_input_options(predicted_outcome):
173
+ if predicted_outcome == "Recommended Crop":
174
+ return gr.update(choices=features, value=features[0]), gr.update(choices=features, value=features[1]), gr.update(choices=features, value=features[2])
175
+ elif predicted_outcome == "Fertilizer Recommendation":
176
+ options = ['N', 'P', 'K', 'ph']
177
+ return gr.update(choices=options, value=options[0]), gr.update(choices=options, value=options[1]), gr.update(choices=options, value=options[2])
178
+ elif predicted_outcome == "Water Pump Status":
179
+ options = ['Soil Moisture Level (%)', 'temperature', 'humidity', 'Season']
180
+ return gr.update(choices=options, value=options[0]), gr.update(choices=options, value=options[1]), gr.update(choices=options, value=options[2])
181
+ else: # Fire Detection
182
+ options = ['temperature', 'humidity', 'Season']
183
+ return gr.update(choices=options, value=options[0]), gr.update(choices=options, value=options[1]), gr.update(choices=options, value=options[2])
184
+
185
+ # Create the Gradio UI
186
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
187
+ gr.Markdown("# 🌱 Smart Agriculture Prediction System")
188
+
189
+ with gr.Row():
190
+ with gr.Column():
191
+ n = gr.Number(label="Nitrogen (N) [kg/ha]" ,info="Range: 0-100")
192
+ p = gr.Number(label="Phosphorus (P) [kg/ha]" ,info="Range: 30-90")
193
+ k = gr.Number(label="Potassium (K) [kg/ha]" ,info="Range: 15-85")
194
+ temperature = gr.Number(label="Temperature [°C]",info="Range: 15-40")
195
+ with gr.Column():
196
+ humidity = gr.Number(label="Humidity [%]",info="Range: 10-85")
197
+ ph = gr.Number(label="pH Level" ,info="Range: 4-9")
198
+ rainfall = gr.Number(label="Rainfall [mm]",info="Range: 30-300")
199
+ soil_moisture = gr.Number(label="Soil Moisture Level (%)",info="Range: 55-75")
200
+
201
+ soil_type = gr.Number(label="Soil Type [0->Alluvial 1->Black 2->Clayey 3->Laterite 4->Sandy]")
202
+ season = gr.Number(label="Season [0->Autumn 1->Spring 2->Summer 3->Winter]")
203
+
204
+ analyze_btn = gr.Button("Predict", variant="primary")
205
+
206
+ with gr.TabItem("Predictions"):
207
+ prediction_output = gr.JSON()
208
+
209
+ # Visualization options
210
+ with gr.TabItem("Visualization"):
211
+ show_crop = gr.Checkbox(label="Show Recommended Crop", value=True)
212
+ show_fertilizer = gr.Checkbox(label="Show Fertilizer Recommendation", value=True)
213
+ show_water_pump = gr.Checkbox(label="Show Water Pump Status", value=True)
214
+ show_fire = gr.Checkbox(label="Show Fire Detection", value=True)
215
+
216
+ visualize_btn = gr.Button("Visualize", variant="secondary")
217
+ plot_output = gr.Plot()
218
+
219
+ # Data Insight options
220
+ with gr.TabItem("Data Insight"):
221
+ visualization_type = gr.Radio(["Scatter Plot", "Correlation Plot", "Pair Plot", "Box Plot", "Violin Plot"], label="Visualization Type")
222
+ predicted_outcome = gr.Radio(["Recommended Crop", "Fertilizer Recommendation", "Water Pump Status", "Fire Detection"], label="Predicted Outcome", visible=False)
223
+ input1 = gr.Dropdown(choices=features, label="X-axis", visible=False)
224
+ input2 = gr.Dropdown(choices=features, label="Y-axis", visible=False)
225
+ input3 = gr.Dropdown(choices=features, label="Color intensity", visible=False)
226
+
227
+ insight_btn = gr.Button("Generate Insight", variant="secondary")
228
+ insight_plot = gr.Plot()
229
+
230
+ def update_insight_inputs(viz_type):
231
+ if viz_type == "Scatter Plot":
232
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
233
+ else:
234
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
235
+
236
+ visualization_type.change(update_insight_inputs, inputs=[visualization_type], outputs=[predicted_outcome, input1, input2, input3])
237
+ predicted_outcome.change(update_input_options, inputs=[predicted_outcome], outputs=[input1, input2, input3])
238
+
239
+ # Adding examples to the UI
240
+ gr.Examples(
241
+ examples=[
242
+ [90, 60, 50, 25, 65, 6.5, 200, 65, 1, 0], # Example 1: Black soil, Autumn season
243
+ [40, 45, 30, 30, 50, 7.0, 100, 70, 4, 2] # Example 2: Sandy soil, Summer season
244
+ ],
245
+ inputs=[n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season],
246
+ outputs=prediction_output,
247
+ label="Try these examples"
248
+ )
249
+
250
+ analyze_btn.click(predict_crop,
251
+ inputs=[n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season],
252
+ outputs=prediction_output)
253
+
254
+ visualize_btn.click(visualize_predictions,
255
+ inputs=[n, p, k, temperature, humidity, ph, rainfall, soil_moisture, soil_type, season,
256
+ show_crop, show_fertilizer, show_water_pump, show_fire],
257
+ outputs=plot_output)
258
+
259
+ insight_btn.click(data_insight,
260
+ inputs=[visualization_type, predicted_outcome, input1, input2, input3],
261
+ outputs=insight_plot)
262
+
263
+ # Add Footer
264
+ gr.HTML("""
265
+ <div style='
266
+ background-color: #333;
267
+ color: #f0f0f0;
268
+ border-radius: 8px;
269
+ padding: 20px;
270
+ margin-top: 40px;
271
+ text-align: center;
272
+ font-size: 16px;
273
+ font-family: "Helvetica", sans-serif;'>
274
+ <strong>Created By Harsh Jain [23/IT/062] & Daksh Yadav [23/IT/048]</strong>
275
+ <br>
276
+ <span style='font-size: 14px; color: #b0b0b0;'>Smart Agriculture Prediction System</span>
277
+ </div>
278
+ """)
279
+
280
+ if __name__ == "__main__":
281
+ demo.launch()