devangshupandey2025-stack commited on
Commit
c99fc72
·
1 Parent(s): 751cd3d

Deploy PlantGuard API to Hugging Face Spaces

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +24 -0
  2. README.md +15 -5
  3. backend/.env +9 -0
  4. backend/.env.example +18 -0
  5. backend/Dockerfile +26 -0
  6. backend/app/__init__.py +0 -0
  7. backend/app/__pycache__/__init__.cpython-311.pyc +0 -0
  8. backend/app/__pycache__/main.cpython-311.pyc +0 -0
  9. backend/app/api/__init__.py +0 -0
  10. backend/app/api/__pycache__/__init__.cpython-311.pyc +0 -0
  11. backend/app/api/__pycache__/routes.cpython-311.pyc +0 -0
  12. backend/app/api/routes.py +319 -0
  13. backend/app/main.py +127 -0
  14. backend/app/ml/__init__.py +0 -0
  15. backend/app/ml/__pycache__/__init__.cpython-311.pyc +0 -0
  16. backend/app/ml/__pycache__/finetuner.cpython-311.pyc +0 -0
  17. backend/app/ml/__pycache__/gemini_validator.cpython-311.pyc +0 -0
  18. backend/app/ml/__pycache__/llama_validator.cpython-311.pyc +0 -0
  19. backend/app/ml/__pycache__/predictor.cpython-311.pyc +0 -0
  20. backend/app/ml/finetuner.py +239 -0
  21. backend/app/ml/gemini_validator.py +260 -0
  22. backend/app/ml/predictor.py +225 -0
  23. backend/app/models/__init__.py +0 -0
  24. backend/app/models/__pycache__/__init__.cpython-311.pyc +0 -0
  25. backend/app/models/__pycache__/schemas.cpython-311.pyc +0 -0
  26. backend/app/models/schemas.py +83 -0
  27. backend/app/services/__init__.py +0 -0
  28. backend/app/services/__pycache__/__init__.cpython-311.pyc +0 -0
  29. backend/app/services/__pycache__/supabase_service.cpython-311.pyc +0 -0
  30. backend/app/services/supabase_service.py +242 -0
  31. backend/requirements.txt +20 -0
  32. backend/start.sh +7 -0
  33. checkpoints/class_names.json +40 -0
  34. checkpoints/mobilenet_v3/best_model.pt +3 -0
  35. checkpoints/mobilenet_v3/training_history.json +137 -0
  36. ml_pipeline/__init__.py +0 -0
  37. ml_pipeline/__pycache__/__init__.cpython-311.pyc +0 -0
  38. ml_pipeline/configs/convnext_tiny.yaml +38 -0
  39. ml_pipeline/configs/efficientnet_v2.yaml +38 -0
  40. ml_pipeline/configs/mobilenet_v3.yaml +38 -0
  41. ml_pipeline/configs/resnet50.yaml +38 -0
  42. ml_pipeline/configs/swin_tiny.yaml +38 -0
  43. ml_pipeline/data/__init__.py +0 -0
  44. ml_pipeline/data/__pycache__/__init__.cpython-311.pyc +0 -0
  45. ml_pipeline/data/__pycache__/dataset.cpython-311.pyc +0 -0
  46. ml_pipeline/data/dataset.py +288 -0
  47. ml_pipeline/distillation/__init__.py +0 -0
  48. ml_pipeline/ensemble/__init__.py +0 -0
  49. ml_pipeline/models/__init__.py +0 -0
  50. ml_pipeline/models/__pycache__/__init__.cpython-311.pyc +0 -0
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # System deps
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ build-essential libgl1 libglib2.0-0 curl \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # Python deps
11
+ COPY backend/requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # App code
15
+ COPY backend/ ./backend/
16
+ COPY ml_pipeline/ ./ml_pipeline/
17
+ COPY checkpoints/ ./checkpoints/
18
+
19
+ ENV PYTHONPATH=/app
20
+
21
+ # Hugging Face Spaces uses port 7860
22
+ EXPOSE 7860
23
+
24
+ CMD ["uvicorn", "backend.app.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,10 +1,20 @@
1
  ---
2
- title: Plantguard Api
3
- emoji: 👀
4
- colorFrom: indigo
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: PlantGuard API
3
+ emoji: 🌿
4
+ colorFrom: green
5
+ colorTo: green
6
  sdk: docker
7
  pinned: false
8
+ app_port: 7860
9
  ---
10
 
11
+ # PlantGuard API
12
+
13
+ AI-powered plant disease detection API using MobileNetV3 + Gemini AI.
14
+
15
+ ## Endpoints
16
+
17
+ - `GET /health` - Health check
18
+ - `POST /api/predict` - Upload plant image for disease prediction
19
+ - `GET /api/classes` - List supported disease classes
20
+
backend/.env ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ SUPABASE_URL=https://jilfujxzegrhnwxfvcop.supabase.co
2
+ SUPABASE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImppbGZ1anh6ZWdyaG53eGZ2Y29wIiwicm9sZSI6ImFub24iLCJpYXQiOjE3Njk4NzI2NjEsImV4cCI6MjA4NTQ0ODY2MX0.ZWl_o9mLA5Njf0lAhYpMEWttiowdtWAJ7DmUcxFhMak
3
+ SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImppbGZ1anh6ZWdyaG53eGZ2Y29wIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc2OTg3MjY2MSwiZXhwIjoyMDg1NDQ4NjYxfQ.nURb5tWEpm3gmdMiGv-bSMi-HfkeQdSuYM2mbCXvdKA
4
+ MODELS_DIR=checkpoints
5
+ ENSEMBLE_DIR=checkpoints/ensemble
6
+ FRONTEND_URL=http://localhost:5173
7
+ GEMINI_API_KEY=AIzaSyDTiDDV23yBqZo161evyNZv6ZTZmVyLp-I
8
+ GEMINI_MODEL=gemini-2.5-flash
9
+ SARVAM_API_KEY=sk_qiu0ryv1_0F1KvdwR0RkSdUvynIOAKPwi
backend/.env.example ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Supabase Configuration
2
+ SUPABASE_URL=https://your-project.supabase.co
3
+ SUPABASE_KEY=your-anon-key-here
4
+ SUPABASE_SERVICE_KEY=your-service-key-here
5
+
6
+ # Gemini API (for AI cross-validation)
7
+ GEMINI_API_KEY=your-gemini-api-key-here
8
+ GEMINI_MODEL=gemini-2.5-flash
9
+
10
+ # ML Model paths
11
+ MODELS_DIR=checkpoints
12
+ ENSEMBLE_DIR=checkpoints/ensemble
13
+
14
+ # Frontend URL (for CORS)
15
+ FRONTEND_URL=http://localhost:5173
16
+
17
+ # Optional monitoring
18
+ SENTRY_DSN=
backend/Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ WORKDIR /app
4
+
5
+ # System deps
6
+ RUN apt-get update && apt-get install -y --no-install-recommends \
7
+ build-essential libgl1 libglib2.0-0 curl \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ # Python deps
11
+ COPY backend/requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # App code
15
+ COPY backend/ ./backend/
16
+ COPY ml_pipeline/ ./ml_pipeline/
17
+
18
+ # Copy model checkpoints if available
19
+ COPY checkpoints/ ./checkpoints/
20
+
21
+ ENV PYTHONPATH=/app
22
+
23
+ EXPOSE 8000
24
+
25
+ # Use Python to read PORT env var (guaranteed to work)
26
+ CMD ["python", "-c", "import os; import subprocess; port = os.environ.get('PORT', '8080'); subprocess.run(['uvicorn', 'backend.app.main:app', '--host', '0.0.0.0', '--port', port])"]
backend/app/__init__.py ADDED
File without changes
backend/app/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (186 Bytes). View file
 
backend/app/__pycache__/main.cpython-311.pyc ADDED
Binary file (4.26 kB). View file
 
backend/app/api/__init__.py ADDED
File without changes
backend/app/api/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (190 Bytes). View file
 
backend/app/api/__pycache__/routes.cpython-311.pyc ADDED
Binary file (15.9 kB). View file
 
backend/app/api/routes.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """API routes for prediction, auth, and history."""
2
+ import io
3
+ import os
4
+ import time
5
+ from typing import Optional
6
+
7
+ from fastapi import APIRouter, File, UploadFile, HTTPException, Header, Query, BackgroundTasks
8
+ from fastapi.responses import Response
9
+ from pydantic import BaseModel
10
+ from PIL import Image
11
+ import httpx
12
+ import base64
13
+
14
+ from backend.app.ml.predictor import get_predictor
15
+ from backend.app.ml.gemini_validator import get_validator
16
+ from backend.app.ml.finetuner import get_finetuner
17
+ from backend.app.models.schemas import (
18
+ PredictionResponse, HealthResponse, GeminiValidation
19
+ )
20
+ from backend.app.services.supabase_service import supabase_service
21
+
22
+ router = APIRouter()
23
+
24
+ SARVAM_API_KEY = os.getenv("SARVAM_API_KEY", "")
25
+ SARVAM_TTS_URL = "https://api.sarvam.ai/text-to-speech"
26
+ SARVAM_TTS_SPEAKER = os.getenv("SARVAM_TTS_SPEAKER", "anushka")
27
+ SARVAM_TTS_MODEL = os.getenv("SARVAM_TTS_MODEL", "bulbul:v2")
28
+ # Max chars per TTS request (bulbul:v2=1500, v3=2500)
29
+ SARVAM_MAX_CHARS = 1500
30
+
31
+
32
+ class TTSRequest(BaseModel):
33
+ text: str
34
+ language: str = "en"
35
+ pace: float = 1.0
36
+
37
+
38
+ class FeedbackRequest(BaseModel):
39
+ predicted_class: str
40
+ actual_class: str
41
+ is_correct: bool
42
+ image_url: str = ""
43
+ prediction_id: Optional[str] = None
44
+
45
+
46
+ @router.get("/health", response_model=HealthResponse)
47
+ async def health_check():
48
+ predictor = get_predictor()
49
+ validator = get_validator()
50
+ return HealthResponse(
51
+ status="healthy" if predictor._loaded else "models_not_loaded",
52
+ model_loaded=predictor._loaded,
53
+ gemini_available=validator.is_available,
54
+ device=str(predictor.device),
55
+ )
56
+
57
+
58
+ @router.post("/predict", response_model=PredictionResponse)
59
+ async def predict_disease(
60
+ file: UploadFile = File(...),
61
+ top_k: int = Query(default=5, ge=1, le=38),
62
+ authorization: Optional[str] = Header(default=None),
63
+ ):
64
+ """
65
+ Predict plant disease from leaf image using MobileNetV3.
66
+ Includes Gemini AI cross-validation with visual analysis of the leaf image.
67
+ """
68
+ if not file.content_type or not file.content_type.startswith("image/"):
69
+ raise HTTPException(400, "File must be an image (JPEG, PNG, etc.)")
70
+
71
+ try:
72
+ contents = await file.read()
73
+ image = Image.open(io.BytesIO(contents)).convert("RGB")
74
+ except Exception:
75
+ raise HTTPException(400, "Invalid image file")
76
+
77
+ predictor = get_predictor()
78
+ if not predictor._loaded:
79
+ raise HTTPException(503, "Model not loaded yet")
80
+
81
+ start = time.time()
82
+ result = predictor.predict(image, top_k=top_k)
83
+ image_metadata = result.pop("image_metadata", {})
84
+ latency_ms = (time.time() - start) * 1000
85
+ print(f"MobileNet inference: {latency_ms:.0f}ms")
86
+
87
+ # Run Gemini validation synchronously (multimodal: image + text)
88
+ gemini_validation = None
89
+ validator = get_validator()
90
+ if validator.is_available:
91
+ gemini_start = time.time()
92
+ validation_result = await validator.validate_async(
93
+ dict(result), dict(image_metadata), image_bytes=contents
94
+ )
95
+ gemini_ms = (time.time() - gemini_start) * 1000
96
+ print(f"Gemini validation: {gemini_ms:.0f}ms")
97
+ if validation_result:
98
+ gemini_validation = GeminiValidation(**validation_result)
99
+
100
+ # Save to history if authenticated
101
+ image_url = None
102
+ if authorization and supabase_service.is_available:
103
+ token = authorization.replace("Bearer ", "")
104
+ user = supabase_service.verify_token(token)
105
+ if user:
106
+ image_url = supabase_service.upload_image(
107
+ contents, file.filename or "image.jpg", user["id"]
108
+ )
109
+ supabase_service.save_prediction(
110
+ user["id"], result, image_url,
111
+ gemini_validation=gemini_validation.model_dump() if gemini_validation else None
112
+ )
113
+
114
+ return PredictionResponse(
115
+ **{"class": result["class"]},
116
+ probability=result["probability"],
117
+ uncertainty=result["uncertainty"],
118
+ top_k=[{"class": p["class"], "probability": p["probability"]} for p in result["top_k"]],
119
+ gemini_validation=gemini_validation,
120
+ image_url=image_url,
121
+ )
122
+
123
+
124
+ @router.post("/auth/signup")
125
+ async def signup(email: str, password: str):
126
+ result = supabase_service.sign_up(email, password)
127
+ if "error" in result:
128
+ raise HTTPException(400, result["error"])
129
+ return result
130
+
131
+
132
+ @router.post("/auth/signin")
133
+ async def signin(email: str, password: str):
134
+ result = supabase_service.sign_in(email, password)
135
+ if "error" in result:
136
+ raise HTTPException(401, result["error"])
137
+ return result
138
+
139
+
140
+ @router.get("/history")
141
+ async def get_history(
142
+ authorization: str = Header(...),
143
+ limit: int = Query(default=20, ge=1, le=100),
144
+ ):
145
+ token = authorization.replace("Bearer ", "")
146
+ user = supabase_service.verify_token(token)
147
+ if not user:
148
+ raise HTTPException(401, "Invalid token")
149
+ history = supabase_service.get_history(user["id"], limit)
150
+ return {"predictions": history}
151
+
152
+
153
+ @router.get("/stats")
154
+ async def get_stats(authorization: str = Header(...)):
155
+ token = authorization.replace("Bearer ", "")
156
+ user = supabase_service.verify_token(token)
157
+ if not user:
158
+ raise HTTPException(401, "Invalid token")
159
+ stats = supabase_service.get_stats(user["id"])
160
+ return stats
161
+
162
+
163
+ @router.get("/classes")
164
+ async def get_classes():
165
+ """Return list of supported disease classes."""
166
+ predictor = get_predictor()
167
+ return {"classes": predictor.class_names, "count": len(predictor.class_names)}
168
+
169
+
170
+ @router.post("/feedback")
171
+ async def submit_feedback(
172
+ request: FeedbackRequest,
173
+ authorization: Optional[str] = Header(default=None),
174
+ ):
175
+ """Submit user feedback on a prediction (for model training)."""
176
+ user_id = None
177
+ if authorization:
178
+ token = authorization.replace("Bearer ", "")
179
+ user = supabase_service.verify_token(token)
180
+ if user:
181
+ user_id = user["id"]
182
+
183
+ if not user_id:
184
+ user_id = "anonymous"
185
+
186
+ result = supabase_service.save_feedback(
187
+ user_id=user_id,
188
+ prediction_id=request.prediction_id,
189
+ image_url=request.image_url,
190
+ predicted_class=request.predicted_class,
191
+ actual_class=request.actual_class,
192
+ is_correct=request.is_correct,
193
+ )
194
+ if result.get("status") == "error":
195
+ raise HTTPException(500, result.get("error", "Failed to save feedback"))
196
+ return result
197
+
198
+
199
+ @router.get("/feedback/stats")
200
+ async def feedback_stats():
201
+ """Get feedback statistics and model training status."""
202
+ stats = supabase_service.get_feedback_stats()
203
+ finetuner = get_finetuner()
204
+ stats["is_training"] = finetuner.is_training
205
+ stats["last_training"] = finetuner.last_training
206
+ stats["can_retrain"] = stats["total"] >= 5
207
+ return stats
208
+
209
+
210
+ @router.post("/admin/retrain")
211
+ async def retrain_model(
212
+ background_tasks: BackgroundTasks,
213
+ authorization: str = Header(...),
214
+ ):
215
+ """Trigger model fine-tuning using accumulated feedback data."""
216
+ token = authorization.replace("Bearer ", "")
217
+ user = supabase_service.verify_token(token)
218
+ if not user:
219
+ raise HTTPException(401, "Invalid token")
220
+
221
+ finetuner = get_finetuner()
222
+ if finetuner.is_training:
223
+ raise HTTPException(409, "Training already in progress")
224
+
225
+ feedback_data = supabase_service.get_feedback()
226
+ if len(feedback_data) < 5:
227
+ raise HTTPException(400, f"Need at least 5 feedback samples, got {len(feedback_data)}")
228
+
229
+ predictor = get_predictor()
230
+
231
+ def run_training():
232
+ result = finetuner.finetune(predictor, feedback_data, supabase_service)
233
+ if result["status"] == "success":
234
+ predictor.model.eval()
235
+ print(f"Model fine-tuned: v{result['version']}, {result['samples_used']} samples, acc={result['final_accuracy']:.2%}")
236
+
237
+ background_tasks.add_task(run_training)
238
+ return {"status": "training_started", "samples_queued": len(feedback_data)}
239
+
240
+
241
+ @router.get("/admin/retrain/status")
242
+ async def retrain_status(authorization: str = Header(...)):
243
+ """Check current training status."""
244
+ token = authorization.replace("Bearer ", "")
245
+ user = supabase_service.verify_token(token)
246
+ if not user:
247
+ raise HTTPException(401, "Invalid token")
248
+
249
+ finetuner = get_finetuner()
250
+ return {
251
+ "is_training": finetuner.is_training,
252
+ "last_training": finetuner.last_training,
253
+ "total_runs": len(finetuner.training_history),
254
+ }
255
+
256
+
257
+ # Language code mapping for Sarvam TTS
258
+ LANG_TO_SARVAM = {
259
+ "en": "en-IN", "hi": "hi-IN", "ta": "ta-IN", "te": "te-IN",
260
+ "bn": "bn-IN", "mr": "mr-IN", "kn": "kn-IN", "gu": "gu-IN",
261
+ }
262
+
263
+
264
+ @router.post("/tts")
265
+ async def text_to_speech(request: TTSRequest):
266
+ """Convert text to speech using Sarvam AI TTS (Indian language support)."""
267
+ if not SARVAM_API_KEY:
268
+ raise HTTPException(503, "TTS service not configured (SARVAM_API_KEY missing)")
269
+
270
+ text = request.text.strip()
271
+ if not text:
272
+ raise HTTPException(400, "Text cannot be empty")
273
+
274
+ target_lang = LANG_TO_SARVAM.get(request.language, "en-IN")
275
+ pace = max(0.5, min(2.0, request.pace))
276
+
277
+ # Truncate text to max chars (Sarvam limit)
278
+ if len(text) > SARVAM_MAX_CHARS:
279
+ text = text[:SARVAM_MAX_CHARS]
280
+
281
+ payload = {
282
+ "text": text,
283
+ "target_language_code": target_lang,
284
+ "speaker": SARVAM_TTS_SPEAKER,
285
+ "model": SARVAM_TTS_MODEL,
286
+ "pace": pace,
287
+ "speech_sample_rate": 22050,
288
+ "enable_preprocessing": True,
289
+ }
290
+
291
+ try:
292
+ async with httpx.AsyncClient(timeout=30.0) as client:
293
+ resp = await client.post(
294
+ SARVAM_TTS_URL,
295
+ json=payload,
296
+ headers={
297
+ "api-subscription-key": SARVAM_API_KEY,
298
+ "Content-Type": "application/json",
299
+ },
300
+ )
301
+ resp.raise_for_status()
302
+ data = resp.json()
303
+
304
+ audios = data.get("audios", [])
305
+ if not audios:
306
+ raise HTTPException(500, "No audio returned from TTS service")
307
+
308
+ audio_bytes = base64.b64decode(audios[0])
309
+ return Response(
310
+ content=audio_bytes,
311
+ media_type="audio/wav",
312
+ headers={"Content-Disposition": "inline"},
313
+ )
314
+ except httpx.HTTPStatusError as e:
315
+ print(f"Sarvam TTS error: {e.response.status_code} - {e.response.text}")
316
+ raise HTTPException(502, f"TTS service error: {e.response.status_code}")
317
+ except Exception as e:
318
+ print(f"TTS error: {e}")
319
+ raise HTTPException(500, "Failed to generate speech")
backend/app/main.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI application — Plant Disease Detection API.
3
+ MobileNetV3 classifier with Gemini AI cross-validation.
4
+
5
+ Start:
6
+ uvicorn backend.app.main:app --host 0.0.0.0 --port 8000 --reload
7
+ """
8
+ import os
9
+ import asyncio
10
+ from contextlib import asynccontextmanager
11
+ from fastapi import FastAPI, Request
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+ from fastapi.middleware.trustedhost import TrustedHostMiddleware
14
+ from fastapi.responses import JSONResponse
15
+
16
+ from backend.app.api.routes import router
17
+ from backend.app.ml.predictor import get_predictor
18
+ from backend.app.ml.gemini_validator import get_validator
19
+ from backend.app.services.supabase_service import supabase_service
20
+
21
+ # Track if models are loaded
22
+ _models_ready = False
23
+
24
+
25
+ async def load_models_background():
26
+ """Load models in background after server starts."""
27
+ global _models_ready
28
+ print("Loading models in background...")
29
+
30
+ # Initialize Supabase
31
+ supabase_service.initialize()
32
+
33
+ # Load MobileNetV3
34
+ predictor = get_predictor()
35
+ models_dir = os.getenv("MODELS_DIR", "checkpoints")
36
+
37
+ if os.path.exists(models_dir):
38
+ try:
39
+ predictor.load(models_dir)
40
+ except FileNotFoundError as e:
41
+ print(f"⚠️ {e}")
42
+ print(" API will start but predictions won't work until model is available.")
43
+ else:
44
+ print(f"⚠️ Models directory not found: {models_dir}")
45
+ print(" API will start but predictions won't work until models are loaded.")
46
+
47
+ # Check Gemini API availability
48
+ validator = get_validator()
49
+ validator.check_availability()
50
+ if not validator.is_available:
51
+ print("⚠️ Gemini API not available — predictions will work without cross-validation.")
52
+
53
+ _models_ready = True
54
+ print("✓ Models loaded successfully")
55
+
56
+
57
+ @asynccontextmanager
58
+ async def lifespan(app: FastAPI):
59
+ """Start server immediately, load models in background."""
60
+ print("Starting Plant Disease Detection API...")
61
+ print(f"PORT: {os.environ.get('PORT', 'not set')}")
62
+ print("✓ Server ready for healthchecks")
63
+
64
+ # Start model loading in background (non-blocking)
65
+ asyncio.create_task(load_models_background())
66
+
67
+ yield
68
+ print("Shutting down...")
69
+
70
+
71
+ app = FastAPI(
72
+ title="Plant Disease Detection API",
73
+ description="MobileNetV3 plant disease classifier with Gemini AI cross-validation for reliable diagnosis.",
74
+ version="1.0.0",
75
+ lifespan=lifespan,
76
+ )
77
+
78
+ # Trust all hosts - required for Railway healthcheck from healthcheck.railway.app
79
+ app.add_middleware(
80
+ TrustedHostMiddleware,
81
+ allowed_hosts=["*"],
82
+ )
83
+
84
+ # CORS - allow all origins
85
+ app.add_middleware(
86
+ CORSMiddleware,
87
+ allow_origins=["*"],
88
+ allow_credentials=True,
89
+ allow_methods=["*"],
90
+ allow_headers=["*"],
91
+ )
92
+
93
+ # Routes
94
+ app.include_router(router, prefix="/api")
95
+
96
+
97
+ @app.get("/")
98
+ async def root():
99
+ return {
100
+ "name": "Plant Disease Detection API",
101
+ "version": "1.0.0",
102
+ "docs": "/docs",
103
+ }
104
+
105
+
106
+ @app.get("/health")
107
+ async def root_health():
108
+ """Simple health check for load balancers (always returns OK if app is running)."""
109
+ return JSONResponse(content={"status": "ok"}, status_code=200)
110
+
111
+
112
+ # Optional: Prometheus metrics
113
+ try:
114
+ from prometheus_client import make_asgi_app
115
+ metrics_app = make_asgi_app()
116
+ app.mount("/metrics", metrics_app)
117
+ except ImportError:
118
+ pass
119
+
120
+ # Optional: Sentry
121
+ try:
122
+ import sentry_sdk
123
+ sentry_dsn = os.getenv("SENTRY_DSN")
124
+ if sentry_dsn:
125
+ sentry_sdk.init(dsn=sentry_dsn, traces_sample_rate=0.1)
126
+ except ImportError:
127
+ pass
backend/app/ml/__init__.py ADDED
File without changes
backend/app/ml/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (189 Bytes). View file
 
backend/app/ml/__pycache__/finetuner.cpython-311.pyc ADDED
Binary file (13.8 kB). View file
 
backend/app/ml/__pycache__/gemini_validator.cpython-311.pyc ADDED
Binary file (12.2 kB). View file
 
backend/app/ml/__pycache__/llama_validator.cpython-311.pyc ADDED
Binary file (11.9 kB). View file
 
backend/app/ml/__pycache__/predictor.cpython-311.pyc ADDED
Binary file (13.6 kB). View file
 
backend/app/ml/finetuner.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dynamic fine-tuning engine for PlantGuard AI.
3
+ Fine-tunes only the classification head (backbone stays frozen) using user feedback data.
4
+ Designed to run on CPU (head has ~500K params).
5
+ """
6
+ import os
7
+ import io
8
+ import time
9
+ import logging
10
+ import threading
11
+ from typing import Optional, Dict, List
12
+ from datetime import datetime
13
+
14
+ import numpy as np
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.optim as optim
18
+ from torch.utils.data import Dataset, DataLoader
19
+ from torchvision import transforms
20
+ from PIL import Image
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ CHECKPOINT_DIR = os.getenv("MODELS_DIR", "checkpoints")
25
+ FINETUNE_DIR = os.path.join(CHECKPOINT_DIR, "mobilenet_v3", "finetuned")
26
+ IMG_SIZE = 224
27
+ FINETUNE_LR = 1e-4
28
+ FINETUNE_EPOCHS = 5
29
+ FINETUNE_BATCH = 8
30
+ MIN_SAMPLES = 5
31
+
32
+
33
+ class FeedbackDataset(Dataset):
34
+ """Dataset from user feedback images + labels."""
35
+
36
+ def __init__(self, images: List[Image.Image], labels: List[int], transform=None):
37
+ self.images = images
38
+ self.labels = labels
39
+ self.transform = transform or transforms.Compose([
40
+ transforms.Resize((IMG_SIZE + 32, IMG_SIZE + 32)),
41
+ transforms.RandomCrop(IMG_SIZE),
42
+ transforms.RandomHorizontalFlip(),
43
+ transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
44
+ transforms.ToTensor(),
45
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
46
+ ])
47
+
48
+ def __len__(self):
49
+ return len(self.images)
50
+
51
+ def __getitem__(self, idx):
52
+ img = self.images[idx].convert('RGB')
53
+ label = self.labels[idx]
54
+ if self.transform:
55
+ img = self.transform(img)
56
+ return img, label
57
+
58
+
59
+ class FineTuner:
60
+ """Handles model fine-tuning from user feedback."""
61
+
62
+ def __init__(self):
63
+ self.is_training = False
64
+ self.last_training: Optional[Dict] = None
65
+ self.training_history: List[Dict] = []
66
+ self._lock = threading.Lock()
67
+
68
+ def finetune(self, predictor, feedback_data: List[Dict],
69
+ supabase_service=None) -> Dict:
70
+ """
71
+ Fine-tune the model head using feedback data.
72
+
73
+ Args:
74
+ predictor: PlantDiseasePredictor instance with loaded model
75
+ feedback_data: List of dicts with 'image_url', 'actual_class'
76
+ supabase_service: Optional SupabaseService for downloading images
77
+
78
+ Returns:
79
+ Training result dict with metrics
80
+ """
81
+ with self._lock:
82
+ if self.is_training:
83
+ return {"status": "error", "message": "Training already in progress"}
84
+ self.is_training = True
85
+
86
+ try:
87
+ start_time = time.time()
88
+ class_names = predictor.class_names
89
+ class_to_idx = {name: i for i, name in enumerate(class_names)}
90
+
91
+ # Download and prepare images
92
+ images, labels = [], []
93
+ skipped = 0
94
+ for item in feedback_data:
95
+ actual_class = item.get("actual_class", "")
96
+ if actual_class not in class_to_idx:
97
+ skipped += 1
98
+ continue
99
+
100
+ img = self._load_image(item, supabase_service)
101
+ if img is None:
102
+ skipped += 1
103
+ continue
104
+
105
+ images.append(img)
106
+ labels.append(class_to_idx[actual_class])
107
+
108
+ if len(images) < MIN_SAMPLES:
109
+ return {
110
+ "status": "error",
111
+ "message": f"Need at least {MIN_SAMPLES} valid samples, got {len(images)}"
112
+ }
113
+
114
+ logger.info(f"Fine-tuning with {len(images)} samples ({skipped} skipped)")
115
+
116
+ # Create dataset with augmentation
117
+ train_dataset = FeedbackDataset(images, labels)
118
+ train_loader = DataLoader(
119
+ train_dataset, batch_size=FINETUNE_BATCH,
120
+ shuffle=True, num_workers=0
121
+ )
122
+
123
+ # Fine-tune only the head
124
+ model = predictor.model
125
+ model.train()
126
+
127
+ # Freeze backbone, unfreeze head
128
+ for param in model.backbone.parameters():
129
+ param.requires_grad = False
130
+ for param in model.head.parameters():
131
+ param.requires_grad = True
132
+
133
+ # Class weights for imbalanced feedback
134
+ label_counts = np.bincount(labels, minlength=len(class_names))
135
+ nonzero = label_counts > 0
136
+ weights = np.zeros(len(class_names), dtype=np.float32)
137
+ weights[nonzero] = len(labels) / (nonzero.sum() * label_counts[nonzero])
138
+ class_weights = torch.FloatTensor(weights).to(predictor.device)
139
+
140
+ optimizer = optim.AdamW(model.head.parameters(), lr=FINETUNE_LR, weight_decay=1e-4)
141
+ criterion = nn.CrossEntropyLoss(weight=class_weights, label_smoothing=0.05)
142
+
143
+ epoch_metrics = []
144
+ for epoch in range(FINETUNE_EPOCHS):
145
+ total_loss, correct, total = 0, 0, 0
146
+ for xb, yb in train_loader:
147
+ xb, yb = xb.to(predictor.device), yb.to(predictor.device)
148
+ optimizer.zero_grad()
149
+ logits = model(xb)
150
+ loss = criterion(logits, yb)
151
+ loss.backward()
152
+ optimizer.step()
153
+
154
+ total_loss += loss.item()
155
+ correct += (logits.argmax(1) == yb).sum().item()
156
+ total += len(yb)
157
+
158
+ acc = correct / total if total > 0 else 0
159
+ epoch_metrics.append({
160
+ "epoch": epoch + 1,
161
+ "loss": round(total_loss / len(train_loader), 4),
162
+ "accuracy": round(acc, 4)
163
+ })
164
+ logger.info(f"Epoch {epoch+1}/{FINETUNE_EPOCHS}: loss={epoch_metrics[-1]['loss']:.4f}, acc={acc:.2%}")
165
+
166
+ # Save fine-tuned model
167
+ model.eval()
168
+ os.makedirs(FINETUNE_DIR, exist_ok=True)
169
+
170
+ version = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
171
+ save_path = os.path.join(FINETUNE_DIR, f"model_v{version}.pt")
172
+ best_path = os.path.join(CHECKPOINT_DIR, "mobilenet_v3", "best_model.pt")
173
+
174
+ # Save versioned copy
175
+ ckpt = {
176
+ "model_state_dict": model.state_dict(),
177
+ "backbone_name": "mobilenetv3_large_100",
178
+ "num_classes": len(class_names),
179
+ "class_names": class_names,
180
+ "feat_dim": model.head[1].in_features,
181
+ "finetuned_from": "user_feedback",
182
+ "num_samples": len(images),
183
+ "version": version,
184
+ }
185
+ torch.save(ckpt, save_path)
186
+
187
+ # Overwrite best_model.pt for auto-loading on restart
188
+ torch.save(ckpt, best_path)
189
+ logger.info(f"Saved fine-tuned model: {save_path}")
190
+
191
+ elapsed = time.time() - start_time
192
+ result = {
193
+ "status": "success",
194
+ "version": version,
195
+ "samples_used": len(images),
196
+ "samples_skipped": skipped,
197
+ "epochs": FINETUNE_EPOCHS,
198
+ "final_loss": epoch_metrics[-1]["loss"],
199
+ "final_accuracy": epoch_metrics[-1]["accuracy"],
200
+ "training_time_seconds": round(elapsed, 1),
201
+ "epoch_metrics": epoch_metrics,
202
+ }
203
+
204
+ self.last_training = result
205
+ self.training_history.append(result)
206
+ return result
207
+
208
+ except Exception as e:
209
+ logger.error(f"Fine-tuning failed: {e}", exc_info=True)
210
+ return {"status": "error", "message": str(e)}
211
+ finally:
212
+ with self._lock:
213
+ self.is_training = False
214
+
215
+ def _load_image(self, item: Dict, supabase_service=None) -> Optional[Image.Image]:
216
+ """Load an image from URL or Supabase storage."""
217
+ image_url = item.get("image_url", "")
218
+ if not image_url:
219
+ return None
220
+
221
+ try:
222
+ import httpx
223
+ resp = httpx.get(image_url, timeout=15.0, follow_redirects=True)
224
+ resp.raise_for_status()
225
+ return Image.open(io.BytesIO(resp.content)).convert("RGB")
226
+ except Exception as e:
227
+ logger.warning(f"Failed to load image {image_url}: {e}")
228
+ return None
229
+
230
+
231
+ # Global instance
232
+ _finetuner: Optional[FineTuner] = None
233
+
234
+
235
+ def get_finetuner() -> FineTuner:
236
+ global _finetuner
237
+ if _finetuner is None:
238
+ _finetuner = FineTuner()
239
+ return _finetuner
backend/app/ml/gemini_validator.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gemini AI cross-validation service.
3
+ Validates MobileNetV3 predictions using Google Gemini with multimodal (image + text) input.
4
+ """
5
+ import json
6
+ import os
7
+ import time
8
+ import asyncio
9
+ from typing import Optional
10
+
11
+ from google import genai
12
+ from google.genai import types
13
+
14
+
15
+ MAX_RETRIES = 3
16
+ RETRY_BACKOFF = [1, 2, 4] # seconds between retries
17
+ AVAILABILITY_RECHECK_INTERVAL = 300 # re-check every 5 minutes if unavailable
18
+
19
+
20
+ SYSTEM_PROMPT = """You are an expert plant pathologist AI assistant. Your role is to cross-validate
21
+ plant disease predictions made by a MobileNetV3 computer vision model.
22
+
23
+ You will receive:
24
+ 1. The actual leaf image for visual inspection
25
+ 2. The model's predicted disease class and confidence
26
+ 3. Top alternative predictions with probabilities
27
+ 4. Image metadata (brightness, contrast, color distribution, dimensions)
28
+
29
+ Your job is to:
30
+ - Visually inspect the leaf image for disease symptoms (spots, lesions, discoloration, wilting, etc.)
31
+ - Assess whether the prediction is reasonable given what you see in the image
32
+ - Provide a confidence assessment (High, Moderate, or Low)
33
+ - Explain your reasoning based on visible disease symptoms
34
+ - Suggest alternative diseases if the prediction seems off
35
+ - Provide practical treatment advice for the predicted disease
36
+
37
+ IMPORTANT: Respond ONLY in valid JSON with exactly these fields:
38
+ {
39
+ "agrees": true/false,
40
+ "confidence_assessment": "High/Moderate/Low — brief explanation",
41
+ "reasoning": "2-3 sentences explaining why you agree or disagree based on visual symptoms",
42
+ "alternative_suggestions": ["list", "of", "alternatives"] or [],
43
+ "treatment_advice": "Practical treatment steps",
44
+ "summary": "One-line summary of your validation"
45
+ }
46
+
47
+ Do NOT include any text outside the JSON object. No explanations, no markdown, just the JSON."""
48
+
49
+
50
+ def _build_prompt(prediction: dict, image_metadata: dict) -> str:
51
+ """Build the text prompt for Gemini validation."""
52
+ top_k_str = "\n".join(
53
+ f" {i+1}. {p['class']} — {p['probability']*100:.1f}%"
54
+ for i, p in enumerate(prediction.get("top_k", []))
55
+ )
56
+
57
+ return f"""Validate this plant disease prediction by examining the leaf image I've provided:
58
+
59
+ **MobileNetV3 Prediction:**
60
+ - Disease: {prediction['class']}
61
+ - Confidence: {prediction['probability']*100:.1f}%
62
+ - Uncertainty: {prediction['uncertainty']*100:.1f}%
63
+
64
+ **Top-K Alternatives:**
65
+ {top_k_str}
66
+
67
+ **Image Metadata:**
68
+ - Dimensions: {image_metadata.get('width', '?')}x{image_metadata.get('height', '?')} pixels
69
+ - Brightness: {image_metadata.get('brightness', '?')} (0=dark, 1=bright)
70
+ - Contrast: {image_metadata.get('contrast', '?')} (0=flat, 1=high)
71
+ - Dominant color: {image_metadata.get('dominant_color', '?')}
72
+ - Green ratio: {image_metadata.get('green_ratio', '?')} (higher = more green/leaf content)
73
+ - RGB means: R={image_metadata.get('r_mean', '?')}, G={image_metadata.get('g_mean', '?')}, B={image_metadata.get('b_mean', '?')}
74
+
75
+ Look at the leaf image carefully and respond with your validation JSON:"""
76
+
77
+
78
+ def _parse_gemini_response(response_text: str) -> Optional[dict]:
79
+ """Parse Gemini JSON response, handling markdown code blocks and extra text."""
80
+ text = response_text.strip()
81
+
82
+ # Strip markdown code fences if present
83
+ if text.startswith("```"):
84
+ lines = text.split("\n")
85
+ lines = [ln for ln in lines if not ln.strip().startswith("```")]
86
+ text = "\n".join(lines).strip()
87
+
88
+ try:
89
+ data = json.loads(text)
90
+ except json.JSONDecodeError:
91
+ # Try to find JSON within the text
92
+ start = text.find("{")
93
+ end = text.rfind("}") + 1
94
+ if start >= 0 and end > start:
95
+ try:
96
+ data = json.loads(text[start:end])
97
+ except json.JSONDecodeError:
98
+ return None
99
+ else:
100
+ return None
101
+
102
+ required = ["agrees", "confidence_assessment", "reasoning", "summary"]
103
+ if not all(k in data for k in required):
104
+ return None
105
+
106
+ return {
107
+ "agrees": bool(data["agrees"]),
108
+ "confidence_assessment": str(data["confidence_assessment"]),
109
+ "reasoning": str(data["reasoning"]),
110
+ "alternative_suggestions": list(data.get("alternative_suggestions", [])),
111
+ "treatment_advice": str(data.get("treatment_advice", "")),
112
+ "summary": str(data["summary"]),
113
+ }
114
+
115
+
116
+ class GeminiValidator:
117
+ """Validates MobileNetV3 predictions using Google Gemini with multimodal input."""
118
+
119
+ def __init__(self, api_key: str, model_name: str = "gemini-2.5-flash"):
120
+ self.model_name = model_name
121
+ self._available = False
122
+ self._last_availability_check = 0
123
+ try:
124
+ self._client = genai.Client(api_key=api_key)
125
+ self._available = True
126
+ print(f"✓ Gemini client initialized: {self.model_name}")
127
+ except Exception as e:
128
+ print(f"⚠️ Gemini client initialization failed: {e}")
129
+ self._client = None
130
+
131
+ def check_availability(self) -> bool:
132
+ """Verify Gemini API is reachable with a lightweight call."""
133
+ if not self._client:
134
+ self._available = False
135
+ return False
136
+ try:
137
+ response = self._client.models.generate_content(
138
+ model=self.model_name,
139
+ contents="Reply with only the word: OK",
140
+ config=types.GenerateContentConfig(
141
+ max_output_tokens=5,
142
+ ),
143
+ )
144
+ self._available = response.text is not None
145
+ self._last_availability_check = time.time()
146
+ if self._available:
147
+ print(f"✓ Gemini API reachable: {self.model_name}")
148
+ return self._available
149
+ except Exception as e:
150
+ print(f"⚠️ Gemini API not reachable: {e}")
151
+ self._available = False
152
+ self._last_availability_check = time.time()
153
+ return False
154
+
155
+ def _ensure_available(self) -> bool:
156
+ """Re-check availability if previously unavailable and enough time has passed."""
157
+ if self._available:
158
+ return True
159
+ if not self._client:
160
+ return False
161
+ elapsed = time.time() - self._last_availability_check
162
+ if elapsed >= AVAILABILITY_RECHECK_INTERVAL:
163
+ print("🔄 Re-checking Gemini availability...")
164
+ return self.check_availability()
165
+ return False
166
+
167
+ @property
168
+ def is_available(self) -> bool:
169
+ return self._ensure_available()
170
+
171
+ def validate(
172
+ self, prediction: dict, image_metadata: dict, image_bytes: bytes = None
173
+ ) -> Optional[dict]:
174
+ """
175
+ Validate a MobileNet prediction with Gemini (multimodal: image + text).
176
+ Retries up to MAX_RETRIES times on transient failures.
177
+ """
178
+ if not self._ensure_available():
179
+ return None
180
+
181
+ prompt_text = _build_prompt(prediction, image_metadata)
182
+
183
+ contents = []
184
+ if image_bytes:
185
+ contents.append(
186
+ types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg")
187
+ )
188
+ contents.append(prompt_text)
189
+
190
+ for attempt in range(MAX_RETRIES):
191
+ try:
192
+ response = self._client.models.generate_content(
193
+ model=self.model_name,
194
+ contents=contents,
195
+ config=types.GenerateContentConfig(
196
+ system_instruction=SYSTEM_PROMPT,
197
+ temperature=0.3,
198
+ max_output_tokens=4096,
199
+ ),
200
+ )
201
+ content = response.text
202
+ if not content:
203
+ print(f"Gemini returned empty response (attempt {attempt + 1})")
204
+ if attempt < MAX_RETRIES - 1:
205
+ time.sleep(RETRY_BACKOFF[attempt])
206
+ continue
207
+ return None
208
+
209
+ parsed = _parse_gemini_response(content)
210
+ if parsed is None:
211
+ print(f"Gemini response parse failed (attempt {attempt + 1}). Raw: {content[:300]}")
212
+ if attempt < MAX_RETRIES - 1:
213
+ time.sleep(RETRY_BACKOFF[attempt])
214
+ continue
215
+ return parsed
216
+
217
+ except Exception as e:
218
+ error_str = str(e).lower()
219
+ is_rate_limit = "429" in error_str or "rate" in error_str or "quota" in error_str
220
+ print(f"Gemini validation error (attempt {attempt + 1}/{MAX_RETRIES}): {e}")
221
+
222
+ if is_rate_limit:
223
+ wait = RETRY_BACKOFF[attempt] * 2
224
+ print(f" → Rate limited, waiting {wait}s before retry...")
225
+ if attempt < MAX_RETRIES - 1:
226
+ time.sleep(wait)
227
+ continue
228
+ self._available = False
229
+ self._last_availability_check = time.time()
230
+ return None
231
+
232
+ if attempt < MAX_RETRIES - 1:
233
+ time.sleep(RETRY_BACKOFF[attempt])
234
+ continue
235
+ return None
236
+
237
+ return None
238
+
239
+ async def validate_async(
240
+ self, prediction: dict, image_metadata: dict, image_bytes: bytes = None
241
+ ) -> Optional[dict]:
242
+ """Async wrapper around validate() for use in FastAPI endpoints."""
243
+ loop = asyncio.get_event_loop()
244
+ return await loop.run_in_executor(
245
+ None, self.validate, prediction, image_metadata, image_bytes
246
+ )
247
+
248
+
249
+ # Global validator instance
250
+ _validator: Optional[GeminiValidator] = None
251
+
252
+
253
+ def get_validator() -> GeminiValidator:
254
+ """Get or create the global Gemini validator instance."""
255
+ global _validator
256
+ if _validator is None:
257
+ api_key = os.getenv("GEMINI_API_KEY", "")
258
+ model = os.getenv("GEMINI_MODEL", "gemini-2.5-flash")
259
+ _validator = GeminiValidator(api_key=api_key, model_name=model)
260
+ return _validator
backend/app/ml/predictor.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ML Inference Engine — MobileNetV3 plant disease classifier.
3
+ Returns probabilities with uncertainty estimates and image metadata for LLM validation.
4
+ """
5
+ import os
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn as nn
13
+ from PIL import Image, ImageStat
14
+ from torchvision import transforms
15
+ import timm
16
+
17
+ import sys
18
+ sys.path.insert(0, str(Path(__file__).parent.parent.parent.parent))
19
+
20
+
21
+ class FlexibleModel(nn.Module):
22
+ """MobileNetV3 with frozen backbone and trainable classification head."""
23
+ def __init__(self, backbone_name: str, num_classes: int, feat_dim: int = None):
24
+ super().__init__()
25
+ self.backbone = timm.create_model(backbone_name, pretrained=False, num_classes=0)
26
+ if feat_dim is None:
27
+ with torch.no_grad():
28
+ feat_dim = self.backbone(torch.randn(1, 3, 224, 224)).shape[1]
29
+ self.head = nn.Sequential(
30
+ nn.Dropout(0.3),
31
+ nn.Linear(feat_dim, 512),
32
+ nn.ReLU(),
33
+ nn.BatchNorm1d(512),
34
+ nn.Dropout(0.2),
35
+ nn.Linear(512, num_classes)
36
+ )
37
+
38
+ def forward(self, x):
39
+ feat = self.backbone(x)
40
+ return self.head(feat)
41
+
42
+
43
+ class PlantDiseasePredictor:
44
+ """
45
+ Production inference engine using MobileNetV3 for plant disease classification.
46
+ Extracts image metadata for LLM cross-validation.
47
+ """
48
+
49
+ def __init__(self, device: str = "auto"):
50
+ if device == "auto":
51
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
52
+ else:
53
+ self.device = torch.device(device)
54
+
55
+ self.model = None
56
+ self.class_names = []
57
+ self.num_classes = 0
58
+ self.transform = None
59
+ self._loaded = False
60
+
61
+ def _load_model_from_checkpoint(self, ckpt):
62
+ """Load MobileNetV3 from checkpoint."""
63
+ num_classes = ckpt['num_classes']
64
+
65
+ if 'backbone_name' in ckpt:
66
+ model = FlexibleModel(
67
+ ckpt['backbone_name'],
68
+ num_classes,
69
+ feat_dim=ckpt.get('feat_dim')
70
+ )
71
+ model.load_state_dict(ckpt['model_state_dict'])
72
+ elif 'model_type' in ckpt:
73
+ try:
74
+ from ml_pipeline.models.architectures import create_model
75
+ model = create_model(
76
+ ckpt['model_type'],
77
+ num_classes=num_classes,
78
+ pretrained=False, dropout=0.0
79
+ )
80
+ model.load_state_dict(ckpt['model_state_dict'])
81
+ except Exception:
82
+ raise ValueError(f"Cannot load model_type={ckpt.get('model_type')}")
83
+ else:
84
+ raise ValueError("Unknown checkpoint format")
85
+
86
+ return model
87
+
88
+ def load(self, models_dir: str = "checkpoints"):
89
+ """Load MobileNetV3 model from checkpoint directory."""
90
+ # Load class names
91
+ class_names_path = os.path.join(models_dir, "class_names.json")
92
+ if os.path.exists(class_names_path):
93
+ with open(class_names_path) as f:
94
+ self.class_names = json.load(f)
95
+ self.num_classes = len(self.class_names)
96
+ print(f"Loaded {self.num_classes} class names")
97
+
98
+ # Load MobileNetV3 checkpoint
99
+ ckpt_path = os.path.join(models_dir, "mobilenet_v3", "best_model.pt")
100
+ if not os.path.exists(ckpt_path):
101
+ raise FileNotFoundError(f"MobileNetV3 checkpoint not found: {ckpt_path}")
102
+
103
+ ckpt = torch.load(ckpt_path, map_location=self.device, weights_only=False)
104
+ self.model = self._load_model_from_checkpoint(ckpt)
105
+ self.model.to(self.device).eval()
106
+
107
+ if not self.class_names and 'class_names' in ckpt:
108
+ self.class_names = ckpt['class_names']
109
+ self.num_classes = len(self.class_names)
110
+
111
+ if not self.num_classes:
112
+ self.num_classes = ckpt['num_classes']
113
+
114
+ # Fallback class names
115
+ if not self.class_names:
116
+ try:
117
+ from ml_pipeline.data.dataset import PLANTVILLAGE_CLASSES
118
+ self.class_names = PLANTVILLAGE_CLASSES
119
+ self.num_classes = len(self.class_names)
120
+ except ImportError:
121
+ self.class_names = [f"class_{i}" for i in range(self.num_classes or 38)]
122
+ self.num_classes = len(self.class_names)
123
+
124
+ self.transform = transforms.Compose([
125
+ transforms.Resize((224, 224)),
126
+ transforms.ToTensor(),
127
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
128
+ ])
129
+
130
+ self._loaded = True
131
+ val_f1 = ckpt.get('val_f1', 'N/A')
132
+ print(f"MobileNetV3 ready: {self.num_classes} classes on {self.device} (val_f1={val_f1})")
133
+
134
+ def extract_image_metadata(self, image: Image.Image) -> dict:
135
+ """Extract image metadata for LLM validation context."""
136
+ rgb = image.convert('RGB')
137
+ stat = ImageStat.Stat(rgb)
138
+ r_mean, g_mean, b_mean = stat.mean
139
+ brightness = sum(stat.mean) / 3.0 / 255.0
140
+ contrast = sum(stat.stddev) / 3.0 / 255.0
141
+
142
+ # Dominant color channel
143
+ channels = {'red': r_mean, 'green': g_mean, 'blue': b_mean}
144
+ dominant = max(channels, key=channels.get)
145
+
146
+ # Green ratio (useful for plant/leaf detection)
147
+ total = r_mean + g_mean + b_mean
148
+ green_ratio = g_mean / total if total > 0 else 0
149
+
150
+ return {
151
+ "width": image.width,
152
+ "height": image.height,
153
+ "brightness": round(brightness, 3),
154
+ "contrast": round(contrast, 3),
155
+ "dominant_color": dominant,
156
+ "green_ratio": round(green_ratio, 3),
157
+ "r_mean": round(r_mean, 1),
158
+ "g_mean": round(g_mean, 1),
159
+ "b_mean": round(b_mean, 1),
160
+ }
161
+
162
+ def preprocess(self, image: Image.Image) -> torch.Tensor:
163
+ """Preprocess a PIL image for inference."""
164
+ if image.mode != 'RGB':
165
+ image = image.convert('RGB')
166
+ tensor = self.transform(image).unsqueeze(0).to(self.device)
167
+ return tensor
168
+
169
+ @torch.no_grad()
170
+ def predict(self, image: Image.Image, top_k: int = 5) -> dict:
171
+ """
172
+ Run MobileNetV3 prediction on a single image.
173
+ Returns prediction with class, probability, uncertainty, top-k, and image metadata.
174
+ """
175
+ if not self._loaded:
176
+ raise RuntimeError("Model not loaded. Call load() first.")
177
+
178
+ tensor = self.preprocess(image)
179
+ logits = self.model(tensor).cpu().numpy()
180
+ probs = self._softmax(logits)[0]
181
+
182
+ # Entropy-based uncertainty
183
+ pred_entropy = -(probs * np.log(probs + 1e-10)).sum()
184
+ max_entropy = np.log(len(probs))
185
+ uncertainty = float(pred_entropy / max_entropy)
186
+
187
+ # Top-k predictions
188
+ top_k_indices = np.argsort(probs)[::-1][:top_k]
189
+ top_k_predictions = []
190
+ for idx in top_k_indices:
191
+ class_name = self.class_names[idx] if idx < len(self.class_names) else f"class_{idx}"
192
+ top_k_predictions.append({
193
+ "class": class_name,
194
+ "probability": float(probs[idx]),
195
+ })
196
+
197
+ best_idx = top_k_indices[0]
198
+ image_metadata = self.extract_image_metadata(image)
199
+
200
+ result = {
201
+ "class": self.class_names[best_idx] if best_idx < len(self.class_names) else f"class_{best_idx}",
202
+ "probability": float(probs[best_idx]),
203
+ "uncertainty": round(uncertainty, 4),
204
+ "top_k": top_k_predictions,
205
+ "image_metadata": image_metadata,
206
+ }
207
+
208
+ return result
209
+
210
+ @staticmethod
211
+ def _softmax(logits):
212
+ exp = np.exp(logits - logits.max(axis=1, keepdims=True))
213
+ return exp / exp.sum(axis=1, keepdims=True)
214
+
215
+
216
+ # Global predictor instance
217
+ _predictor: Optional[PlantDiseasePredictor] = None
218
+
219
+
220
+ def get_predictor() -> PlantDiseasePredictor:
221
+ """Get or create the global predictor instance."""
222
+ global _predictor
223
+ if _predictor is None:
224
+ _predictor = PlantDiseasePredictor()
225
+ return _predictor
backend/app/models/__init__.py ADDED
File without changes
backend/app/models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (193 Bytes). View file
 
backend/app/models/__pycache__/schemas.cpython-311.pyc ADDED
Binary file (6.03 kB). View file
 
backend/app/models/schemas.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pydantic models for API request/response schemas."""
2
+ from typing import List, Optional
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class PredictionItem(BaseModel):
7
+ class_name: str = Field(..., alias="class", description="Disease class name")
8
+ probability: float = Field(..., ge=0, le=1, description="Calibrated probability")
9
+
10
+ class Config:
11
+ populate_by_name = True
12
+
13
+
14
+ class GeminiValidation(BaseModel):
15
+ """Gemini AI cross-validation report for MobileNet predictions."""
16
+ agrees: bool = Field(..., description="Whether Gemini agrees with MobileNet prediction")
17
+ confidence_assessment: str = Field(..., description="Gemini's assessment of prediction confidence")
18
+ reasoning: str = Field(..., description="Explanation based on visual inspection of the leaf image")
19
+ alternative_suggestions: List[str] = Field(default_factory=list, description="Alternative diseases to consider")
20
+ treatment_advice: str = Field(default="", description="Recommended treatment or next steps")
21
+ summary: str = Field(..., description="Brief one-line validation summary")
22
+
23
+ class Config:
24
+ json_schema_extra = {
25
+ "example": {
26
+ "agrees": True,
27
+ "confidence_assessment": "High — the visible symptoms align well with the predicted disease.",
28
+ "reasoning": "The leaf image shows brown necrotic lesions with concentric rings on tomato leaves, which is highly consistent with Early Blight caused by Alternaria solani.",
29
+ "alternative_suggestions": ["Tomato___Septoria_leaf_spot"],
30
+ "treatment_advice": "Apply copper-based fungicide. Remove affected leaves. Improve air circulation around plants. Avoid overhead watering.",
31
+ "summary": "Prediction confirmed: Early Blight on Tomato with high confidence."
32
+ }
33
+ }
34
+
35
+
36
+ class PredictionResponse(BaseModel):
37
+ """Main prediction response with Gemini AI validation."""
38
+ class_name: str = Field(..., alias="class", description="Predicted disease class")
39
+ probability: float = Field(..., ge=0, le=1, description="Model probability")
40
+ uncertainty: float = Field(..., ge=0, le=1, description="Uncertainty score (0=confident, 1=uncertain)")
41
+ top_k: List[PredictionItem] = Field(default_factory=list, description="Top-k predictions")
42
+ gemini_validation: Optional[GeminiValidation] = Field(default=None, description="Gemini AI cross-validation report")
43
+ image_url: Optional[str] = Field(default=None, description="Supabase storage URL of the uploaded image")
44
+
45
+ class Config:
46
+ populate_by_name = True
47
+ json_schema_extra = {
48
+ "example": {
49
+ "class": "Tomato___Early_blight",
50
+ "probability": 0.92,
51
+ "uncertainty": 0.08,
52
+ "top_k": [
53
+ {"class": "Tomato___Early_blight", "probability": 0.92},
54
+ {"class": "Tomato___Late_blight", "probability": 0.05},
55
+ {"class": "Tomato___Bacterial_spot", "probability": 0.02},
56
+ ],
57
+ "gemini_validation": None,
58
+ }
59
+ }
60
+
61
+
62
+ class HealthResponse(BaseModel):
63
+ status: str
64
+ model_loaded: bool
65
+ gemini_available: bool
66
+ device: str
67
+
68
+
69
+ class UserProfile(BaseModel):
70
+ id: str
71
+ email: str
72
+ display_name: Optional[str] = None
73
+
74
+
75
+ class PredictionHistory(BaseModel):
76
+ id: Optional[str] = None
77
+ user_id: str
78
+ image_url: Optional[str] = None
79
+ prediction_class: str
80
+ probability: float
81
+ uncertainty: float
82
+ top_k: Optional[List[dict]] = None
83
+ created_at: Optional[str] = None
backend/app/services/__init__.py ADDED
File without changes
backend/app/services/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (195 Bytes). View file
 
backend/app/services/__pycache__/supabase_service.cpython-311.pyc ADDED
Binary file (14.9 kB). View file
 
backend/app/services/supabase_service.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Supabase service for authentication and data storage."""
2
+ import os
3
+ import logging
4
+ from typing import Optional, List
5
+ from datetime import datetime
6
+ import json
7
+
8
+ from dotenv import load_dotenv
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ # Load .env from backend directory (handles running from project root)
13
+ load_dotenv(os.path.join(os.path.dirname(__file__), '..', '..', '.env'))
14
+ load_dotenv() # Also check CWD
15
+
16
+ SUPABASE_URL = os.getenv("SUPABASE_URL", "")
17
+ SUPABASE_KEY = os.getenv("SUPABASE_KEY", "")
18
+ SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_KEY", "")
19
+
20
+
21
+ class SupabaseService:
22
+ """Supabase client wrapper for auth, database, and storage."""
23
+
24
+ def __init__(self):
25
+ self.client = None
26
+ self._initialized = False
27
+
28
+ def initialize(self):
29
+ """Initialize Supabase client."""
30
+ if not SUPABASE_URL or not SUPABASE_KEY:
31
+ print("⚠️ Supabase not configured. Set SUPABASE_URL and SUPABASE_KEY env vars.")
32
+ print(" The app will work without Supabase (no auth/history).")
33
+ return
34
+
35
+ try:
36
+ from supabase import create_client
37
+ # Anon client for auth (token verification)
38
+ self.client = create_client(SUPABASE_URL, SUPABASE_KEY)
39
+ # Service role client for DB/storage (bypasses RLS)
40
+ if SUPABASE_SERVICE_KEY:
41
+ self._admin_client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
42
+ else:
43
+ self._admin_client = self.client
44
+ print("⚠️ No SUPABASE_SERVICE_KEY — using anon key for DB ops (RLS may block writes)")
45
+ self._initialized = True
46
+ print("✓ Supabase connected")
47
+ except Exception as e:
48
+ print(f"⚠️ Supabase init failed: {e}")
49
+
50
+ @property
51
+ def is_available(self) -> bool:
52
+ return self._initialized and self.client is not None
53
+
54
+ # --- Auth ---
55
+ def verify_token(self, token: str) -> Optional[dict]:
56
+ """Verify a Supabase JWT token and return user info."""
57
+ if not self.is_available:
58
+ logger.warning("verify_token called but Supabase not available")
59
+ return None
60
+ try:
61
+ user = self.client.auth.get_user(token)
62
+ return {"id": user.user.id, "email": user.user.email}
63
+ except Exception as e:
64
+ logger.error(f"Token verification failed: {e}")
65
+ return None
66
+
67
+ def sign_up(self, email: str, password: str) -> dict:
68
+ if not self.is_available:
69
+ return {"error": "Supabase not configured"}
70
+ try:
71
+ res = self.client.auth.sign_up({"email": email, "password": password})
72
+ return {"user_id": res.user.id, "email": res.user.email}
73
+ except Exception as e:
74
+ return {"error": str(e)}
75
+
76
+ def sign_in(self, email: str, password: str) -> dict:
77
+ if not self.is_available:
78
+ return {"error": "Supabase not configured"}
79
+ try:
80
+ res = self.client.auth.sign_in_with_password({"email": email, "password": password})
81
+ return {
82
+ "access_token": res.session.access_token,
83
+ "refresh_token": res.session.refresh_token,
84
+ "user_id": res.user.id,
85
+ "email": res.user.email,
86
+ }
87
+ except Exception as e:
88
+ return {"error": str(e)}
89
+
90
+ # --- Prediction History ---
91
+ def save_prediction(self, user_id: str, prediction: dict,
92
+ image_url: Optional[str] = None,
93
+ gemini_validation: Optional[dict] = None) -> dict:
94
+ """Save a prediction to history."""
95
+ if not self.is_available:
96
+ return {"status": "skipped", "reason": "supabase_not_configured"}
97
+ try:
98
+ data = {
99
+ "user_id": user_id,
100
+ "prediction_class": prediction.get("class", ""),
101
+ "probability": prediction.get("probability", 0),
102
+ "uncertainty": prediction.get("uncertainty", 0),
103
+ "top_k": json.dumps(prediction.get("top_k", [])),
104
+ "image_url": image_url,
105
+ "created_at": datetime.utcnow().isoformat(),
106
+ }
107
+ if gemini_validation is not None:
108
+ data["gemini_validation"] = json.dumps(gemini_validation)
109
+ result = self._admin_client.table("predictions").insert(data).execute()
110
+ return {"status": "saved", "id": result.data[0]["id"] if result.data else None}
111
+ except Exception as e:
112
+ return {"status": "error", "error": str(e)}
113
+
114
+ def get_history(self, user_id: str, limit: int = 20) -> List[dict]:
115
+ """Get prediction history for a user."""
116
+ if not self.is_available:
117
+ logger.warning("get_history called but Supabase not available")
118
+ return []
119
+ try:
120
+ result = (
121
+ self._admin_client.table("predictions")
122
+ .select("*")
123
+ .eq("user_id", user_id)
124
+ .order("created_at", desc=True)
125
+ .limit(limit)
126
+ .execute()
127
+ )
128
+ return result.data or []
129
+ except Exception as e:
130
+ logger.error(f"Failed to get history: {e}")
131
+ return []
132
+
133
+ # --- Image Storage ---
134
+ def upload_image(self, file_bytes: bytes, filename: str, user_id: str) -> Optional[str]:
135
+ """Upload image to Supabase Storage and return URL."""
136
+ if not self.is_available:
137
+ return None
138
+ try:
139
+ import uuid
140
+ ext = filename.rsplit('.', 1)[-1] if '.' in filename else 'jpg'
141
+ unique_name = f"{uuid.uuid4().hex}.{ext}"
142
+ path = f"{user_id}/{unique_name}"
143
+ self._admin_client.storage.from_("plant-images").upload(
144
+ path, file_bytes,
145
+ file_options={"content-type": f"image/{ext}", "upsert": "true"}
146
+ )
147
+ url = self._admin_client.storage.from_("plant-images").get_public_url(path)
148
+ return url
149
+ except Exception as e:
150
+ logger.error(f"Image upload failed: {e}")
151
+ return None
152
+
153
+ def get_stats(self, user_id: str) -> dict:
154
+ """Get user prediction statistics."""
155
+ if not self.is_available:
156
+ return {"total": 0, "diseases_detected": 0}
157
+ try:
158
+ result = (
159
+ self._admin_client.table("predictions")
160
+ .select("prediction_class")
161
+ .eq("user_id", user_id)
162
+ .execute()
163
+ )
164
+ data = result.data or []
165
+ unique_diseases = len(set(d["prediction_class"] for d in data))
166
+ return {"total": len(data), "diseases_detected": unique_diseases}
167
+ except Exception:
168
+ return {"total": 0, "diseases_detected": 0}
169
+
170
+ # --- Training Feedback ---
171
+ def save_feedback(self, user_id: Optional[str], prediction_id: Optional[str],
172
+ image_url: str, predicted_class: str,
173
+ actual_class: str, is_correct: bool) -> dict:
174
+ """Save user feedback on a prediction for model training."""
175
+ if not self.is_available:
176
+ return {"status": "skipped", "reason": "supabase_not_configured"}
177
+ try:
178
+ data = {
179
+ "predicted_class": predicted_class,
180
+ "actual_class": actual_class,
181
+ "is_correct": is_correct,
182
+ "created_at": datetime.utcnow().isoformat(),
183
+ }
184
+ if user_id and user_id != "anonymous":
185
+ data["user_id"] = user_id
186
+ if prediction_id:
187
+ data["prediction_id"] = prediction_id
188
+ if image_url:
189
+ data["image_url"] = image_url
190
+ result = self._admin_client.table("training_feedback").insert(data).execute()
191
+ return {"status": "saved", "id": result.data[0]["id"] if result.data else None}
192
+ except Exception as e:
193
+ logger.error(f"Failed to save feedback: {e}")
194
+ return {"status": "error", "error": str(e)}
195
+
196
+ def get_feedback(self, limit: int = 500) -> List[dict]:
197
+ """Get all training feedback (for fine-tuning)."""
198
+ if not self.is_available:
199
+ return []
200
+ try:
201
+ result = (
202
+ self._admin_client.table("training_feedback")
203
+ .select("*")
204
+ .order("created_at", desc=True)
205
+ .limit(limit)
206
+ .execute()
207
+ )
208
+ return result.data or []
209
+ except Exception as e:
210
+ logger.error(f"Failed to get feedback: {e}")
211
+ return []
212
+
213
+ def get_feedback_stats(self) -> dict:
214
+ """Get feedback statistics for training dashboard."""
215
+ if not self.is_available:
216
+ return {"total": 0, "correct": 0, "incorrect": 0, "classes": {}}
217
+ try:
218
+ result = (
219
+ self._admin_client.table("training_feedback")
220
+ .select("*")
221
+ .execute()
222
+ )
223
+ data = result.data or []
224
+ correct = sum(1 for d in data if d.get("is_correct"))
225
+ incorrect = len(data) - correct
226
+ classes = {}
227
+ for d in data:
228
+ cls = d.get("actual_class", "unknown")
229
+ classes[cls] = classes.get(cls, 0) + 1
230
+ return {
231
+ "total": len(data),
232
+ "correct": correct,
233
+ "incorrect": incorrect,
234
+ "classes": classes,
235
+ }
236
+ except Exception as e:
237
+ logger.error(f"Failed to get feedback stats: {e}")
238
+ return {"total": 0, "correct": 0, "incorrect": 0, "classes": {}}
239
+
240
+
241
+ # Global instance
242
+ supabase_service = SupabaseService()
backend/requirements.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Backend Dependencies
2
+ fastapi>=0.104.0
3
+ uvicorn[standard]>=0.24.0
4
+ python-multipart>=0.0.6
5
+ Pillow>=10.0.0
6
+ numpy>=1.24.0
7
+ pydantic>=2.5.0
8
+ supabase>=2.0.0
9
+ python-dotenv>=1.0.0
10
+ prometheus-client>=0.19.0
11
+ sentry-sdk[fastapi]>=1.38.0
12
+ httpx>=0.25.0
13
+ pyyaml>=6.0
14
+ google-genai>=1.0.0
15
+
16
+ # PyTorch CPU-only (much smaller than CUDA version for deployment)
17
+ --extra-index-url https://download.pytorch.org/whl/cpu
18
+ torch>=2.1.0
19
+ torchvision>=0.16.0
20
+ timm>=0.9.12
backend/start.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Startup script for Railway deployment
3
+
4
+ echo "Starting PlantGuard API..."
5
+ echo "PORT=${PORT:-8000}"
6
+
7
+ exec uvicorn backend.app.main:app --host 0.0.0.0 --port "${PORT:-8000}"
checkpoints/class_names.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ "Apple___Apple_scab",
3
+ "Apple___Black_rot",
4
+ "Apple___Cedar_apple_rust",
5
+ "Apple___healthy",
6
+ "Blueberry___healthy",
7
+ "Cherry_(including_sour)___Powdery_mildew",
8
+ "Cherry_(including_sour)___healthy",
9
+ "Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot",
10
+ "Corn_(maize)___Common_rust_",
11
+ "Corn_(maize)___Northern_Leaf_Blight",
12
+ "Corn_(maize)___healthy",
13
+ "Grape___Black_rot",
14
+ "Grape___Esca_(Black_Measles)",
15
+ "Grape___Leaf_blight_(Isariopsis_Leaf_Spot)",
16
+ "Grape___healthy",
17
+ "Orange___Haunglongbing_(Citrus_greening)",
18
+ "Peach___Bacterial_spot",
19
+ "Peach___healthy",
20
+ "Pepper,_bell___Bacterial_spot",
21
+ "Pepper,_bell___healthy",
22
+ "Potato___Early_blight",
23
+ "Potato___Late_blight",
24
+ "Potato___healthy",
25
+ "Raspberry___healthy",
26
+ "Soybean___healthy",
27
+ "Squash___Powdery_mildew",
28
+ "Strawberry___Leaf_scorch",
29
+ "Strawberry___healthy",
30
+ "Tomato___Bacterial_spot",
31
+ "Tomato___Early_blight",
32
+ "Tomato___Late_blight",
33
+ "Tomato___Leaf_Mold",
34
+ "Tomato___Septoria_leaf_spot",
35
+ "Tomato___Spider_mites Two-spotted_spider_mite",
36
+ "Tomato___Target_Spot",
37
+ "Tomato___Tomato_Yellow_Leaf_Curl_Virus",
38
+ "Tomato___Tomato_mosaic_virus",
39
+ "Tomato___healthy"
40
+ ]
checkpoints/mobilenet_v3/best_model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:656e2323ef885eb869b0eee588b541166b7d18d07e2c008ef0fc0e24668be2e2
3
+ size 19728464
checkpoints/mobilenet_v3/training_history.json ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "epoch": 1,
4
+ "train_loss": 1.4754562307751535,
5
+ "train_acc": 0.7657695232954684,
6
+ "val_loss": 1.0507514628709531,
7
+ "val_acc": 0.8720629843769221,
8
+ "val_f1": 0.839838479693271,
9
+ "time": 2134.799591779709
10
+ },
11
+ {
12
+ "epoch": 2,
13
+ "train_loss": 1.1581421535187277,
14
+ "train_acc": 0.8464633577860105,
15
+ "val_loss": 0.9508979570631887,
16
+ "val_acc": 0.8804280969368926,
17
+ "val_f1": 0.877772828468893,
18
+ "time": 1520.8893296718597
19
+ },
20
+ {
21
+ "epoch": 3,
22
+ "train_loss": 1.0474498474990928,
23
+ "train_acc": 0.8790941877867465,
24
+ "val_loss": 0.9237516089981678,
25
+ "val_acc": 0.9143806126214786,
26
+ "val_f1": 0.8952668643192974,
27
+ "time": 1455.7170903682709
28
+ },
29
+ {
30
+ "epoch": 4,
31
+ "train_loss": 1.0000751933647287,
32
+ "train_acc": 0.894894379155524,
33
+ "val_loss": 0.8974116262267617,
34
+ "val_acc": 0.9227457251814492,
35
+ "val_f1": 0.8968918629162261,
36
+ "time": 1407.9666616916656
37
+ },
38
+ {
39
+ "epoch": 5,
40
+ "train_loss": 0.9811938846691437,
41
+ "train_acc": 0.8995068573811918,
42
+ "val_loss": 0.8841090396338818,
43
+ "val_acc": 0.9443966047484316,
44
+ "val_f1": 0.926687092394606,
45
+ "time": 1396.372747182846
46
+ },
47
+ {
48
+ "epoch": 6,
49
+ "train_loss": 0.9563302820200449,
50
+ "train_acc": 0.9098849333889448,
51
+ "val_loss": 0.8687813504069459,
52
+ "val_acc": 0.9404600811907984,
53
+ "val_f1": 0.9187613017763079,
54
+ "time": 1463.5929679870605
55
+ },
56
+ {
57
+ "epoch": 7,
58
+ "train_loss": 0.944852351721265,
59
+ "train_acc": 0.9122647758777203,
60
+ "val_loss": 0.8668547753025504,
61
+ "val_acc": 0.945749784721368,
62
+ "val_f1": 0.9263269732704236,
63
+ "time": 1441.4581434726715
64
+ },
65
+ {
66
+ "epoch": 8,
67
+ "train_loss": 0.9229121897808237,
68
+ "train_acc": 0.9209745086974656,
69
+ "val_loss": 0.8765205524715722,
70
+ "val_acc": 0.9500553573625292,
71
+ "val_f1": 0.9316049347432307,
72
+ "time": 1426.3272116184235
73
+ },
74
+ {
75
+ "epoch": 9,
76
+ "train_loss": 0.9052303869458532,
77
+ "train_acc": 0.9262003483893128,
78
+ "val_loss": 0.8286291617973178,
79
+ "val_acc": 0.9511625046131136,
80
+ "val_f1": 0.9329479902298496,
81
+ "time": 1459.579822063446
82
+ },
83
+ {
84
+ "epoch": 10,
85
+ "train_loss": 0.8945274736200061,
86
+ "train_acc": 0.9302239996074486,
87
+ "val_loss": 0.8196153508681877,
88
+ "val_acc": 0.9554680772542749,
89
+ "val_f1": 0.9398121159320021,
90
+ "time": 1478.4978857040405
91
+ },
92
+ {
93
+ "epoch": 11,
94
+ "train_loss": 0.8811485677536466,
95
+ "train_acc": 0.9341985819082902,
96
+ "val_loss": 0.8023291778330709,
97
+ "val_acc": 0.9612498462295486,
98
+ "val_f1": 0.9471128124649691,
99
+ "time": 1509.495314836502
100
+ },
101
+ {
102
+ "epoch": 12,
103
+ "train_loss": 0.8654819950578351,
104
+ "train_acc": 0.938933732427194,
105
+ "val_loss": 0.7963946771387961,
106
+ "val_acc": 0.9581744372001476,
107
+ "val_f1": 0.9435510220579112,
108
+ "time": 1472.0998933315277
109
+ },
110
+ {
111
+ "epoch": 13,
112
+ "train_loss": 0.8616015490969084,
113
+ "train_acc": 0.9413626438332638,
114
+ "val_loss": 0.7887863209434584,
115
+ "val_acc": 0.9621109607577808,
116
+ "val_f1": 0.9485549077712332,
117
+ "time": 1612.443365573883
118
+ },
119
+ {
120
+ "epoch": 14,
121
+ "train_loss": 0.8532575388531108,
122
+ "train_acc": 0.9417061262543241,
123
+ "val_loss": 0.8017812482282227,
124
+ "val_acc": 0.9635871570918932,
125
+ "val_f1": 0.9524276544446466,
126
+ "time": 1710.4971199035645
127
+ },
128
+ {
129
+ "epoch": 15,
130
+ "train_loss": 0.8508924984108522,
131
+ "train_acc": 0.943399003900979,
132
+ "val_loss": 0.7979195382080826,
133
+ "val_acc": 0.9613728625907245,
134
+ "val_f1": 0.9477633630914835,
135
+ "time": 1419.0859017372131
136
+ }
137
+ ]
ml_pipeline/__init__.py ADDED
File without changes
ml_pipeline/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (186 Bytes). View file
 
