MHamzaShahid commited on
Commit
7312c7f
Β·
verified Β·
1 Parent(s): c724aea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -126
app.py CHANGED
@@ -1,133 +1,45 @@
1
- import gradio as gr
2
  from fastapi import FastAPI
3
- import pandas as pd
4
- import numpy as np
5
- import os
6
  import joblib
7
- import warnings
8
- warnings.filterwarnings('ignore')
9
-
10
- app = FastAPI(title="Crop Yield Predictor API")
11
-
12
- # ======== MODEL LOADING WITH JOBLIB ========
13
- def load_model_properly():
14
- model_path = 'CropYieldPredictor_COMPATIBLE.joblib'
15
-
16
- if not os.path.exists(model_path):
17
- return None, f"❌ Model file '{model_path}' not found!"
18
-
19
- try:
20
- model = joblib.load(model_path)
21
- return model, "βœ… Model loaded successfully with joblib!"
22
- except Exception as e:
23
- return None, f"❌ Loading failed: {str(e)}"
24
-
25
- model, load_status = load_model_properly()
26
- print(load_status)
27
 
28
- # ======== AVAILABLE AREAS ========
29
- AVAILABLE_AREAS = [
30
- 'Albania', 'Algeria', 'Angola', 'Argentina', 'Armenia', 'Australia', 'Austria',
31
- 'Azerbaijan', 'Bahamas', 'Bahrain', 'Bangladesh', 'Belarus', 'Belgium', 'Botswana',
32
- 'Brazil', 'Bulgaria', 'Burkina Faso', 'Burundi', 'Cameroon', 'Canada',
33
- 'Central African Republic', 'Chile', 'Colombia', 'Croatia', 'Denmark',
34
- 'Dominican Republic', 'Ecuador', 'Egypt', 'El Salvador', 'Eritrea', 'Estonia',
35
- 'Finland', 'France', 'Germany', 'Ghana', 'Greece', 'Guatemala', 'Guinea',
36
- 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'India', 'Indonesia', 'Iraq',
37
- 'Ireland', 'Italy', 'Jamaica', 'Japan', 'Kazakhstan', 'Kenya', 'Latvia',
38
- 'Lebanon', 'Lesotho', 'Libya', 'Lithuania', 'Madagascar', 'Malawi', 'Malaysia',
39
- 'Mali', 'Mauritania', 'Mauritius', 'Mexico', 'Montenegro', 'Morocco',
40
- 'Mozambique', 'Namibia', 'Nepal', 'Netherlands', 'New Zealand', 'Nicaragua',
41
- 'Niger', 'Norway', 'Pakistan', 'Papua New Guinea', 'Peru', 'Poland', 'Portugal',
42
- 'Qatar', 'Romania', 'Rwanda', 'Saudi Arabia', 'Senegal', 'Slovenia',
43
- 'South Africa', 'Spain', 'Sri Lanka', 'Sudan', 'Suriname', 'Sweden',
44
- 'Switzerland', 'Tajikistan', 'Thailand', 'Tunisia', 'Turkey', 'Uganda',
45
- 'Ukraine', 'United Kingdom', 'Uruguay', 'Zambia', 'Zimbabwe'
46
- ]
47
 
48
- # ======== PREDICTION FUNCTION ========
49
- def predict_yield(area, item, year, rainfall, pesticides, temperature):
50
- if model is None:
51
- return f"❌ ERROR: {load_status}"
52
-
53
- try:
54
- year_val = int(year)
55
- rainfall_val = float(rainfall)
56
- pesticides_val = float(pesticides)
57
- temperature_val = float(temperature)
58
-
59
- input_data = {
60
- 'Area': [area],
61
- 'Item': [item],
62
- 'Year': [year_val],
63
- 'average_rain_fall_mm_per_year': [rainfall_val],
64
- 'pesticides_tonnes': [pesticides_val],
65
- 'avg_temp': [temperature_val]
66
- }
67
-
68
- input_df = pd.DataFrame(input_data)
69
- prediction = model.predict(input_df)
70
- predicted_yield = prediction[0]
71
- predicted_yield_kg_ha = predicted_yield * 0.1
72
-
73
- result_text = f"**🌾 Predicted Yield: {predicted_yield_kg_ha:,.0f} kg/ha**\n*({predicted_yield:,.0f} hg/ha)*"
74
-
75
- return result_text
76
-
77
- except Exception as e:
78
- return f"❌ PREDICTION ERROR: {str(e)}"
79
 
