Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,489 +1,393 @@
|
|
| 1 |
-
from
|
| 2 |
-
|
| 3 |
-
from
|
| 4 |
-
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
import matplotlib
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
"
|
| 37 |
-
|
| 38 |
-
"
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
return
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
"
|
| 221 |
-
"
|
| 222 |
-
"
|
| 223 |
-
"
|
| 224 |
-
"
|
| 225 |
-
"
|
| 226 |
-
}
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
return jsonify({"error": "Invalid input. Please enter a valid crop and district."}), 400
|
| 395 |
-
|
| 396 |
-
yield_col = base_crop_names[crop_input]
|
| 397 |
-
district_yield = yield_df[yield_df['Dist Name'] == district_input]
|
| 398 |
-
district_soil = soil_df[soil_df['Dist Name'] == district_input]
|
| 399 |
-
|
| 400 |
-
if district_yield.empty or district_soil.empty:
|
| 401 |
-
return jsonify({"error": "District data not found."}), 400
|
| 402 |
-
|
| 403 |
-
ts_data = district_yield[['Year', yield_col]].dropna()
|
| 404 |
-
ts_data.columns = ['ds', 'y']
|
| 405 |
-
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 406 |
-
|
| 407 |
-
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 408 |
-
model.fit(ts_data)
|
| 409 |
-
|
| 410 |
-
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 411 |
-
forecast = model.predict(future)
|
| 412 |
-
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 413 |
-
|
| 414 |
-
if predicted_yield > 1000:
|
| 415 |
-
yield_cat = "Highly Recommended Crop"
|
| 416 |
-
color = "green"
|
| 417 |
-
elif predicted_yield > 500:
|
| 418 |
-
yield_cat = "Good Crop"
|
| 419 |
-
color = "yellow"
|
| 420 |
-
elif predicted_yield > 200:
|
| 421 |
-
yield_cat = "Poor Crop"
|
| 422 |
-
color = "orange"
|
| 423 |
-
else:
|
| 424 |
-
yield_cat = "Very Poor Crop"
|
| 425 |
-
color = "red"
|
| 426 |
-
|
| 427 |
-
soil_score = district_soil['SoilHealthScore'].values[0]
|
| 428 |
-
soil_cat = district_soil['Soil_Category'].values[0]
|
| 429 |
-
climate_score = calculate_climate_score(yield_cat, soil_cat)
|
| 430 |
-
|
| 431 |
-
# Calculate Loan Amount
|
| 432 |
-
loan_amount = calculate_loan(crop_input,predicted_yield, yield_cat, soil_cat, climate_score)
|
| 433 |
-
#
|
| 434 |
-
|
| 435 |
-
best_crop = None
|
| 436 |
-
max_yield = 0
|
| 437 |
-
for crop, column in base_crop_names.items():
|
| 438 |
-
ts_data = district_yield[['Year', column]].dropna()
|
| 439 |
-
ts_data.columns = ['ds', 'y']
|
| 440 |
-
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 441 |
-
if len(ts_data) >= 5:
|
| 442 |
-
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 443 |
-
model.fit(ts_data)
|
| 444 |
-
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 445 |
-
forecast = model.predict(future)
|
| 446 |
-
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 447 |
-
if predicted_yield > max_yield:
|
| 448 |
-
max_yield = predicted_yield
|
| 449 |
-
best_crop = crop
|
| 450 |
-
if best_crop:
|
| 451 |
-
print(f"\n{'='*40}")
|
| 452 |
-
print(f"Maximum Yield Prediction for {district_input}:")
|
| 453 |
-
print(f"Best Crop: {best_crop}")
|
| 454 |
-
print(f"Predicted Yield: {max_yield:.2f} Kg/ha (Highly Recommended Crop)")
|
| 455 |
-
print(f"{'='*40}")
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
import json
|
| 459 |
-
|
| 460 |
-
# Extracting data points from the original crop
|
| 461 |
-
ts_data = district_yield[['Year', yield_col]].dropna()
|
| 462 |
-
ts_data.columns = ['ds', 'y']
|
| 463 |
-
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 464 |
-
|
| 465 |
-
ts_data_json = [{"Year": str(year.year), "Yield": yield_value} for year, yield_value in zip(ts_data['ds'], ts_data['y'])]
|
| 466 |
-
|
| 467 |
-
# Extracting data points for the best crop
|
| 468 |
-
best_crop_data = district_yield[['Year', base_crop_names[best_crop]]].dropna()
|
| 469 |
-
best_crop_data.columns = ['ds', 'y']
|
| 470 |
-
best_crop_data['ds'] = pd.to_datetime(best_crop_data['ds'], format='%Y')
|
| 471 |
-
|
| 472 |
-
best_crop_data_json = [{"Year": str(year.year), "Yield": yield_value} for year, yield_value in zip(best_crop_data['ds'], best_crop_data['y'])]
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
#
|
| 476 |
-
result = {
|
| 477 |
-
|
| 478 |
-
"ts_data": ts_data_json,
|
| 479 |
-
"best_crop_data": best_crop_data_json
|
| 480 |
-
|
| 481 |
-
}
|
| 482 |
-
|
| 483 |
-
# result.headers.add("Access-Control-Allow-Origin","*")
|
| 484 |
-
return jsonify(result), 200
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
# if __name__ == '__main__':
|
| 488 |
-
# app.run(host='0.0.0.0' ,debug=True)
|
| 489 |
-
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 2 |
+
from fastapi.responses import HTMLResponse, JSONResponse
|
| 3 |
+
from fastapi.templating import Jinja2Templates
|
| 4 |
+
from fastapi.staticfiles import StaticFiles
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from prophet import Prophet
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
import os
|
| 9 |
+
import matplotlib
|
| 10 |
+
matplotlib.use("Agg")
|
| 11 |
+
from pydantic import BaseModel
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
|
| 16 |
+
# Mount static files
|
| 17 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 18 |
+
|
| 19 |
+
# Templates
|
| 20 |
+
templates = Jinja2Templates(directory="templates")
|
| 21 |
+
|
| 22 |
+
UPLOAD_FOLDER = 'static'
|
| 23 |
+
if not os.path.exists(UPLOAD_FOLDER):
|
| 24 |
+
os.makedirs(UPLOAD_FOLDER)
|
| 25 |
+
|
| 26 |
+
# Load data
|
| 27 |
+
yield_file = 'ICRISAT-District_Level_Data_30_Years.csv'
|
| 28 |
+
soil_file = 'SoilHealthScores_by_District_2.csv'
|
| 29 |
+
|
| 30 |
+
yield_df = pd.read_csv(yield_file)
|
| 31 |
+
soil_df = pd.read_csv(soil_file)
|
| 32 |
+
|
| 33 |
+
# Helper functions
|
| 34 |
+
def get_soil_category(score):
|
| 35 |
+
if score == 0:
|
| 36 |
+
return "No Soil Health Data"
|
| 37 |
+
elif score >= 4.5:
|
| 38 |
+
return "Very Excellent Soil Health"
|
| 39 |
+
elif score >= 4:
|
| 40 |
+
return "Excellent Soil Health"
|
| 41 |
+
elif score >= 3:
|
| 42 |
+
return "Good Soil Health"
|
| 43 |
+
elif score >= 2:
|
| 44 |
+
return "Poor Soil Health"
|
| 45 |
+
else:
|
| 46 |
+
return "Very Poor Soil Health"
|
| 47 |
+
|
| 48 |
+
def calculate_climate_score(yield_cat, soil_cat):
|
| 49 |
+
score_map = {
|
| 50 |
+
"Highly Recommended Crop": 90,
|
| 51 |
+
"Good Crop": 70,
|
| 52 |
+
"Poor Crop": 50,
|
| 53 |
+
"Very Poor Crop": 30,
|
| 54 |
+
"Very Excellent Soil Health": 95,
|
| 55 |
+
"Excellent Soil Health": 85,
|
| 56 |
+
"Good Soil Health": 65,
|
| 57 |
+
"Poor Soil Health": 45,
|
| 58 |
+
"Very Poor Soil Health": 25,
|
| 59 |
+
"No Soil Health Data": 0
|
| 60 |
+
}
|
| 61 |
+
return int((score_map[yield_cat] * 0.6) + (score_map[soil_cat] * 0.4))
|
| 62 |
+
|
| 63 |
+
soil_df['Soil_Category'] = soil_df['SoilHealthScore'].apply(get_soil_category)
|
| 64 |
+
yield_columns = [col for col in yield_df.columns if 'YIELD (Kg per ha)' in col]
|
| 65 |
+
base_crop_names = {col.split(' YIELD')[0]: col for col in yield_columns}
|
| 66 |
+
|
| 67 |
+
def calculate_loan(c, predicted_yield, yield_cat, soil_cat, climate_score):
|
| 68 |
+
crop_base_prices_per_hectare = {
|
| 69 |
+
"RICE": 75000,
|
| 70 |
+
"WHEAT": 65000,
|
| 71 |
+
"KHARIF SORGHUM": 60000,
|
| 72 |
+
"RABI SORGHUM": 62000,
|
| 73 |
+
"SORGHUM": 61000,
|
| 74 |
+
"PEARL MILLET": 50000,
|
| 75 |
+
"MAIZE": 55000,
|
| 76 |
+
"FINGER MILLET": 77000,
|
| 77 |
+
"BARLEY": 48000,
|
| 78 |
+
"CHICKPEA": 90000,
|
| 79 |
+
"PIGEONPEA": 95000,
|
| 80 |
+
"MINOR PULSES": 85000,
|
| 81 |
+
"GROUNDNUT": 110000,
|
| 82 |
+
"SESAMUM": 130000,
|
| 83 |
+
"RAPESEED AND MUSTARD": 100000,
|
| 84 |
+
"SAFFLOWER": 95000,
|
| 85 |
+
"CASTOR": 88000,
|
| 86 |
+
"LINSEED": 90000,
|
| 87 |
+
"SUNFLOWER": 102000,
|
| 88 |
+
"SOYABEAN": 98000,
|
| 89 |
+
"OILSEEDS": 94000,
|
| 90 |
+
"SUGARCANE": 150000,
|
| 91 |
+
"COTTON": 120000
|
| 92 |
+
}
|
| 93 |
+
base_loan = crop_base_prices_per_hectare[c]
|
| 94 |
+
|
| 95 |
+
yield_multiplier = {
|
| 96 |
+
"Highly Recommended Crop": 1.5,
|
| 97 |
+
"Good Crop": 1.2,
|
| 98 |
+
"Poor Crop": 0.8,
|
| 99 |
+
"Very Poor Crop": 0.5
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
soil_multiplier = {
|
| 103 |
+
"Very Excellent Soil Health": 1.5,
|
| 104 |
+
"Excellent Soil Health": 1.3,
|
| 105 |
+
"Good Soil Health": 1.1,
|
| 106 |
+
"Poor Soil Health": 0.9,
|
| 107 |
+
"Very Poor Soil Health": 0.7,
|
| 108 |
+
"No Soil Health Data": 0.5
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
climate_multiplier = climate_score / 100
|
| 112 |
+
loan_amount = base_loan * yield_multiplier[yield_cat] * soil_multiplier[soil_cat] * climate_multiplier
|
| 113 |
+
return round(loan_amount, 2)
|
| 114 |
+
|
| 115 |
+
@app.get("/", response_class=HTMLResponse)
|
| 116 |
+
async def home(request: Request):
|
| 117 |
+
return templates.TemplateResponse("index.html", {"request": request, "crops": base_crop_names.keys()})
|
| 118 |
+
|
| 119 |
+
@app.get("/api/crops")
|
| 120 |
+
async def get_crops():
|
| 121 |
+
return {"crops": list(base_crop_names.keys())}
|
| 122 |
+
|
| 123 |
+
class PredictInput(BaseModel):
|
| 124 |
+
crop: str
|
| 125 |
+
district: str
|
| 126 |
+
land_area: str
|
| 127 |
+
|
| 128 |
+
@app.post("/predict", response_class=HTMLResponse)
|
| 129 |
+
async def predict(request: Request, input_data: PredictInput):
|
| 130 |
+
crop_input = input_data.crop
|
| 131 |
+
district_input = input_data.district
|
| 132 |
+
land_area = input_data.land_area
|
| 133 |
+
|
| 134 |
+
if not crop_input or not district_input or crop_input not in base_crop_names:
|
| 135 |
+
raise HTTPException(status_code=400, detail="Invalid input. Please enter a valid crop and district.")
|
| 136 |
+
|
| 137 |
+
yield_col = base_crop_names[crop_input]
|
| 138 |
+
district_yield = yield_df[yield_df['Dist Name'] == district_input]
|
| 139 |
+
district_soil = soil_df[soil_df['Dist Name'] == district_input]
|
| 140 |
+
|
| 141 |
+
if district_yield.empty or district_soil.empty:
|
| 142 |
+
raise HTTPException(status_code=400, detail="District data not found.")
|
| 143 |
+
|
| 144 |
+
ts_data = district_yield[['Year', yield_col]].dropna()
|
| 145 |
+
ts_data.columns = ['ds', 'y']
|
| 146 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 147 |
+
|
| 148 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 149 |
+
model.fit(ts_data)
|
| 150 |
+
|
| 151 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 152 |
+
forecast = model.predict(future)
|
| 153 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 154 |
+
|
| 155 |
+
if predicted_yield > 1000:
|
| 156 |
+
yield_cat = "Highly Recommended Crop"
|
| 157 |
+
color = "green"
|
| 158 |
+
elif predicted_yield > 500:
|
| 159 |
+
yield_cat = "Good Crop"
|
| 160 |
+
color = "yellow"
|
| 161 |
+
elif predicted_yield > 200:
|
| 162 |
+
yield_cat = "Poor Crop"
|
| 163 |
+
color = "orange"
|
| 164 |
+
else:
|
| 165 |
+
yield_cat = "Very Poor Crop"
|
| 166 |
+
color = "red"
|
| 167 |
+
|
| 168 |
+
soil_score = district_soil['SoilHealthScore'].values[0]
|
| 169 |
+
soil_cat = district_soil['Soil_Category'].values[0]
|
| 170 |
+
climate_score = calculate_climate_score(yield_cat, soil_cat)
|
| 171 |
+
|
| 172 |
+
plt.figure(figsize=(10, 5))
|
| 173 |
+
model.plot(forecast)
|
| 174 |
+
image_path = os.path.join(UPLOAD_FOLDER, "forecast.png")
|
| 175 |
+
plt.savefig(image_path)
|
| 176 |
+
plt.close()
|
| 177 |
+
|
| 178 |
+
loan_amount = calculate_loan(crop_input, predicted_yield, yield_cat, soil_cat, climate_score)
|
| 179 |
+
|
| 180 |
+
best_crop = None
|
| 181 |
+
max_yield = 0
|
| 182 |
+
for crop, column in base_crop_names.items():
|
| 183 |
+
ts_data = district_yield[['Year', column]].dropna()
|
| 184 |
+
ts_data.columns = ['ds', 'y']
|
| 185 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 186 |
+
if len(ts_data) >= 5:
|
| 187 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 188 |
+
model.fit(ts_data)
|
| 189 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 190 |
+
forecast = model.predict(future)
|
| 191 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 192 |
+
if predicted_yield > max_yield:
|
| 193 |
+
max_yield = predicted_yield
|
| 194 |
+
best_crop = crop
|
| 195 |
+
|
| 196 |
+
plt.figure(figsize=(10, 5))
|
| 197 |
+
ts_data = district_yield[['Year', yield_col]].dropna()
|
| 198 |
+
ts_data.columns = ['ds', 'y']
|
| 199 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 200 |
+
plt.plot(ts_data['ds'], ts_data['y'], label=f'{crop_input} Yield')
|
| 201 |
+
|
| 202 |
+
best_crop_data = district_yield[['Year', base_crop_names[best_crop]]].dropna()
|
| 203 |
+
best_crop_data.columns = ['ds', 'y']
|
| 204 |
+
best_crop_data['ds'] = pd.to_datetime(best_crop_data['ds'], format='%Y')
|
| 205 |
+
plt.plot(best_crop_data['ds'], best_crop_data['y'], label=f'{best_crop} Yield', linestyle='--')
|
| 206 |
+
|
| 207 |
+
plt.xlabel('Year')
|
| 208 |
+
plt.ylabel('Yield (Kg/ha)')
|
| 209 |
+
plt.title(f"Yield Comparison for {crop_input} and Best Crop ({best_crop}) in {district_input}")
|
| 210 |
+
plt.legend()
|
| 211 |
+
image_path2 = os.path.join(UPLOAD_FOLDER, "forecast2.png")
|
| 212 |
+
plt.grid(True)
|
| 213 |
+
plt.savefig(image_path2)
|
| 214 |
+
plt.close()
|
| 215 |
+
|
| 216 |
+
result = {
|
| 217 |
+
"crop": crop_input,
|
| 218 |
+
"district": district_input,
|
| 219 |
+
"predicted_yield": f"{round(predicted_yield, 2)}Kg/ha",
|
| 220 |
+
"loan_amount": float(loan_amount) * float(land_area),
|
| 221 |
+
"best_crop": best_crop,
|
| 222 |
+
"yield_cat": yield_cat,
|
| 223 |
+
"color": color,
|
| 224 |
+
"soil_health": soil_cat,
|
| 225 |
+
"climate_score": climate_score
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
return templates.TemplateResponse("index.html", {
|
| 229 |
+
"request": request,
|
| 230 |
+
"result": result,
|
| 231 |
+
"image_path": image_path,
|
| 232 |
+
"image_path2": image_path2,
|
| 233 |
+
"crops": base_crop_names.keys()
|
| 234 |
+
})
|
| 235 |
+
|
| 236 |
+
@app.get("/api/predict")
|
| 237 |
+
async def api_predict(crop: str, district: str, land: str):
|
| 238 |
+
if not crop or not district:
|
| 239 |
+
raise HTTPException(status_code=400, detail="Missing crop or district in request.")
|
| 240 |
+
return await predict2(crop, district, land)
|
| 241 |
+
|
| 242 |
+
async def predict2(crop_input: str, district_input: str, area: str):
|
| 243 |
+
if not crop_input or not district_input or crop_input not in base_crop_names:
|
| 244 |
+
raise HTTPException(status_code=400, detail="Invalid input. Please enter a valid crop and district.")
|
| 245 |
+
|
| 246 |
+
yield_col = base_crop_names[crop_input]
|
| 247 |
+
district_yield = yield_df[yield_df['Dist Name'] == district_input]
|
| 248 |
+
district_soil = soil_df[soil_df['Dist Name'] == district_input]
|
| 249 |
+
|
| 250 |
+
if district_yield.empty or district_soil.empty:
|
| 251 |
+
raise HTTPException(status_code=400, detail="District data not found.")
|
| 252 |
+
|
| 253 |
+
ts_data = district_yield[['Year', yield_col]].dropna()
|
| 254 |
+
ts_data.columns = ['ds', 'y']
|
| 255 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 256 |
+
|
| 257 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 258 |
+
model.fit(ts_data)
|
| 259 |
+
|
| 260 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 261 |
+
forecast = model.predict(future)
|
| 262 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 263 |
+
|
| 264 |
+
if predicted_yield > 1000:
|
| 265 |
+
yield_cat = "Highly Recommended Crop"
|
| 266 |
+
color = "green"
|
| 267 |
+
elif predicted_yield > 500:
|
| 268 |
+
yield_cat = "Good Crop"
|
| 269 |
+
color = "yellow"
|
| 270 |
+
elif predicted_yield > 200:
|
| 271 |
+
yield_cat = "Poor Crop"
|
| 272 |
+
color = "orange"
|
| 273 |
+
else:
|
| 274 |
+
yield_cat = "Very Poor Crop"
|
| 275 |
+
color = "red"
|
| 276 |
+
|
| 277 |
+
soil_score = district_soil['SoilHealthScore'].values[0]
|
| 278 |
+
soil_cat = district_soil['Soil_Category'].values[0]
|
| 279 |
+
climate_score = calculate_climate_score(yield_cat, soil_cat)
|
| 280 |
+
|
| 281 |
+
loan_amount = calculate_loan(crop_input, predicted_yield, yield_cat, soil_cat, climate_score)
|
| 282 |
+
|
| 283 |
+
best_crop = None
|
| 284 |
+
max_yield = 0
|
| 285 |
+
for crop, column in base_crop_names.items():
|
| 286 |
+
ts_data = district_yield[['Year', column]].dropna()
|
| 287 |
+
ts_data.columns = ['ds', 'y']
|
| 288 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 289 |
+
if len(ts_data) >= 5:
|
| 290 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 291 |
+
model.fit(ts_data)
|
| 292 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 293 |
+
forecast = model.predict(future)
|
| 294 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 295 |
+
if predicted_yield > max_yield:
|
| 296 |
+
max_yield = predicted_yield
|
| 297 |
+
best_crop = crop
|
| 298 |
+
|
| 299 |
+
top_crops = []
|
| 300 |
+
crop_yields = []
|
| 301 |
+
for crop, column in base_crop_names.items():
|
| 302 |
+
ts_data = district_yield[['Year', column]].dropna()
|
| 303 |
+
ts_data.columns = ['ds', 'y']
|
| 304 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 305 |
+
if len(ts_data) >= 5:
|
| 306 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 307 |
+
model.fit(ts_data)
|
| 308 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 309 |
+
forecast = model.predict(future)
|
| 310 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 311 |
+
crop_yields.append((crop, predicted_yield))
|
| 312 |
+
|
| 313 |
+
top_crops = sorted(crop_yields, key=lambda x: x[1], reverse=True)[:3]
|
| 314 |
+
top_crops_array = [crop for crop, yield_value in top_crops]
|
| 315 |
+
|
| 316 |
+
ts_data_json = [{"Year": str(year.year), "Yield": yield_value} for year, yield_value in zip(ts_data['ds'], ts_data['y'])]
|
| 317 |
+
best_crop_data = district_yield[['Year', base_crop_names[best_crop]]].dropna()
|
| 318 |
+
best_crop_data.columns = ['ds', 'y']
|
| 319 |
+
best_crop_data['ds'] = pd.to_datetime(best_crop_data['ds'], format='%Y')
|
| 320 |
+
best_crop_data_json = [{"Year": str(year.year), "Yield": yield_value} for year, yield_value in zip(best_crop_data['ds'], best_crop_data['y'])]
|
| 321 |
+
|
| 322 |
+
result = {
|
| 323 |
+
"crop": crop_input,
|
| 324 |
+
"district": district_input,
|
| 325 |
+
"predicted_yield": f"{round(predicted_yield, 2)} Kg/ha",
|
| 326 |
+
"yield_category": yield_cat,
|
| 327 |
+
"best_crop": top_crops_array,
|
| 328 |
+
"soil_health": soil_cat,
|
| 329 |
+
"score": climate_score,
|
| 330 |
+
"loan_amount": f"{float(loan_amount)*float(area)}",
|
| 331 |
+
}
|
| 332 |
+
return result
|
| 333 |
+
|
| 334 |
+
@app.get("/api/map")
|
| 335 |
+
async def api_map(crop: str, district: str, land: str):
|
| 336 |
+
if not crop or not district:
|
| 337 |
+
raise HTTPException(status_code=400, detail="Missing crop or district in request.")
|
| 338 |
+
return await map_data(crop, district, land)
|
| 339 |
+
|
| 340 |
+
async def map_data(crop_input: str, district_input: str, area: str):
|
| 341 |
+
if not crop_input or not district_input or crop_input not in base_crop_names:
|
| 342 |
+
raise HTTPException(status_code=400, detail="Invalid input. Please enter a valid crop and district.")
|
| 343 |
+
|
| 344 |
+
yield_col = base_crop_names[crop_input]
|
| 345 |
+
district_yield = yield_df[yield_df['Dist Name'] == district_input]
|
| 346 |
+
district_soil = soil_df[soil_df['Dist Name'] == district_input]
|
| 347 |
+
|
| 348 |
+
if district_yield.empty or district_soil.empty:
|
| 349 |
+
raise HTTPException(status_code=400, detail="District data not found.")
|
| 350 |
+
|
| 351 |
+
ts_data = district_yield[['Year', yield_col]].dropna()
|
| 352 |
+
ts_data.columns = ['ds', 'y']
|
| 353 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 354 |
+
|
| 355 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 356 |
+
model.fit(ts_data)
|
| 357 |
+
|
| 358 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 359 |
+
forecast = model.predict(future)
|
| 360 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 361 |
+
|
| 362 |
+
best_crop = None
|
| 363 |
+
max_yield = 0
|
| 364 |
+
for crop, column in base_crop_names.items():
|
| 365 |
+
ts_data = district_yield[['Year', column]].dropna()
|
| 366 |
+
ts_data.columns = ['ds', 'y']
|
| 367 |
+
ts_data['ds'] = pd.to_datetime(ts_data['ds'], format='%Y')
|
| 368 |
+
if len(ts_data) >= 5:
|
| 369 |
+
model = Prophet(yearly_seasonality=True, growth='flat')
|
| 370 |
+
model.fit(ts_data)
|
| 371 |
+
future = model.make_future_dataframe(periods=1, freq='YS')
|
| 372 |
+
forecast = model.predict(future)
|
| 373 |
+
predicted_yield = max(forecast.iloc[-1]['yhat'], 0)
|
| 374 |
+
if predicted_yield > max_yield:
|
| 375 |
+
max_yield = predicted_yield
|
| 376 |
+
best_crop = crop
|
| 377 |
+
|
| 378 |
+
ts_data_json = [{"Year": str(year.year), "Yield": yield_value} for year, yield_value in zip(ts_data['ds'], ts_data['y'])]
|
| 379 |
+
best_crop_data = district_yield[['Year', base_crop_names[best_crop]]].dropna()
|
| 380 |
+
best_crop_data.columns = ['ds', 'y']
|
| 381 |
+
best_crop_data['ds'] = pd.to_datetime(best_crop_data['ds'], format='%Y')
|
| 382 |
+
best_crop_data_json = [{"Year": str(year.year), "Yield": yield_value} for year, yield_value in zip(best_crop_data['ds'], best_crop_data['y'])]
|
| 383 |
+
|
| 384 |
+
result = {
|
| 385 |
+
"ts_data": ts_data_json,
|
| 386 |
+
"best_crop_data": best_crop_data_json
|
| 387 |
+
}
|
| 388 |
+
return result
|
| 389 |
+
|
| 390 |
+
# To run the application:
|
| 391 |
+
# if __name__ == "__main__":
|
| 392 |
+
# import uvicorn
|
| 393 |
+
# uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|