Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import joblib
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from fastapi import FastAPI, HTTPException
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
# Load the trained model
|
| 8 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 9 |
+
model_path = os.path.join(script_dir, "district_yield_pipeline.pkl")
|
| 10 |
+
|
| 11 |
+
model_loaded = False
|
| 12 |
+
model = None
|
| 13 |
+
|
| 14 |
+
if os.path.exists(model_path):
|
| 15 |
+
try:
|
| 16 |
+
model = joblib.load(model_path)
|
| 17 |
+
model_loaded = True
|
| 18 |
+
print("Model loaded successfully!")
|
| 19 |
+
except Exception as e:
|
| 20 |
+
print(f"Error loading model file: {e}")
|
| 21 |
+
else:
|
| 22 |
+
print(f"Model file not found at: {model_path}")
|
| 23 |
+
print(f"Available files: {os.listdir(script_dir)}")
|
| 24 |
+
|
| 25 |
+
class PredictionInput(BaseModel):
|
| 26 |
+
crop: str
|
| 27 |
+
season: str
|
| 28 |
+
state: str
|
| 29 |
+
area: float
|
| 30 |
+
annual_rainfall: float
|
| 31 |
+
fertilizer: float
|
| 32 |
+
pesticide: float
|
| 33 |
+
year: int
|
| 34 |
+
|
| 35 |
+
class PredictionOutput(BaseModel):
|
| 36 |
+
prediction: str
|
| 37 |
+
insights: str
|
| 38 |
+
|
| 39 |
+
app = FastAPI(
|
| 40 |
+
title="Crop Yield Prediction API",
|
| 41 |
+
description="API for predicting crop yields based on agricultural parameters",
|
| 42 |
+
version="1.0.0"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
@app.get("/health")
|
| 46 |
+
def health_check():
|
| 47 |
+
return {"status": "healthy", "model_loaded": model_loaded}
|
| 48 |
+
|
| 49 |
+
@app.post("/predict", response_model=PredictionOutput)
|
| 50 |
+
def predict(input_data: PredictionInput):
|
| 51 |
+
if not model_loaded:
|
| 52 |
+
raise HTTPException(status_code=500, detail="Model not loaded. Please check if the model file exists.")
|
| 53 |
+
|
| 54 |
+
try:
|
| 55 |
+
# Create input dataframe
|
| 56 |
+
df = pd.DataFrame({
|
| 57 |
+
'Crop': [input_data.crop],
|
| 58 |
+
'Season': [input_data.season],
|
| 59 |
+
'State': [input_data.state],
|
| 60 |
+
'Area': [input_data.area],
|
| 61 |
+
'Annual_Rainfall': [input_data.annual_rainfall],
|
| 62 |
+
'Fertilizer': [input_data.fertilizer],
|
| 63 |
+
'Pesticide': [input_data.pesticide],
|
| 64 |
+
'Year': [input_data.year]
|
| 65 |
+
})
|
| 66 |
+
|
| 67 |
+
# Make prediction (import numpy here if needed, but not required)
|
| 68 |
+
import numpy as np
|
| 69 |
+
prediction = model.predict(df)[0]
|
| 70 |
+
|
| 71 |
+
# Format output
|
| 72 |
+
result_text = f"""
|
| 73 |
+
### πΎ Prediction Results
|
| 74 |
+
|
| 75 |
+
**Predicted Crop Yield:** `{prediction:.2f}` tonnes/hectare
|
| 76 |
+
|
| 77 |
+
---
|
| 78 |
+
|
| 79 |
+
**Input Summary:**
|
| 80 |
+
- π± **Crop:** {input_data.crop}
|
| 81 |
+
- π
**Season:** {input_data.season}
|
| 82 |
+
- π **State:** {input_data.state}
|
| 83 |
+
- π **Area:** {input_data.area} hectares
|
| 84 |
+
- π§οΈ **Annual Rainfall:** {input_data.annual_rainfall} mm
|
| 85 |
+
- π **Fertilizer:** {input_data.fertilizer} kg
|
| 86 |
+
- π§ͺ **Pesticide:** {input_data.pesticide} kg
|
| 87 |
+
- π
**Year:** {input_data.year}
|
| 88 |
+
|
| 89 |
+
---
|
| 90 |
+
|
| 91 |
+
**Yield Category:**
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
# Add yield interpretation
|
| 95 |
+
if prediction < 1:
|
| 96 |
+
result_text += "β οΈ **Low Yield** - Consider improving farming practices"
|
| 97 |
+
elif prediction < 5:
|
| 98 |
+
result_text += "β
**Moderate Yield** - Good performance"
|
| 99 |
+
elif prediction < 50:
|
| 100 |
+
result_text += "π **High Yield** - Excellent performance"
|
| 101 |
+
else:
|
| 102 |
+
result_text += "π **Exceptional Yield** - Outstanding performance"
|
| 103 |
+
|
| 104 |
+
# Additional insights
|
| 105 |
+
insights = f"""
|
| 106 |
+
### π‘ Insights & Recommendations
|
| 107 |
+
|
| 108 |
+
Based on the prediction of **{prediction:.2f} tonnes/hectare**:
|
| 109 |
+
|
| 110 |
+
1. **Water Management:** With {input_data.annual_rainfall} mm of rainfall, ensure proper irrigation during dry spells.
|
| 111 |
+
2. **Nutrient Balance:** Current fertilizer usage is {input_data.fertilizer} kg. Monitor soil health regularly.
|
| 112 |
+
3. **Pest Control:** Pesticide usage at {input_data.pesticide} kg. Follow integrated pest management practices.
|
| 113 |
+
4. **Area Optimization:** Managing {input_data.area} hectares requires strategic planning for maximum efficiency.
|
| 114 |
+
|
| 115 |
+
**Note:** This prediction is based on historical data and machine learning models.
|
| 116 |
+
Actual yields may vary based on weather conditions, soil quality, and farming practices.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
return PredictionOutput(prediction=result_text, insights=insights)
|
| 120 |
+
|
| 121 |
+
except Exception as e:
|
| 122 |
+
raise HTTPException(status_code=500, detail=f"Error making prediction: {str(e)}")
|