Ravindra S commited on
Commit
e0e6cdf
·
1 Parent(s): 3c59271

Add application file

Browse files
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ .env
2
+ _pycache_/
3
+ Model1-crop-rec\__pycache__
4
+ Model-yeild-rec\yield_model_from_csv.joblib
Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ WORKDIR /app
4
+ COPY . /app
5
+
6
+ RUN pip install --no-cache-dir -r requirements.txt
7
+
8
+ EXPOSE 7860
9
+ CMD ["uvicorn", "runmodel:app", "--host", "0.0.0.0", "--port", "7860"]
Model-crop-rec/__pycache__/model1crop-rec.cpython-313.pyc ADDED
Binary file (8.95 kB). View file
 
Model-crop-rec/crop_imputer.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb75c61e69929761446a89bf2ca95e1c5e9e9c5d524f4795f716a8b0cd2aa007
3
+ size 847
Model-crop-rec/crop_model.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f2cca809359586cef47f38ef48e9fc7c61b516494e06632829eeec3194906e8
3
+ size 11030105
Model-plant/plant_disease_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2928928345656a1e78c9fd63b7743135824346899068e39657366032e604e13e
3
+ size 97589648
Model-yeild-rec/yield_model_from_csv.joblib ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:196329e9bad8817270ea1f5806b37bcbfdf2d797b795b28363cb6a23f076d555
3
+ size 126713923
README.md CHANGED
@@ -1,9 +1,11 @@
1
  ---
2
- title: Farmer Bud
3
- emoji: 👁
4
- colorFrom: indigo
5
- colorTo: gray
6
- sdk: docker
 
 
7
  pinned: false
8
  license: apache-2.0
9
  ---
 
1
  ---