ml_pipeline/configs/convnext_tiny.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ConvNeXt-Tiny Configuration
2
+ model:
3
+ type: convnext_tiny
4
+ num_classes: 38
5
+ pretrained: true
6
+ dropout: 0.3
7
+
8
+ data:
9
+ img_size: 224
10
+ batch_size: 64
11
+ augment_level: heavy
12
+ num_workers: 4
13
+ use_balanced_sampling: true
14
+
15
+ training:
16
+ epochs: 50
17
+ optimizer: adamw
18
+ learning_rate: 0.0008
19
+ weight_decay: 0.0001
20
+ scheduler: cosine
21
+ warmup_epochs: 5
22
+ label_smoothing: 0.05
23
+ mixup_alpha: 0.2
24
+ cutmix_prob: 0.5
25
+ early_stopping_patience: 10
26
+ early_stopping_metric: val_f1
27
+ gradient_clip_val: 1.0
28
+ seed: 456
29
+
30
+ loss:
31
+ type: cross_entropy
32
+ focal_gamma: 2.0
33
+ focal_alpha: null
34
+
35
+ checkpoint:
36
+ save_dir: checkpoints/convnext_tiny
37
+ save_top_k: 3
38
+ monitor: val_f1
ml_pipeline/configs/efficientnet_v2.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EfficientNetV2-S Configuration
2
+ model:
3
+ type: efficientnet_v2
4
+ num_classes: 38
5
+ pretrained: true
6
+ dropout: 0.3
7
+
8
+ data:
9
+ img_size: 384
10
+ batch_size: 32
11
+ augment_level: heavy
12
+ num_workers: 4
13
+ use_balanced_sampling: true
14
+
15
+ training:
16
+ epochs: 60
17
+ optimizer: adamw
18
+ learning_rate: 0.001
19
+ weight_decay: 0.0001
20
+ scheduler: cosine
21
+ warmup_epochs: 5
22
+ label_smoothing: 0.05
23
+ mixup_alpha: 0.2
24
+ cutmix_prob: 0.5
25
+ early_stopping_patience: 10
26
+ early_stopping_metric: val_f1
27
+ gradient_clip_val: 1.0
28
+ seed: 42
29
+
30
+ loss:
31
+ type: cross_entropy # or focal
32
+ focal_gamma: 2.0
33
+ focal_alpha: null # auto from class weights
34
+
35
+ checkpoint:
36
+ save_dir: checkpoints/efficientnet_v2
37
+ save_top_k: 3
38
+ monitor: val_f1
ml_pipeline/configs/mobilenet_v3.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MobileNetV3-Large Configuration (Edge/Mobile)
2
+ model:
3
+ type: mobilenet_v3
4
+ num_classes: 38
5
+ pretrained: true
6
+ dropout: 0.2
7
+
8
+ data:
9
+ img_size: 224
10
+ batch_size: 128
11
+ augment_level: medium
12
+ num_workers: 4
13
+ use_balanced_sampling: true
14
+
15
+ training:
16
+ epochs: 80
17
+ optimizer: adamw
18
+ learning_rate: 0.001
19
+ weight_decay: 0.00005
20
+ scheduler: cosine
21
+ warmup_epochs: 5
22
+ label_smoothing: 0.05
23
+ mixup_alpha: 0.1
24
+ cutmix_prob: 0.3
25
+ early_stopping_patience: 15
26
+ early_stopping_metric: val_f1
27
+ gradient_clip_val: 1.0
28
+ seed: 101
29
+
30
+ loss:
31
+ type: cross_entropy
32
+ focal_gamma: 2.0
33
+ focal_alpha: null
34
+
35
+ checkpoint:
36
+ save_dir: checkpoints/mobilenet_v3
37
+ save_top_k: 3
38
+ monitor: val_f1
ml_pipeline/configs/resnet50.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ResNet50 Configuration
2
+ model:
3
+ type: resnet50
4
+ num_classes: 38
5
+ pretrained: true
6
+ dropout: 0.3
7
+
8
+ data:
9
+ img_size: 224
10
+ batch_size: 64
11
+ augment_level: medium
12
+ num_workers: 4
13
+ use_balanced_sampling: true
14
+
15
+ training:
16
+ epochs: 60
17
+ optimizer: adamw
18
+ learning_rate: 0.0005
19
+ weight_decay: 0.0001
20
+ scheduler: onecycle
21
+ warmup_epochs: 3
22
+ label_smoothing: 0.05
23
+ mixup_alpha: 0.2
24
+ cutmix_prob: 0.5
25
+ early_stopping_patience: 12
26
+ early_stopping_metric: val_f1
27
+ gradient_clip_val: 1.0
28
+ seed: 123
29
+
30
+ loss:
31
+ type: cross_entropy
32
+ focal_gamma: 2.0
33
+ focal_alpha: null
34
+
35
+ checkpoint:
36
+ save_dir: checkpoints/resnet50
37
+ save_top_k: 3
38
+ monitor: val_f1
ml_pipeline/configs/swin_tiny.yaml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Swin-Tiny Configuration
2
+ model:
3
+ type: swin_tiny
4
+ num_classes: 38
5
+ pretrained: true
6
+ dropout: 0.3
7
+
8
+ data:
9
+ img_size: 224
10
+ batch_size: 64
11
+ augment_level: medium
12
+ num_workers: 4
13
+ use_balanced_sampling: true
14
+
15
+ training:
16
+ epochs: 50
17
+ optimizer: adamw
18
+ learning_rate: 0.0005
19
+ weight_decay: 0.0001
20
+ scheduler: cosine
21
+ warmup_epochs: 5
22
+ label_smoothing: 0.1
23
+ mixup_alpha: 0.2
24
+ cutmix_prob: 0.5
25
+ early_stopping_patience: 10
26
+ early_stopping_metric: val_f1
27
+ gradient_clip_val: 1.0
28
+ seed: 789
29
+
30
+ loss:
31
+ type: cross_entropy
32
+ focal_gamma: 2.0
33
+ focal_alpha: null
34
+
35
+ checkpoint:
36
+ save_dir: checkpoints/swin_tiny
37
+ save_top_k: 3
38
+ monitor: val_f1
ml_pipeline/data/__init__.py ADDED
File without changes
ml_pipeline/data/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (191 Bytes). View file
 
