Muhammad commited on
Update src/predict.py
Browse files12341 unmodified line6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616 unmodified lines6869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255import jsonfrom pathlib import Pathfrom typing import Any1 unmodified linefrom PIL import Imageimport tensorflow as tffrom .config import CLASS_MAP_PATH, IMAGE_SIZE, MODEL_PATH, OOD_THRESHOLD, TOP_K_DEFAULT_model = None_idx_to_class: dict[str, str] | None = Nonedef _prettify(label: str) -> str:return label.replace("___", " - ").replace("_", " ")def _split_label(label: str) -> tuple[str, str]:parts = label.split("___", 1)if len(parts) == 2:return parts[0], parts[1]return label, "unknown"def _get_detailed_info(plant: str, disease: str) -> dict[str, Any]:disease_l = disease.lower()plant_l = plant.lower()# Default values (English + Urdu)info = {"status": "Diseased","status_ur": "بیمار","disease_name": _prettify(disease),"description": "A condition affecting the health and growth of the plant.","description_ur": "ایک ایسی حالت جو پودے کی صحت اور نشوونما کو متاثر کر رہی ہے۔","causes": ["Environmental stress", "Pathogen exposure"],"causes_ur": ["ماحولیاتی دباؤ", "جراثیم کا حملہ"],"cure": "Remove affected parts and monitor closely.","cure_ur": "متاثرہ حصوں کو ہٹا دیں اور قریب سے نگرانی کریں۔","prevention": "Maintain proper watering and sunlight.","prevention_ur": "پانی اور سورج کی روشنی کا مناسب انتظام برقرار رکھیں۔","severity": "Moderate","organic_remedies": "Neem oil spray","organic_remedies_ur": "نیم کے تیل کا سپرے","fertilizer": "Balanced NPK fertilizer","fertilizer_ur": "متوازن این پی کے کھاد","weather_advice": "Avoid extreme humidity or dry spells.","weather_advice_ur": "بہت زیادہ نمی یا خشک سالی سے بچیں"}if "healthy" in disease_l:info.update({"status": "Healthy","status_ur": "صحت مند","disease_name": "None","description": f"The {plant} plant appears to be in good health with no visible signs of disease.","description_ur": f"آپ کا {plant} کا پودا بالکل صحت مند معلوم ہوتا ہے اور بیماری کی کوئی علامت نہیں ہے۔","causes": ["Proper care and environment"],"causes_ur": ["مناسب دیکھ بھال اور ماحول"],"cure": "No treatment needed.",6 unmodified lines"fertilizer": "Regular compost","fertilizer_ur": "عام کھاد یا کمپوسٹ","weather_advice": "Ideal conditions for growth.","weather_advice_ur": "نشوونما کے لیے بہترین حالات۔"})return info# Specific Disease Datadisease_data = {"early_blight": {"description_ur": "ارلی بلائٹ ایک عام فنگل بیماری ہے جس کی وجہ سے پتوں پر گول بھورے دھبے بن جاتے ہیں، جو آخر کار پتے پیلے کر کے گرا دیتی ہے۔","causes_ur": ["زیادہ نمی", "ہوا کی کمی", "مٹی میں فنگس"],"cure_ur": "متاثرہ پتوں کو فوری طور پر ہٹا دیں۔ کاپر پر مبنی فنگس کش سپرے استعمال کریں۔","prevention_ur": "ہر سال فصلیں بدلیں۔ پودوں کی بنیاد میں پانی دیں، پتوں پر نہیں۔ ہوا کے لیے پودوں کے درمیان جگہ رکھیں۔","organic_remedies_ur": "بیکنگ سوڈا کا محلول (1 چائے کا چمچ فی لیٹر) یا نیم کا تیل۔","fertilizer_ur": "کیلشیم سے بھرپور کھاد تاکہ پودے کی طاقت بڑھے۔","weather_advice_ur": "گرم اور مرطوب موسم اس بیماری کو تیزی سے پھیلاتا ہے۔"},"late_blight": {"description_ur": "لیٹ بلائٹ ایک خطرناک بیماری ہے جو پودوں کو تیزی سے مار سکتی ہے۔ یہ پتوں پر سیاہ، پانی بھرے دھبوں کی طرح نظر آتی ہے۔","causes_ur": ["ٹھنڈا اور گیلا موسم", "ہوا سے پھیلنے والے ذرات"],"cure_ur": "بیماری کو پھیلنے سے روکنے کے لیے متاثرہ پودوں کو فوری طور پر تلف کر دیں۔","prevention_ur": "بیماری سے بچاؤ والی اقسام استعمال کریں۔ اوپر سے پانی دینے سے گریز کریں۔","organic_remedies_ur": "کاپر صابن والا فنگس کش محلول۔","fertilizer_ur": "قوت مدافعت بڑھانے کے لیے پوٹاشیم سپلیمنٹ۔","weather_advice_ur": "بارش اور دھند والے حالات بہت خطرناک ہیں۔"},"powdery_mildew": {"description_ur": "ایک فنگل بیماری جو پتوں، تنوں اور پھلوں کی سطح پر سفید آٹے یا پاؤڈر کی طرح نظر آتی ہے۔","causes_ur": ["زیادہ نمی", "سایہ دار حالات", "ہوا کی گردش کی کمی"],"cure_ur": "پوٹاشیم بائیکاربونیٹ یا دودھ اور پانی کا سپرے (40/60 تناسب) لگائیں۔","prevention_ur": "مکمل دھوپ میں پودا لگائیں۔ پودوں کے ارد گرد نمی کم کریں۔","organic_remedies_ur": "لہسن کے پانی کا سپرے یا سرکہ اور پانی کا محلول۔","fertilizer_ur": "زیادہ نائٹروجن سے بچیں؛ فاسفورس سے بھرپور کھاد استعمال کریں۔","weather_advice_ur": "خشک دن اور مرطوب راتیں اس بیماری کے لیے سازگار ہیں۔"},"rust": {"description_ur": "رسٹ کی شناخت پتوں کے نیچے نارنجی، پیلے یا بھورے دھبوں سے ہوتی ہے۔","causes_ur": ["پتوں کا زیادہ دیر تک گیلا رہنا", "متاثرہ باقیات"],"cure_ur": "متاثرہ حصوں کو کاٹ کر جلا دیں۔ گندھک (سلفر) پر مبنی سپرے استعمال کریں۔","prevention_ur": "پتوں کو خشک رکھیں۔ خزاں میں پودوں کا ملبہ ہٹا دیں۔","organic_remedies_ur": "سلفر سپرے یا کمپوسٹ چائے۔","fertilizer_ur": "متوازن نامیاتی کھاد (آرگینک کمپوسٹ)۔","weather_advice_ur": "مرطوب اور رکی ہوئی ہوا بیماری کو پھیلنے کا موقع دیتی ہے۔"}}# Match the disease to the closest keyfor key, val in disease_data.items():if key in disease_l:info.update(val)breakreturn infodef load_model_and_classes() -> tuple[Any, dict[str, str]]:global _model, _idx_to_class# Dynamic path resolution# This looks for the folder GardCom starting from the /app roothf_model_path = Path("/app/GardCom/saved_models_run2/best_model.keras")hf_class_path = Path("/app/GardCom/saved_models_run2/class_map.json")# Fallback to config paths if HF paths don't existfinal_model_path = hf_model_path if hf_model_path.exists() else MODEL_PATHfinal_class_path = hf_class_path if hf_class_path.exists() else CLASS_MAP_PATHif not final_model_path.exists():raise Exception(f"Model file missing at {final_model_path}")if not final_class_path.exists():raise Exception(f"Class map file missing at {final_class_path}")if _model is None:_model = tf.keras.models.load_model(final_model_path)if _idx_to_class is None:with open(final_class_path, "r", encoding="utf-8") as f:_idx_to_class = json.load(f)return _model, _idx_to_classdef preprocess_image(file_path: str) -> np.ndarray:img = Image.open(file_path).convert("RGB").resize(IMAGE_SIZE, Image.LANCZOS)arr = np.array(img, dtype=np.float32)return np.expand_dims(arr, axis=0)def predict(file_path: str, top_k: int = TOP_K_DEFAULT, plant_hint: str | None = None) -> dict[str, Any]:model, idx_to_class = load_model_and_classes()probs = model.predict(preprocess_image(file_path), verbose=0)[0]top_idx = -1confidence = 0.0mode = "global"# Step 1: Check for plant hint prioritizationhint_status = "none"if plant_hint and len(plant_hint.strip()) > 1:hint = plant_hint.strip().lower()matching_indices = []for i, label in idx_to_class.items():plant_part, _ = _split_label(label)if hint in plant_part.lower() or plant_part.lower() in hint:matching_indices.append(int(i))if matching_indices:best_match_idx = matching_indices[0]max_match_prob = probs[best_match_idx]for idx in matching_indices:if probs[idx] > max_match_prob:max_match_prob = probs[idx]best_match_idx = idxif max_match_prob > 0.30:top_idx = best_match_idxconfidence = float(max_match_prob)mode = "hinted"hint_status = "correct"if top_idx == -1:top_idx = int(np.argmax(probs))confidence = float(probs[top_idx])mode = "global"if plant_hint and len(plant_hint.strip()) > 1:global_plant, _ = _split_label(idx_to_class[str(top_idx)])hint_low = plant_hint.strip().lower()if hint_low in global_plant.lower() or global_plant.lower() in hint_low:hint_status = "correct"else:hint_status = "wrong"if confidence < OOD_THRESHOLD:return {"status": "rejected","message": "Image rejected as out-of-domain (non-plant or unsupported).","plant_name": "unknown","disease_name": "unknown","confidence": round(confidence * 100.0, 2),"top_k": [],"user_hint": plant_hint,"hint_status": "none","error": None,}top_pairs = sorted(enumerate(probs), key=lambda x: x[1], reverse=True)[: max(1, top_k)]label = idx_to_class[str(top_idx)]plant, disease = _split_label(label)# Get the rich data requested by userdetails = _get_detailed_info(plant, disease)return {"status": "ok","message": f"{details['disease_name']} detected on {plant}." if details['status'] != "Healthy" else f"Healthy {plant} leaf detected.","plant_name": plant,"disease_name": details['disease_name'],"disease_status": details['status'],"disease_status_ur": details['status_ur'],"confidence": round(confidence * 100.0, 1),"description": details['description'],"description_ur": details['description_ur'],"causes": details['causes'],"causes_ur": details['causes_ur'],"cure": details['cure'],"cure_ur": details['cure_ur'],"prevention": details['prevention'],"prevention_ur": details['prevention_ur'],"severity": details['severity'],"organic_remedies": details['organic_remedies'],"organic_remedies_ur": details['organic_remedies_ur'],"fertilizer": details['fertilizer'],"fertilizer_ur": details['fertilizer_ur'],"weather_advice": details['weather_advice'],"weather_advice_ur": details['weather_advice_ur'],"user_hint": plant_hint,"hint_status": hint_status,"top_k": [{"class": idx_to_class[str(i)],"confidence": round(float(p) * 100.0, 1),}for i, p in top_pairs],"error": None,}123451 unmodified line7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651666 unmodified lines173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345import jsonimport threadingfrom pathlib import Pathfrom typing import Any1 unmodified linefrom PIL import Imageimport tensorflow as tffrom .config import (CLASS_MAP_PATH,DISEASES_DB_PATH,IMAGE_SIZE,LOW_CONFIDENCE_THRESHOLD,MODEL_PATH,OOD_THRESHOLD,TOP_K_DEFAULT,TOP_K_MAX,)# ── Module-level singletons ───────────────────────────────────────────────────_model: Any = None_idx_to_class: dict[str, str] | None = None_diseases_db: dict[str, Any] | None = None_load_lock = threading.Lock() # FIX: prevents double-load under concurrent requests# ── Label helpers ─────────────────────────────────────────────────────────────def _prettify(label: str) -> str:"""Convert raw class-map label to human-readable form."""return label.replace("___", " - ").replace("_", " ")def _split_label(label: str) -> tuple[str, str]:"""Split 'Plant___Disease' into ('Plant', 'Disease')."""parts = label.split("___", 1)if len(parts) == 2:return parts[0], parts[1]return label, "unknown"# ── Data loading ──────────────────────────────────────────────────────────────def _load_diseases_db() -> dict[str, Any]:"""Load diseases.json into memory.diseases.json uses the same keys as class_map.json values(e.g. "Tomato___Early_blight") so lookups are O(1).Returns an empty dict if the file is missing so the system degradesgracefully rather than crashing."""if not Path(DISEASES_DB_PATH).exists():return {}with open(DISEASES_DB_PATH, "r", encoding="utf-8") as f:return json.load(f)def load_model_and_classes() -> tuple[Any, dict[str, str], dict[str, Any]]:"""Load (or return cached) model, class map, and diseases DB.Thread-safe: uses a module-level Lock so only one thread loadseven under concurrent first requests."""global _model, _idx_to_class, _diseases_db# Fast path — already loadedif _model is not None and _idx_to_class is not None and _diseases_db is not None:return _model, _idx_to_class, _diseases_dbwith _load_lock:# Re-check after acquiring lock (another thread may have loaded first)if _model is None:if not Path(MODEL_PATH).exists():raise FileNotFoundError(f"Model not found at {MODEL_PATH}")_model = tf.keras.models.load_model(MODEL_PATH)if _idx_to_class is None:if not Path(CLASS_MAP_PATH).exists():raise FileNotFoundError(f"class_map not found at {CLASS_MAP_PATH}")with open(CLASS_MAP_PATH, "r", encoding="utf-8") as f:_idx_to_class = json.load(f)if _diseases_db is None:_diseases_db = _load_diseases_db()return _model, _idx_to_class, _diseases_db# ── Image preprocessing ───────────────────────────────────────────────────────def preprocess_image(file_path: str) -> np.ndarray:"""Load, resize, and batch an image for inference.Normalization: raw 0-255 float32 — EfficientNetB0 contains its ownbuilt-in Rescaling + normalization layers (preprocess_input is bakedinto the SavedModel). Do NOT divide by 255 here.This matches the training generator which also sends raw 0-255 pixels(ImageDataGenerator with no rescale= parameter)."""with Image.open(file_path) as img:arr = np.array(img.convert("RGB").resize(IMAGE_SIZE, Image.LANCZOS),dtype=np.float32,)return np.expand_dims(arr, axis=0) # shape: (1, 224, 224, 3)# ── Disease info lookup ───────────────────────────────────────────────────────_GENERIC_INFO: dict[str, Any] = {"status": "Diseased","status_ur": "بیمار","disease_name": "Unknown Disease","description": "A condition affecting the health and growth of the plant.","description_ur": "ایک ایسی حالت جو پودے کی صحت اور نشوونما کو متاثر کر رہی ہے۔","causes": ["Environmental stress", "Pathogen exposure"],"causes_ur": ["ماحولیاتی دباؤ", "جراثیم کا حملہ"],"cure": "Remove affected parts and consult an agronomist.","cure_ur": "متاثرہ حصوں کو ہٹائیں اور زرعی ماہر سے مشورہ لیں۔","prevention": "Maintain proper watering, sunlight, and crop rotation.","prevention_ur": "پانی، سورج اور فصلوں کی تبدیلی کا خیال رکھیں۔","severity": "Moderate","organic_remedies": "Neem oil spray","organic_remedies_ur": "نیم کے تیل کا سپرے","fertilizer": "Balanced NPK fertilizer","fertilizer_ur": "متوازن این پی کے کھاد","weather_advice": "Monitor closely during humid or wet periods.","weather_advice_ur": "نمی یا بارش کے موسم میں خاص نگرانی کریں۔",}def _get_disease_info(plant: str, disease: str, raw_label: str, diseases_db: dict[str, Any]) -> dict[str, Any]:"""Look up disease information.Lookup order:1. Exact match on raw class-map label (e.g. "Tomato___Early_blight")2. Generic healthy info if 'healthy' in disease name3. Generic fallbackThe original code used fuzzy substring matching over a tiny 4-entrydict, which left 51 of 55 classes returning placeholder text.Now diseases.json (58 entries) is queried by exact key."""# Exact key lookup — O(1), covers all 55 trained classesif raw_label in diseases_db:return dict(diseases_db[raw_label])# Healthy fallback if not in DB (should not happen with complete diseases.json)if "healthy" in disease.lower():return {**_GENERIC_INFO,"status": "Healthy","status_ur": "صحت مند","disease_name": "None","description": f"The {_prettify(plant)} plant appears to be in good health.","description_ur": f"آپ کا {_prettify(plant)} کا پودا بالکل صحت مند معلوم ہوتا ہے۔","causes": ["Proper care and environment"],"causes_ur": ["مناسب دیکھ بھال اور ماحول"],"cure": "No treatment needed.",6 unmodified lines"fertilizer": "Regular compost","fertilizer_ur": "عام کھاد یا کمپوسٹ","weather_advice": "Ideal conditions for growth.","weather_advice_ur": "نشوونما کے لیے بہترین حالات۔",}# Generic fallback — still better than empty stringinfo = dict(_GENERIC_INFO)info["disease_name"] = _prettify(disease)return info# ── Main prediction function ──────────────────────────────────────────────────def predict(file_path: str,top_k: int = TOP_K_DEFAULT,plant_hint: str | None = None,) -> dict[str, Any]:"""Run inference and return a structured result dict.Args:file_path: Path to the uploaded image file (will be read, not deleted).top_k: How many alternative predictions to include (1–TOP_K_MAX).plant_hint: Optional plant name provided by the user (e.g. "Tomato").Returns a dict with status "ok", "rejected", or "error"."""# Clamp top_k to a safe rangetop_k = max(1, min(top_k, TOP_K_MAX))model, idx_to_class, diseases_db = load_model_and_classes()probs: np.ndarray = model.predict(preprocess_image(file_path), verbose=0)[0]# probs.shape == (num_classes,)# ── Step 1: Resolve predicted index ──────────────────────────────────────top_idx = -1confidence = 0.0hint_status = "none"cleaned_hint = plant_hint.strip().lower() if plant_hint and plant_hint.strip() else ""if cleaned_hint:# Gather all class indices that match the hint (plant name substring)matching = [int(i)for i, label in idx_to_class.items()if cleaned_hint in _split_label(label)[0].lower()or _split_label(label)[0].lower() in cleaned_hint]if matching:# Best-confidence class among those matching the hintbest_idx = max(matching, key=lambda i: probs[i])best_prob = float(probs[best_idx])# Accept the hinted result at a lower threshold (user has domain knowledge)# but still require at least 30% — below that it's likely wrong classif best_prob >= 0.30:top_idx = best_idxconfidence = best_probhint_status = "correct"# Fall back to global argmax if no valid hint matchif top_idx == -1:top_idx = int(np.argmax(probs))confidence = float(probs[top_idx])if cleaned_hint:# Evaluate whether global prediction matches the hintglobal_plant, _ = _split_label(idx_to_class[str(top_idx)])if (cleaned_hint in global_plant.lower()or global_plant.lower() in cleaned_hint):hint_status = "correct"else:hint_status = "wrong"# ── Step 2: OOD rejection ─────────────────────────────────────────────────if confidence < OOD_THRESHOLD:return {"status": "rejected","message": "Image not recognised as a supported plant leaf. ""Please upload a clear close-up photo of a leaf.","plant_name": "unknown","disease_name": "unknown","confidence": round(confidence * 100.0, 2),"top_k": [],"user_hint": plant_hint,"hint_status": hint_status,"low_confidence": False,"error": None,}# ── Step 3: Lookup disease information ────────────────────────────────────raw_label = idx_to_class[str(top_idx)]plant, disease = _split_label(raw_label)info = _get_disease_info(plant, disease, raw_label, diseases_db)# ── Step 4: Build top-k list ──────────────────────────────────────────────# Ensure the chosen class always appears first in top_k, regardless of# whether it was selected via hint or global argmax.# Get top-k indices by probability (excluding the chosen one)other_indices = [(i, float(p))for i, p in enumerate(probs)if i != top_idx]other_top = sorted(other_indices, key=lambda x: x[1], reverse=True)[: top_k - 1]top_k_list = [{"class": raw_label,"confidence": round(confidence * 100.0, 1),}] + [{"class": idx_to_class[str(i)],"confidence": round(p * 100.0, 1),}for i, p in other_top]# ── Step 5: Build response ────────────────────────────────────────────────is_healthy = info.get("status", "").lower() == "healthy"return {"status": "ok","message": (f"Healthy {_prettify(plant)} leaf detected."if is_healthyelse f"{info['disease_name']} detected on {_prettify(plant)}."),# Core classification"plant_name": _prettify(plant),"disease_name": info.get("disease_name", _prettify(disease)),"disease_status": info.get("status", "Diseased"),"disease_status_ur": info.get("status_ur", "بیمار"),"confidence": round(confidence * 100.0, 1),# Low-confidence flag — UI should show a warning badge below this threshold"low_confidence": confidence < LOW_CONFIDENCE_THRESHOLD,# Disease details (English)"description": info.get("description", ""),"causes": info.get("causes", []),"cure": info.get("cure", ""),"prevention": info.get("prevention", ""),"severity": info.get("severity", "Moderate"),"organic_remedies": info.get("organic_remedies", ""),"fertilizer": info.get("fertilizer", ""),"weather_advice": info.get("weather_advice", ""),# Disease details (Urdu)"description_ur": info.get("description_ur", ""),"causes_ur": info.get("causes_ur", []),"cure_ur": info.get("cure_ur", ""),"prevention_ur": info.get("prevention_ur", ""),"organic_remedies_ur": info.get("organic_remedies_ur", ""),"fertilizer_ur": info.get("fertilizer_ur", ""),"weather_advice_ur": info.get("weather_advice_ur", ""),# Hint metadata"user_hint": plant_hint,"hint_status": hint_status,# Alternatives"top_k": top_k_list,"error": None,}
src/predict.py+275-185