2
+ title: Farmer Help
3
+ emoji: 📚
4
+ colorFrom: gray
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.44.1
8
+ app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  ---
app.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, File, UploadFile
2
+ from pydantic import BaseModel
3
+ import pandas as pd
4
+ import numpy as np
5
+ import joblib
6
+ from pymongo import MongoClient
7
+ from datetime import datetime
8
+ from openai import OpenAI
9
+ import os
10
+ from runmodel import app
11
+ import dotenv
12
+ import json
13
+ import io
14
+ import tensorflow as tf
15
+ from PIL import Image
16
+
17
+ # -------------------------
18
+ # Config
19
+ # -------------------------
20
+ dotenv.load_dotenv()
21
+
22
+ MONGO_URI = os.getenv("MONGO_URI")
23
+ MONGO_DB = os.getenv("MONGO_DB")
24
+ MONGO_COLL = os.getenv("MONGO_COLL")
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+
27
+ # Model paths
28
+ CROP_MODEL_PATH = "Model-crop-rec/crop_model.joblib"
29
+ CROP_IMPUTER_PATH = "Model-crop-rec/crop_imputer.joblib"
30
+ YIELD_MODEL_PATH = "Model-yeild-rec/yield_model_from_csv.joblib"
31
+ DISEASE_MODEL_PATH = "Model-plant/plant_disease_model.h5" # <-- NEW
32
+
33
+ # --- NEW: Disease Class Names ---
34
+ ## IMPORTANT: Update with your actual class names in the correct order ##
35
+ DISEASE_CLASS_NAMES = ["Early Blight", "Late Blight", "Healthy"]
36
+
37
+ # Feature sets
38
+ CROP_FEATURES = ["N", "P", "K", "temperature", "humidity", "ph", "rainfall"]
39
+ YIELD_FEATURES = ['Year', 'rainfall_mm', 'pesticides_tonnes', 'avg_temp', 'Area', 'Item']
40
+ AI_MODEL_NAME = "openai/gpt-oss-120b:cerebras"
41
+
42
+ # -------------------------
43
+ # Load models & imputer
44
+ # -------------------------
45
+ print("Loading machine learning models...")
46
+ clf = joblib.load(CROP_MODEL_PATH)
47
+ imp = joblib.load(CROP_IMPUTER_PATH)
48
+ yield_model = joblib.load(YIELD_MODEL_PATH)
49
+ print("Crop, Imputer, and Yield models loaded successfully.")
50
+
51
+ # --- NEW: Load Disease Detection Model ---
52
+ disease_model = None
53
+ try:
54
+ if os.path.exists(DISEASE_MODEL_PATH):
55
+ disease_model = tf.keras.models.load_model(DISEASE_MODEL_PATH)
56
+ print("Plant disease detection model loaded successfully.")
57
+ else:
58
+ print(f"Warning: Disease model not found at {DISEASE_MODEL_PATH}")
59
+ except Exception as e:
60
+ print(f"Error loading disease model: {e}")
61
+
62
+
63
+ # Database connection
64
+ client = MongoClient(MONGO_URI)
65
+ coll = client[MONGO_DB][MONGO_COLL]
66
+
67
+ # -------------------------
68
+ # LLM Client (for gpt-oss-120b text generation)
69
+ # -------------------------
70
+ llm_client = None
71
+ if HF_TOKEN:
72
+ try:
73
+ llm_client = OpenAI(
74
+ base_url="https://router.huggingface.co/v1",
75
+ api_key=HF_TOKEN,
76
+ default_headers={"Accept-Encoding": "identity"}
77
+ )
78
+ print("LLM client for text generation initialized.")
79
+ except Exception as e:
80
+ print(f"Warning: LLM client init failed: {e}")
81
+ llm_client = None
82
+
83
+ # -------------------------
84
+ # NEW: Image Preprocessing Helper
85
+ # -------------------------
86
+ def preprocess_image(image_bytes: bytes) -> np.ndarray:
87
+ """Reads image bytes, resizes to 128x128, normalizes, and prepares for the model."""
88
+ img = Image.open(io.BytesIO(image_bytes))
89
+ img = img.convert("RGB") # Ensure 3 channels
90
+ img = img.resize((128, 128))
91
+ img_array = tf.keras.preprocessing.image.img_to_array(img)
92
+ img_array = img_array / 255.0 # Normalize to [0, 1]
93
+ img_batch = np.expand_dims(img_array, axis=0) # Add batch dimension
94
+ return img_batch
95
+
96
+ # -------------------------
97
+ # Core Logic Functions
98
+ # -------------------------
99
+ def get_crop_recommendation_logic(farmer_doc: dict):
100
+ # This function remains the same
101
+ if any(pd.isna(farmer_doc.get(k)) for k in CROP_FEATURES):
102
+ raise ValueError("Missing required fields for crop recommendation.")
103
+ feat = {k: float(farmer_doc[k]) for k in CROP_FEATURES}
104
+ actual_crop = str(farmer_doc.get("crop", "")).strip().lower()
105
+ df_in = pd.DataFrame([feat], columns=CROP_FEATURES)
106
+ df_in_imp = pd.DataFrame(imp.transform(df_in), columns=CROP_FEATURES)
107
+ probs = clf.predict_proba(df_in_imp)[0]
108
+ prob_map = dict(zip(clf.classes_, probs))
109
+ crop_df = pd.DataFrame(list(coll.find()))
110
+ centroids = crop_df.groupby("crop")[CROP_FEATURES].mean()
111
+ centroid_matrix = centroids.values
112
+ dists = np.linalg.norm(centroid_matrix - df_in_imp.values.reshape(1, -1), axis=1)
113
+ sims = 1.0 / (1.0 + dists)
114
+ sim_map = dict(zip(centroids.index, sims))
115
+ all_scores = {}
116
+ for crop in clf.classes_:
117
+ p = prob_map.get(crop, 0.0)
118
+ s = sim_map.get(crop, 0.0)
119
+ all_scores[crop.lower()] = { "crop": crop, "probability": float(p), "centroid_similarity": float(s), "final_score": float(0.5 * p + 0.5 * s) }
120
+ advice_for_existing_crop = None
121
+ if actual_crop and actual_crop in all_scores and llm_client:
122
+ advice_for_existing_crop = get_cultivation_advice(llm_client, all_scores[actual_crop]['crop'], feat)
123
+ sorted_scores = sorted(all_scores.values(), key=lambda x: x['final_score'], reverse=True)
124
+ new_recommendations = [s for s in sorted_scores if s['crop'].lower() != actual_crop][:3]
125
+ advice_for_new_crop = None
126
+ if new_recommendations and llm_client:
127
+ advice_for_new_crop = get_cultivation_advice(llm_client, new_recommendations[0]['crop'], feat)
128
+ return {
129
+ "features_used": feat,
130
+ "new_crop_recommendations": new_recommendations,
131
+ "advice_for_top_new_crop": advice_for_new_crop,
132
+ "advice_for_existing_crop": advice_for_existing_crop
133
+ }
134
+
135
+ def get_yield_prediction_logic(farmer_doc: dict):
136
+ # This function remains the same
137
+ yield_input = {
138
+ 'Year': farmer_doc.get('year', datetime.now().year),
139
+ 'rainfall_mm': farmer_doc.get('rainfall'),
140
+ 'pesticides_tonnes': farmer_doc.get('pesticides_tonnes', 0.0),
141
+ 'avg_temp': farmer_doc.get('temperature'),
142
+ 'Area': farmer_doc.get('state', 'Unknown'),
143
+ 'Item': farmer_doc.get('crop')
144
+ }
145
+ missing_fields = [k for k in YIELD_FEATURES if yield_input.get(k) is None]
146
+ if missing_fields:
147
+ raise ValueError(f"Missing required fields for yield prediction: {missing_fields}")
148
+ yield_input_data = pd.DataFrame([yield_input], columns=YIELD_FEATURES)
149
+ predicted_yield_hg_ha = yield_model.predict(yield_input_data)[0]
150
+ predicted_yield_quintal_ha = float(round(predicted_yield_hg_ha / 10, 2))
151
+ return {
152
+ "predicted_yield_quintal_per_hectare": predicted_yield_quintal_ha,
153
+ "features_used": yield_input
154
+ }
155
+
156
+ # -------------------------
157
+ # LLM Helper Functions
158
+ # -------------------------
159
+
160
+ def get_cultivation_advice(client, crop_name, features):
161
+ if not client: return "LLM client not available for advice generation."
162
+ prompt = f"Provide concise cultivation advice for '{crop_name}' given these conditions: N={features['N']:.2f}, P={features['P']:.2f}, K={features['K']:.2f}, pH={features['ph']:.2f}, Temp={features['temperature']:.2f}C, Humidity={features['humidity']:.2f}%, Rainfall={features['rainfall']:.2f}mm. Suggest land prep, sowing, fertilization, irrigation in bullets."
163
+ try:
164
+ completion = client.chat.completions.create(model=AI_MODEL_NAME, messages=[{"role": "user", "content": prompt}], temperature=0.7, max_tokens=512)
165
+ return completion.choices[0].message.content.strip()
166
+ except Exception as e: return f"Could not generate advice: {e}"
167
+
168
+ def generate_yield_advice(client, farmer_data, prediction):
169
+ if not client: return "LLM client not available for advice generation."
170
+ prompt = f"An expert agronomist providing 2-3 key bullet points to improve crop yield. Farmer's crop: '{farmer_data.get('crop')}' in an area of {farmer_data.get('areaHectare')} ha. Our model predicts a yield of {prediction:.2f} quintals per hectare. Focus on practical steps."
171
+ try:
172
+ completion = client.chat.completions.create(model=AI_MODEL_NAME, messages=[{"role": "user", "content": prompt}], temperature=0.7, max_tokens=512)
173
+ return completion.choices[0].message.content.strip()
174
+ except Exception as e: return f"Could not generate yield advice: {e}"
175
+
176
+ def get_intent_from_llm(client, query: str):
177
+ if not client: return {"intent": "UNKNOWN", "error": "LLM client not available."}
178
+ prompt = f"""Analyze the user's query and classify it into one of the intents: 'CROP_RECOMMENDATION', 'YIELD_PREDICTION', or 'GREETING'. Respond ONLY with a JSON object like {{"intent": "YOUR_CLASSIFICATION"}}. User query: "{query}" """
179
+ try:
180
+ completion = client.chat.completions.create(model=AI_MODEL_NAME, messages=[{"role": "user", "content": prompt}], temperature=0.1, max_tokens=50)
181
+ result_text = completion.choices[0].message.content.strip()
182
+ return json.loads(result_text)
183
+ except Exception as e:
184
+ print(f"LLM intent classification failed: {e}")
185
+ return {"intent": "UNKNOWN"}
186
+
187
+ # -------------------------
188
+ # FastAPI App & Pydantic Models
189
+ # -------------------------
190
+ app = FastAPI(title="Farmer AI Services API")
191
+
192
+ class FarmerRequest(BaseModel):
193
+ farmerId: str
194
+
195
+ class VoiceQueryRequest(BaseModel):
196
+ farmerId: str
197
+ query: str
198
+
199
+ # -------------------------
200
+ # API Endpoints
201
+ # -------------------------
202
+
203
+ @app.get("/")
204
+ def read_root():
205
+ return {"status": "API is running", "timestamp": datetime.now().isoformat()}
206
+
207
+ @app.post("/m1/crop-recommendation")
208
+ def recommend_crop(req: FarmerRequest):
209
+ farmer_doc = coll.find_one({"farmerId": req.farmerId})
210
+ if not farmer_doc:
211
+ raise HTTPException(status_code=404, detail="Farmer not found")
212
+ try:
213
+ result = get_crop_recommendation_logic(farmer_doc)
214
+ return { "farmerId": req.farmerId, **result, "recommended_at": datetime.utcnow().isoformat() }
215
+ except ValueError as e:
216
+ raise HTTPException(status_code=400, detail=str(e))
217
+ except Exception as e:
218
+ raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
219
+
220
+ @app.post("/m1/yield")
221
+ def predict_yield(req: FarmerRequest):
222
+ farmer_doc = coll.find_one({"farmerId": req.farmerId})
223
+ if not farmer_doc:
224
+ raise HTTPException(status_code=404, detail="Farmer not found")
225
+ try:
226
+ result = get_yield_prediction_logic(farmer_doc)
227
+ advice = generate_yield_advice(llm_client, farmer_doc, result["predicted_yield_quintal_per_hectare"])
228
+ return { "farmerId": req.farmerId, **result, "yield_advice": advice, "predicted_at": datetime.utcnow().isoformat() }
229
+ except ValueError as e:
230
+ raise HTTPException(status_code=400, detail=str(e))
231
+ except Exception as e:
232
+ raise HTTPException(status_code=500, detail=f"Yield prediction failed: {e}")
233
+
234
+ @app.post("/m1/voice-query")
235
+ def handle_voice_query(req: VoiceQueryRequest):
236
+ farmer_doc = coll.find_one({"farmerId": req.farmerId})
237
+ if not farmer_doc:
238
+ raise HTTPException(status_code=404, detail="Farmer not found")
239
+ intent_data = get_intent_from_llm(llm_client, req.query)
240
+ intent = intent_data.get("intent")
241
+ response_text = "I'm sorry, I couldn't process that request."
242
+ if intent == "CROP_RECOMMENDATION":
243
+ try:
244
+ result = get_crop_recommendation_logic(farmer_doc)
245
+ top_crop = result['new_crop_recommendations'][0]['crop'] if result['new_crop_recommendations'] else 'a suitable crop'
246
+ response_text = f"Based on your farm's data, I recommend planting {top_crop}. {result['advice_for_top_new_crop']}"
247
+ except Exception as e:
248
+ response_text = f"I tried to get a crop recommendation, but an error occurred: {e}"
249
+ elif intent == "YIELD_PREDICTION":
250
+ try:
251
+ result = get_yield_prediction_logic(farmer_doc)
252
+ yield_val = result['predicted_yield_quintal_per_hectare']
253
+ advice = generate_yield_advice(llm_client, farmer_doc, yield_val)
254
+ response_text = f"The predicted yield for your {farmer_doc.get('crop', 'crop')} is {yield_val} quintals per hectare. Here is some advice to improve it: {advice}"
255
+ except Exception as e:
256
+ response_text = f"I tried to predict the yield, but an error occurred: {e}"
257
+ elif intent == "GREETING":
258
+ response_text = "Hello! How can I assist you with your farm today? You can ask for a crop recommendation or a yield prediction."
259
+ else: # UNKNOWN
260
+ response_text = "I'm sorry, I didn't understand that. Please ask for a crop recommendation or a yield prediction."
261
+ return {"response_text": response_text}
262
+
263
+ # -------------------------
264
+ # NEW: Plant Disease Endpoint
265
+ # -------------------------
266
+ @app.post("/m2/plant-disease")
267
+ async def detect_plant_disease(file: UploadFile = File(...)):
268
+ """Endpoint for plant disease detection from an image."""
269
+ if not disease_model:
270
+ raise HTTPException(status_code=503, detail="Disease detection service is unavailable.")
271
+
272
+ # Validate file type
273
+ if not file.content_type.startswith("image/"):
274
+ raise HTTPException(status_code=400, detail="Invalid file type. Please upload an image.")
275
+
276
+ try:
277
+ # Read and process the image
278
+ image_bytes = await file.read()
279
+ processed_image = preprocess_image(image_bytes)
280
+
281
+ # Make prediction
282
+ predictions = disease_model.predict(processed_image)
283
+
284
+ # Process result
285
+ predicted_index = np.argmax(predictions[0])
286
+ confidence = float(predictions[0][predicted_index])
287
+ predicted_class = DISEASE_CLASS_NAMES[predicted_index]
288
+
289
+ return {
290
+ "predicted_class": predicted_class,
291
+ "confidence": f"{confidence:.2%}", # Format as percentage string
292
+ "details": {
293
+ "raw_predictions": predictions[0].tolist(),
294
+ "class_names": DISEASE_CLASS_NAMES
295
+ }
296
+ }
297
+ except Exception as e:
298
+ print(f"Error during disease prediction: {e}")
299
+ raise HTTPException(status_code=500, detail="Failed to process the image.")
300
+ if __name__ == "__main__":
301
+ import uvicorn
302
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ pandas
4
+ numpy
5
+ joblib
6
+ scikit-learn
7
+ pymongo
8
+ openai
9
+ requests
10
+ kaggle
11
+ dotenv
12
+ tensorflow
13
+ Pillow
space.yml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ sdk: docker
2
+ docker:
3
+ build:
4
+ dockerfile: Dockerfile