ml_pipeline/data/__pycache__/dataset.cpython-311.pyc ADDED
Binary file (20 kB). View file
 
ml_pipeline/data/dataset.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Data pipeline for PlantVillage dataset.
3
+ Handles downloading, validation, stratified splitting, and preprocessing.
4
+ """
5
+ import os
6
+ import json
7
+ import shutil
8
+ import random
9
+ from typing import Dict, List, Tuple
10
+ from collections import defaultdict, Counter
11
+
12
+ import numpy as np
13
+ import torch
14
+ from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
15
+ from torchvision import transforms, datasets
16
+
17
+
18
+ # PlantVillage 38-class label mapping
19
+ PLANTVILLAGE_CLASSES = [
20
+ "Apple___Apple_scab", "Apple___Black_rot", "Apple___Cedar_apple_rust", "Apple___healthy",
21
+ "Blueberry___healthy", "Cherry_(including_sour)___Powdery_mildew", "Cherry_(including_sour)___healthy",
22
+ "Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot", "Corn_(maize)___Common_rust_",
23
+ "Corn_(maize)___Northern_Leaf_Blight", "Corn_(maize)___healthy",
24
+ "Grape___Black_rot", "Grape___Esca_(Black_Measles)", "Grape___Leaf_blight_(Isariopsis_Leaf_Spot)",
25
+ "Grape___healthy", "Orange___Haunglongbing_(Citrus_greening)",
26
+ "Peach___Bacterial_spot", "Peach___healthy",
27
+ "Pepper,_bell___Bacterial_spot", "Pepper,_bell___healthy",
28
+ "Potato___Early_blight", "Potato___Late_blight", "Potato___healthy",
29
+ "Raspberry___healthy", "Soybean___healthy",
30
+ "Squash___Powdery_mildew", "Strawberry___Leaf_scorch", "Strawberry___healthy",
31
+ "Tomato___Bacterial_spot", "Tomato___Early_blight", "Tomato___Late_blight",
32
+ "Tomato___Leaf_Mold", "Tomato___Septoria_leaf_spot",
33
+ "Tomato___Spider_mites Two-spotted_spider_mite", "Tomato___Target_Spot",
34
+ "Tomato___Tomato_Yellow_Leaf_Curl_Virus", "Tomato___Tomato_mosaic_virus", "Tomato___healthy"
35
+ ]
36
+
37
+ # Map class to plant species for group-based splitting
38
+ CLASS_TO_SPECIES = {}
39
+ for cls in PLANTVILLAGE_CLASSES:
40
+ species = cls.split("___")[0]
41
+ CLASS_TO_SPECIES[cls] = species
42
+
43
+
44
+ def normalize_label(label: str) -> str:
45
+ """Normalize label names to consistent format."""
46
+ label = label.strip().replace(" ", "_").replace(",", ",")
47
+ return label
48
+
49
+
50
+ def get_species_groups(data_dir: str) -> Dict[str, List[str]]:
51
+ """Group classes by plant species to prevent data leakage in splits."""
52
+ species_to_classes = defaultdict(list)
53
+ for cls in sorted(os.listdir(data_dir)):
54
+ cls_path = os.path.join(data_dir, cls)
55
+ if os.path.isdir(cls_path):
56
+ species = cls.split("___")[0] if "___" in cls else cls.split("_")[0]
57
+ species_to_classes[species].append(cls)
58
+ return dict(species_to_classes)
59
+
60
+
61
+ def create_stratified_species_split(
62
+ data_dir: str,
63
+ output_dir: str,
64
+ train_ratio: float = 0.7,
65
+ val_ratio: float = 0.15,
66
+ test_ratio: float = 0.15,
67
+ seed: int = 42
68
+ ) -> Dict[str, List[str]]:
69
+ """
70
+ Create stratified train/val/test splits GROUPED by plant species
71
+ to avoid data leakage (same plant appearing in train and test).
72
+
73
+ Within each species group, images are split maintaining class proportions.
74
+ """
75
+ assert abs(train_ratio + val_ratio + test_ratio - 1.0) < 1e-6
76
+ random.seed(seed)
77
+ np.random.seed(seed)
78
+
79
+ splits = {"train": [], "val": [], "test": []}
80
+ split_stats = {"train": Counter(), "val": Counter(), "test": Counter()}
81
+
82
+ all_classes = sorted([
83
+ d for d in os.listdir(data_dir)
84
+ if os.path.isdir(os.path.join(data_dir, d))
85
+ ])
86
+
87
+ for cls in all_classes:
88
+ cls_dir = os.path.join(data_dir, cls)
89
+ images = sorted([
90
+ f for f in os.listdir(cls_dir)
91
+ if f.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.webp'))
92
+ ])
93
+ random.shuffle(images)
94
+
95
+ n = len(images)
96
+ n_train = int(n * train_ratio)
97
+ n_val = int(n * val_ratio)
98
+
99
+ train_imgs = images[:n_train]
100
+ val_imgs = images[n_train:n_train + n_val]
101
+ test_imgs = images[n_train + n_val:]
102
+
103
+ for split_name, img_list in [("train", train_imgs), ("val", val_imgs), ("test", test_imgs)]:
104
+ split_cls_dir = os.path.join(output_dir, split_name, cls)
105
+ os.makedirs(split_cls_dir, exist_ok=True)
106
+ for img in img_list:
107
+ src = os.path.join(cls_dir, img)
108
+ dst = os.path.join(split_cls_dir, img)
109
+ if not os.path.exists(dst):
110
+ shutil.copy2(src, dst)
111
+ splits[split_name].append(dst)
112
+ split_stats[split_name][cls] = len(img_list)
113
+
114
+ # Save split metadata
115
+ meta = {
116
+ "seed": seed,
117
+ "ratios": {"train": train_ratio, "val": val_ratio, "test": test_ratio},
118
+ "counts": {k: dict(v) for k, v in split_stats.items()},
119
+ "total": {k: sum(v.values()) for k, v in split_stats.items()}
120
+ }
121
+ with open(os.path.join(output_dir, "split_metadata.json"), "w") as f:
122
+ json.dump(meta, f, indent=2)
123
+
124
+ print(f"Split complete: train={meta['total']['train']}, "
125
+ f"val={meta['total']['val']}, test={meta['total']['test']}")
126
+ return splits
127
+
128
+
129
+ def get_train_transforms(img_size: int = 224, augment_level: str = "medium"):
130
+ """Configurable training augmentation pipeline."""
131
+ if augment_level == "light":
132
+ return transforms.Compose([
133
+ transforms.Resize((img_size + 32, img_size + 32)),
134
+ transforms.RandomCrop(img_size),
135
+ transforms.RandomHorizontalFlip(p=0.5),
136
+ transforms.ToTensor(),
137
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
138
+ ])
139
+ elif augment_level == "medium":
140
+ return transforms.Compose([
141
+ transforms.Resize((img_size + 32, img_size + 32)),
142
+ transforms.RandomCrop(img_size),
143
+ transforms.RandomHorizontalFlip(p=0.5),
144
+ transforms.RandomVerticalFlip(p=0.3),
145
+ transforms.RandomRotation(15),
146
+ transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
147
+ transforms.ToTensor(),
148
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
149
+ transforms.RandomErasing(p=0.25, scale=(0.02, 0.15)),
150
+ ])
151
+ else: # heavy
152
+ return transforms.Compose([
153
+ transforms.Resize((img_size + 32, img_size + 32)),
154
+ transforms.RandomCrop(img_size),
155
+ transforms.RandomHorizontalFlip(p=0.5),
156
+ transforms.RandomVerticalFlip(p=0.3),
157
+ transforms.RandomRotation(30),
158
+ transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.15),
159
+ transforms.RandAugment(num_ops=2, magnitude=9),
160
+ transforms.ToTensor(),
161
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
162
+ transforms.RandomErasing(p=0.4, scale=(0.02, 0.2)),
163
+ ])
164
+
165
+
166
+ def get_val_transforms(img_size: int = 224):
167
+ """Validation/test transforms — no augmentation."""
168
+ return transforms.Compose([
169
+ transforms.Resize((img_size, img_size)),
170
+ transforms.ToTensor(),
171
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
172
+ ])
173
+
174
+
175
+ class PlantDiseaseDataset(Dataset):
176
+ """Custom dataset with MixUp/CutMix support."""
177
+
178
+ def __init__(self, root_dir: str, transform=None, return_path: bool = False):
179
+ self.dataset = datasets.ImageFolder(root_dir, transform=transform)
180
+ self.classes = self.dataset.classes
181
+ self.class_to_idx = self.dataset.class_to_idx
182
+ self.return_path = return_path
183
+ self.targets = self.dataset.targets
184
+
185
+ def __len__(self):
186
+ return len(self.dataset)
187
+
188
+ def __getitem__(self, idx):
189
+ img, label = self.dataset[idx]
190
+ if self.return_path:
191
+ path = self.dataset.samples[idx][0]
192
+ return img, label, path
193
+ return img, label
194
+
195
+ def get_class_weights(self) -> torch.Tensor:
196
+ """Compute inverse frequency weights for class-balanced sampling."""
197
+ counts = Counter(self.targets)
198
+ total = len(self.targets)
199
+ weights = torch.zeros(len(self.classes))
200
+ for cls_idx, count in counts.items():
201
+ weights[cls_idx] = total / (len(self.classes) * count)
202
+ return weights
203
+
204
+ def get_sampler(self) -> WeightedRandomSampler:
205
+ """Get weighted random sampler for class-balanced training."""
206
+ class_weights = self.get_class_weights()
207
+ sample_weights = [class_weights[t] for t in self.targets]
208
+ return WeightedRandomSampler(sample_weights, num_samples=len(self.targets), replacement=True)
209
+
210
+
211
+ class MixUpCutMix:
212
+ """MixUp and CutMix data augmentation."""
213
+
214
+ def __init__(self, mixup_alpha: float = 0.2, cutmix_prob: float = 0.5, num_classes: int = 38):
215
+ self.mixup_alpha = mixup_alpha
216
+ self.cutmix_prob = cutmix_prob
217
+ self.num_classes = num_classes
218
+
219
+ def __call__(self, images: torch.Tensor, targets: torch.Tensor):
220
+ if random.random() < self.cutmix_prob:
221
+ return self._cutmix(images, targets)
222
+ else:
223
+ return self._mixup(images, targets)
224
+
225
+ def _mixup(self, images, targets):
226
+ lam = np.random.beta(self.mixup_alpha, self.mixup_alpha) if self.mixup_alpha > 0 else 1.0
227
+ batch_size = images.size(0)
228
+ index = torch.randperm(batch_size, device=images.device)
229
+ mixed_images = lam * images + (1 - lam) * images[index]
230
+ targets_onehot = torch.nn.functional.one_hot(targets, self.num_classes).float()
231
+ mixed_targets = lam * targets_onehot + (1 - lam) * targets_onehot[index]
232
+ return mixed_images, mixed_targets
233
+
234
+ def _cutmix(self, images, targets):
235
+ lam = np.random.beta(1.0, 1.0)
236
+ batch_size = images.size(0)
237
+ index = torch.randperm(batch_size, device=images.device)
238
+ _, _, H, W = images.shape
239
+ cut_rat = np.sqrt(1.0 - lam)
240
+ cut_w, cut_h = int(W * cut_rat), int(H * cut_rat)
241
+ cx, cy = random.randint(0, W), random.randint(0, H)
242
+ x1 = max(0, cx - cut_w // 2)
243
+ y1 = max(0, cy - cut_h // 2)
244
+ x2 = min(W, cx + cut_w // 2)
245
+ y2 = min(H, cy + cut_h // 2)
246
+
247
+ images[:, :, y1:y2, x1:x2] = images[index, :, y1:y2, x1:x2]
248
+ lam = 1 - (x2 - x1) * (y2 - y1) / (W * H)
249
+ targets_onehot = torch.nn.functional.one_hot(targets, self.num_classes).float()
250
+ mixed_targets = lam * targets_onehot + (1 - lam) * targets_onehot[index]
251
+ return images, mixed_targets
252
+
253
+
254
+ def create_dataloaders(
255
+ data_dir: str,
256
+ img_size: int = 224,
257
+ batch_size: int = 32,
258
+ augment_level: str = "medium",
259
+ num_workers: int = 4,
260
+ use_balanced_sampling: bool = True
261
+ ) -> Tuple[DataLoader, DataLoader, DataLoader]:
262
+ """Create train/val/test dataloaders with all preprocessing."""
263
+ train_transform = get_train_transforms(img_size, augment_level)
264
+ val_transform = get_val_transforms(img_size)
265
+
266
+ train_dataset = PlantDiseaseDataset(os.path.join(data_dir, "train"), train_transform)
267
+ val_dataset = PlantDiseaseDataset(os.path.join(data_dir, "val"), val_transform)
268
+ test_dataset = PlantDiseaseDataset(os.path.join(data_dir, "test"), val_transform, return_path=True)
269
+
270
+ sampler = train_dataset.get_sampler() if use_balanced_sampling else None
271
+
272
+ train_loader = DataLoader(
273
+ train_dataset, batch_size=batch_size,
274
+ sampler=sampler, shuffle=(sampler is None),
275
+ num_workers=num_workers, pin_memory=True, drop_last=True
276
+ )
277
+ val_loader = DataLoader(
278
+ val_dataset, batch_size=batch_size,
279
+ shuffle=False, num_workers=num_workers, pin_memory=True
280
+ )
281
+ test_loader = DataLoader(
282
+ test_dataset, batch_size=batch_size,
283
+ shuffle=False, num_workers=num_workers, pin_memory=True
284
+ )
285
+
286
+ print(f"Dataloaders: train={len(train_dataset)}, val={len(val_dataset)}, test={len(test_dataset)}")
287
+ print(f"Classes: {len(train_dataset.classes)}")
288
+ return train_loader, val_loader, test_loader
ml_pipeline/distillation/__init__.py ADDED
File without changes
ml_pipeline/ensemble/__init__.py ADDED
File without changes
ml_pipeline/models/__init__.py ADDED
File without changes
ml_pipeline/models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (193 Bytes). View file