80
- # ======== GRADIO INTERFACE ========
81
- with gr.Blocks(title="Crop Yield Predictor", theme=gr.themes.Soft()) as demo:
82
- gr.Markdown("# 🌾 Crop Yield Predictor API")
83
- gr.Markdown(f"**Model Status:** {load_status}")
84
-
85
- with gr.Row():
86
- with gr.Column():
87
- area = gr.Dropdown(label="🌍 Country/Area", choices=AVAILABLE_AREAS, value="India")
88
- item = gr.Textbox(label="🌱 Crop Type", value="Maize")
89
- year = gr.Number(label="πŸ“… Year", value=2023)
90
- rainfall = gr.Textbox(label="πŸ’§ Average Rainfall (mm/year)", value="800.0")
91
- pesticides = gr.Textbox(label="🧴 Pesticides (tonnes)", value="5000.0")
92
- temperature = gr.Textbox(label="🌑️ Average Temperature (°C)", value="20.0")
93
- predict_btn = gr.Button("πŸš€ Predict Yield", variant="primary")
94
-
95
- with gr.Column():
96
- output = gr.Markdown(label="Prediction Result")
97
-
98
- predict_btn.click(
99
- fn=predict_yield,
100
- inputs=[area, item, year, rainfall, pesticides, temperature],
101
- outputs=[output]
102
- )
103
 
104
- # ======== FASTAPI ROUTES ========
105
  @app.get("/")
106
- async def home():
107
- return {"message": "Crop Yield Predictor API", "status": "running"}
108
-
109
- @app.get("/health")
110
- async def health():
111
- return {"model_loaded": model is not None, "status": load_status}
112
-
113
- @app.get("/api/areas")
114
- async def get_areas():
115
- return {"areas": AVAILABLE_AREAS}
116
-
117
- @app.post("/api/predict")
118
- async def api_predict(area: str, item: str, year: int, rainfall: float, pesticides: float, temperature: float):
119
- result = predict_yield(area, item, year, rainfall, pesticides, temperature)
120
- return {
121
- "success": True if "❌" not in result else False,
122
- "prediction": result,
123
- "input": {
124
- "area": area,
125
- "item": item,
126
- "year": year,
127
- "rainfall": rainfall,
128
- "pesticides": pesticides,
129
- "temperature": temperature
130
- }
131
- }
132
-
133
- app = gr.mount_gradio_app(app, demo, path="/")
 
 
1
  from fastapi import FastAPI
2
+ from pydantic import BaseModel
 
 
3
  import joblib
4
+ import pandas as pd
5
+ import uvicorn
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # βœ… Initialize FastAPI app
8
+ app = FastAPI(title="Crop Yield Predictor API", version="1.0")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # βœ… Load your trained model
11
+ model = joblib.load("CropYeildPredictor.pkl")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # βœ… Define the expected input schema
14
+ class CropInput(BaseModel):
15
+ country: str
16
+ crop_type: str
17
+ year: int
18
+ avg_rainfall: float
19
+ pesticides: float
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # βœ… Home route
22
  @app.get("/")
23
+ def home():
24
+ return {"message": "Crop Yield Predictor API is running successfully!"}
25
+
26
+ # βœ… Prediction route
27
+ @app.post("/predict")
28
+ def predict_yield(data: CropInput):
29
+ # Convert input to DataFrame (must match training features order)
30
+ input_df = pd.DataFrame([{
31
+ "Country": data.country,
32
+ "Crop": data.crop_type,
33
+ "Year": data.year,
34
+ "average_rain_fall_mm_per_year": data.avg_rainfall,
35
+ "pesticides_tonnes": data.pesticides
36
+ }])
37
+
38
+ # Make prediction
39
+ prediction = model.predict(input_df)[0]
40
+
41
+ return {"predicted_yield": float(prediction)}
42
+
43
+ # βœ… For local testing (won’t be used in HF)
44
+ if __name__ == "__main__":
45
+ uvicorn.run(app, host="0.0.0.0", port=7860)