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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ===================== IMPORTS =====================
|
| 2 |
+
import streamlit as st
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import difflib
|
| 6 |
+
import pickle
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from tensorflow.keras.models import load_model
|
| 11 |
+
from tensorflow.keras.preprocessing.image import img_to_array, load_img
|
| 12 |
+
from transformers import CLIPProcessor, CLIPModel
|
| 13 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
| 14 |
+
from langdetect import detect
|
| 15 |
+
|
| 16 |
+
# ===================== PATHS =====================
|
| 17 |
+
model_path = os.path.join(Main_py, "best_cnn_model_finetuned.keras")
|
| 18 |
+
label_path = os.path.join(Main_py, "label_encoder.pkl")
|
| 19 |
+
json_path = os.path.join(Main_py, "banana_disease_knowledge_base_updated_shuffled.json")
|
| 20 |
+
|
| 21 |
+
# ===================== LOAD MODELS & DATA =====================
|
| 22 |
+
@st.cache_resource
|
| 23 |
+
def load_cnn_clip_kb():
|
| 24 |
+
model = load_model(model_path)
|
| 25 |
+
with open(label_path, "rb") as f:
|
| 26 |
+
le = pickle.load(f)
|
| 27 |
+
with open(json_path, "r", encoding="utf-8") as f:
|
| 28 |
+
kb_data = json.load(f)
|
| 29 |
+
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
|
| 30 |
+
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
| 31 |
+
return model, le, kb_data, clip_model, clip_processor
|
| 32 |
+
|
| 33 |
+
@st.cache_resource
|
| 34 |
+
def load_nlp_models():
|
| 35 |
+
embedder = SentenceTransformer("sentence-transformers/paraphrase-xlm-r-multilingual-v1")
|
| 36 |
+
cross_encoder = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1")
|
| 37 |
+
return embedder, cross_encoder
|
| 38 |
+
|
| 39 |
+
model, le, kb_data, clip_model, clip_processor = load_cnn_clip_kb()
|
| 40 |
+
embedder, cross_encoder = load_nlp_models()
|
| 41 |
+
|
| 42 |
+
# ===================== CLIP FILTER =====================
|
| 43 |
+
def verify_image_with_clip(image_path):
|
| 44 |
+
prompts = ["a photo of a banana leaf", "a photo of something that is not a banana leaf"]
|
| 45 |
+
try:
|
| 46 |
+
image = Image.open(image_path).convert("RGB")
|
| 47 |
+
except Exception as e:
|
| 48 |
+
return ('REJECTED', f'Invalid image file: {e}', 0.0)
|
| 49 |
+
|
| 50 |
+
inputs = clip_processor(text=prompts, images=image, return_tensors="pt", padding=True)
|
| 51 |
+
with torch.no_grad():
|
| 52 |
+
outputs = clip_model(**inputs)
|
| 53 |
+
probs = outputs.logits_per_image.softmax(dim=1).cpu().numpy()[0]
|
| 54 |
+
|
| 55 |
+
banana_score, not_banana_score = probs[0], probs[1]
|
| 56 |
+
rejection_factor = 3.0
|
| 57 |
+
|
| 58 |
+
if banana_score >= not_banana_score * rejection_factor:
|
| 59 |
+
return ('ACCEPTED', 'banana leaf', banana_score)
|
| 60 |
+
else:
|
| 61 |
+
return ('REJECTED', 'Not a banana leaf', not_banana_score)
|
| 62 |
+
|
| 63 |
+
# ===================== CNN PREDICTION =====================
|
| 64 |
+
def predict_disease(image_path, target_size=(224, 224)):
|
| 65 |
+
image = load_img(image_path, target_size=target_size)
|
| 66 |
+
img_array = img_to_array(image) / 255.0
|
| 67 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 68 |
+
preds = model.predict(img_array)[0]
|
| 69 |
+
idx = np.argmax(preds)
|
| 70 |
+
label = le.inverse_transform([idx])[0]
|
| 71 |
+
confidence = preds[idx]
|
| 72 |
+
return label, confidence, image
|
| 73 |
+
|
| 74 |
+
# ===================== FUZZY MARATHI OUTPUT =====================
|
| 75 |
+
def match_disease_name_fuzzy(predicted_name):
|
| 76 |
+
disease_names = [entry["Disease"].strip().lower() for entry in kb_data]
|
| 77 |
+
matches = difflib.get_close_matches(predicted_name.strip().lower(), disease_names, n=1, cutoff=0.5)
|
| 78 |
+
if matches:
|
| 79 |
+
for entry in kb_data:
|
| 80 |
+
if entry["Disease"].strip().lower() == matches[0]:
|
| 81 |
+
return entry
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
def get_marathi_recommendation_fuzzy(predicted_disease, confidence=None):
|
| 85 |
+
entry = match_disease_name_fuzzy(predicted_disease)
|
| 86 |
+
if entry:
|
| 87 |
+
return {
|
| 88 |
+
"पिक": entry.get("Crop", "केळी"),
|
| 89 |
+
"रोग": entry.get("Local_Name", {}).get("mr", predicted_disease),
|
| 90 |
+
"लक्षणे": entry.get("Symptoms_MR", ""),
|
| 91 |
+
"कारण": entry.get("Cause_MR", ""),
|
| 92 |
+
"किटकनाशके": entry.get("Pesticide_MR", ""),
|
| 93 |
+
"किटकनाशक शिफारस": entry.get("Pesticide_Recommendation", {}).get("mr", ""),
|
| 94 |
+
"नियंत्रण पद्धती": entry.get("Management_MR", ""),
|
| 95 |
+
"रोगजन्य घटक": entry.get("Pathogen", ""),
|
| 96 |
+
"विश्वासार्हता": f"{confidence:.2%}" if confidence else "N/A"
|
| 97 |
+
}
|
| 98 |
+
return None
|
| 99 |
+
|
| 100 |
+
# ===================== NLP PREDICTION =====================
|
| 101 |
+
def detect_language(query: str) -> str:
|
| 102 |
+
try:
|
| 103 |
+
lang = detect(query)
|
| 104 |
+
return lang if lang in ["mr", "hi"] else "en"
|
| 105 |
+
except:
|
| 106 |
+
return "en"
|
| 107 |
+
|
| 108 |
+
def predict_disease_from_text(query: str):
|
| 109 |
+
lang = detect_language(query)
|
| 110 |
+
query_emb = embedder.encode([query], normalize_embeddings=True)
|
| 111 |
+
|
| 112 |
+
symptom_key = f"Symptoms_{lang.upper()}" if lang != "en" else "Symptoms"
|
| 113 |
+
pairs = [[query, entry.get(symptom_key, "")] for entry in kb_data]
|
| 114 |
+
scores = cross_encoder.predict(pairs)
|
| 115 |
+
best_idx = np.argmax(scores)
|
| 116 |
+
|
| 117 |
+
if scores[best_idx] < 0.2:
|
| 118 |
+
return {
|
| 119 |
+
"message": {
|
| 120 |
+
"mr": "हा रोग आमच्या डेटा���ेसमध्ये नाही.",
|
| 121 |
+
"hi": "यह रोग हमारे डेटाबेस में नहीं है।",
|
| 122 |
+
"en": "This disease is not in our database."
|
| 123 |
+
}[lang]
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
entry = kb_data[best_idx]
|
| 127 |
+
return {
|
| 128 |
+
"पिक": entry.get("Crop", "केळी"),
|
| 129 |
+
"रोग": entry["Local_Name"].get(lang, entry["Disease"]),
|
| 130 |
+
"लक्षणे": entry.get(symptom_key, ""),
|
| 131 |
+
"कारण": entry.get(f"Cause_{lang.upper()}", entry.get("Cause", "")),
|
| 132 |
+
"किटकनाशक शिफारस": entry.get("Pesticide_Recommendation", {}).get(lang, ""),
|
| 133 |
+
"किटकनाशके": entry.get("Pesticide", ""),
|
| 134 |
+
"रोगजन्य घटक": entry.get("Pathogen", ""),
|
| 135 |
+
"नियंत्रण पद्धती": entry.get(f"Management_{lang.upper()}", entry.get("Management_Practices", "")),
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
# ===================== STREAMLIT UI =====================
|
| 139 |
+
st.set_page_config(page_title="🍌\ Banana Disease Detection (CNN + NLP)", layout="centered")
|
| 140 |
+
st.title(" केळीच्या पानांवरील रोगांचे निदान")
|
| 141 |
+
st.markdown("प्रतिमा किंवा लक्षणे वापरून केळीवरील रोगांचे निदान करा (मराठी, हिंदी, इंग्रजी भाषांमध्ये).")
|
| 142 |
+
|
| 143 |
+
option = st.radio("इनपुट पद्धत निवडा:", ["Image Only", "Text Only", "Both"])
|
| 144 |
+
|
| 145 |
+
# ===================== IMAGE FLOW =====================
|
| 146 |
+
if option in ["Image Only", "Both"]:
|
| 147 |
+
st.subheader(" प्रतिमा अपलोड करा")
|
| 148 |
+
uploaded_img = st.file_uploader("JPG / PNG", type=["jpg", "jpeg", "png"])
|
| 149 |
+
if uploaded_img:
|
| 150 |
+
temp_path = "temp_uploaded.jpg"
|
| 151 |
+
with open(temp_path, "wb") as f:
|
| 152 |
+
f.write(uploaded_img.getbuffer())
|
| 153 |
+
|
| 154 |
+
st.image(temp_path, caption="अपलोड केलेली प्रतिमा", use_column_width=True)
|
| 155 |
+
st.info("CLIP मॉडेलद्वारे पडताळणी करत आहे...")
|
| 156 |
+
|
| 157 |
+
status, reason, clip_conf = verify_image_with_clip(temp_path)
|
| 158 |
+
if status == "REJECTED":
|
| 159 |
+
st.error(f" CLIP नकार: {reason} [विश्वासार्हता: {clip_conf:.2f}]")
|
| 160 |
+
else:
|
| 161 |
+
st.success(f" CLIP मंजूरी: शक्यतो केळीचे पान [विश्वासार्हता: {clip_conf:.2f}]")
|
| 162 |
+
pred_disease, cnn_conf, img = predict_disease(temp_path)
|
| 163 |
+
st.markdown(f"**ओळखलेला रोग:** {pred_disease} (विश्वासार्हता: {cnn_conf:.2%})")
|
| 164 |
+
|
| 165 |
+
marathi_info = get_marathi_recommendation_fuzzy(pred_disease, cnn_conf)
|
| 166 |
+
if marathi_info:
|
| 167 |
+
st.subheader(" मराठी शिफारस:")
|
| 168 |
+
for k, v in marathi_info.items():
|
| 169 |
+
st.markdown(f"**{k}**: {v}")
|
| 170 |
+
else:
|
| 171 |
+
st.warning(" ज्ञानतळात रोगासाठी माहिती नाही.")
|
| 172 |
+
st.image(img, caption=f"{pred_disease} ({cnn_conf:.2%})", use_column_width=True)
|
| 173 |
+
|
| 174 |
+
os.remove(temp_path)
|
| 175 |
+
|
| 176 |
+
# ===================== TEXT FLOW =====================
|
| 177 |
+
if option in ["Text Only", "Both"]:
|
| 178 |
+
st.subheader(" लक्षणे लिहा")
|
| 179 |
+
symptoms = st.text_area("लक्षणे (मराठी / हिंदी / इंग्रजी):")
|
| 180 |
+
if symptoms and st.button(" रोग ओळखा"):
|
| 181 |
+
result = predict_disease_from_text(symptoms)
|
| 182 |
+
if "message" in result:
|
| 183 |
+
st.warning(result["message"])
|
| 184 |
+
else:
|
| 185 |
+
st.subheader(" शिफारस:")
|
| 186 |
+
for k, v in result.items():
|
| 187 |
+
st.markdown(f"**{k}**: {v}")
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tensorflow==2.18.0
|
| 2 |
+
torch==2.6.0+cu124
|
| 3 |
+
transformers==4.54.0
|
| 4 |
+
joblib==1.5.1
|
| 5 |
+
opencv-python-headless== 4.12.0.88
|
| 6 |
+
numpy==2.0.2
|
| 7 |
+
matplotlib==3.10.0
|
| 8 |
+
pandas==2.2.2
|