Spaces:
Runtime error
Runtime error
AdityaAdaki
commited on
Commit
·
00fd610
1
Parent(s):
d60910c
starter
Browse files- app.py +348 -0
- models/cotton_model.h5 +3 -0
- models/maize_model.h5 +3 -0
- models/rice.h5 +3 -0
- models/sugercane_model.h5 +3 -0
- models/wheat_model.h5 +3 -0
app.py
ADDED
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import tensorflow as tf
|
3 |
+
import tensorflow_hub as hub
|
4 |
+
import numpy as np
|
5 |
+
from PIL import Image
|
6 |
+
import requests
|
7 |
+
from googletrans import Translator
|
8 |
+
import asyncio
|
9 |
+
import nest_asyncio
|
10 |
+
import os
|
11 |
+
|
12 |
+
# Apply the nest_asyncio patch to allow nested event loops in Streamlit
|
13 |
+
nest_asyncio.apply()
|
14 |
+
|
15 |
+
# Set page configuration with a custom title, icon, and wide layout
|
16 |
+
st.set_page_config(
|
17 |
+
page_title="Plant Disease Classifier 🌱",
|
18 |
+
page_icon="🌱",
|
19 |
+
layout="wide",
|
20 |
+
initial_sidebar_state="expanded",
|
21 |
+
)
|
22 |
+
|
23 |
+
# Custom CSS for styling
|
24 |
+
custom_css = """
|
25 |
+
<style>
|
26 |
+
body {
|
27 |
+
background-color: #f8f9fa;
|
28 |
+
}
|
29 |
+
h1, h2, h3, h4 {
|
30 |
+
color: #2c3e50;
|
31 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
32 |
+
}
|
33 |
+
.stButton>button {
|
34 |
+
background-color: #27ae60;
|
35 |
+
color: white;
|
36 |
+
border: none;
|
37 |
+
padding: 0.5em 1em;
|
38 |
+
border-radius: 5px;
|
39 |
+
font-size: 16px;
|
40 |
+
}
|
41 |
+
.sidebar .sidebar-content {
|
42 |
+
background-image: linear-gradient(#27ae60, #2ecc71);
|
43 |
+
color: white;
|
44 |
+
}
|
45 |
+
</style>
|
46 |
+
"""
|
47 |
+
st.markdown(custom_css, unsafe_allow_html=True)
|
48 |
+
|
49 |
+
# Dictionary mapping diseases to recommended pesticides (fallback recommendations)
|
50 |
+
pesticide_recommendations = {
|
51 |
+
'Bacterial Blight': 'Copper-based fungicides, Streptomycin',
|
52 |
+
'Red Rot': 'Fungicides containing Mancozeb or Copper',
|
53 |
+
'Blight': 'Fungicides containing Chlorothalonil',
|
54 |
+
'Common_Rust': 'Fungicides containing Azoxystrobin or Propiconazole',
|
55 |
+
'Gray_Leaf_Spot,Healthy': 'Fungicides containing Azoxystrobin or Propiconazole',
|
56 |
+
'Bacterial blight': 'Copper-based fungicides, Streptomycin',
|
57 |
+
'curl_virus': 'Insecticides such as Imidacloprid or Pyrethroids',
|
58 |
+
'fussarium_wilt': 'Soil fumigants, Fungicides containing Thiophanate-methyl',
|
59 |
+
'Bacterial_blight': 'Copper-based fungicides, Streptomycin',
|
60 |
+
'Blast': 'Fungicides containing Tricyclazole or Propiconazole',
|
61 |
+
'Brownspot': 'Fungicides containing Azoxystrobin or Propiconazole',
|
62 |
+
'Tungro': 'Insecticides such as Neonicotinoids or Pyrethroids',
|
63 |
+
'septoria': 'Fungicides containing Azoxystrobin or Propiconazole',
|
64 |
+
'strip_rust': 'Fungicides containing Azoxystrobin or Propiconazole'
|
65 |
+
}
|
66 |
+
|
67 |
+
|
68 |
+
def recommend_pesticide(predicted_class):
|
69 |
+
if predicted_class == 'Healthy':
|
70 |
+
return 'No need for any pesticide, plant is healthy'
|
71 |
+
return pesticide_recommendations.get(predicted_class, "No recommendation available")
|
72 |
+
|
73 |
+
|
74 |
+
@st.cache_resource(show_spinner=False)
|
75 |
+
def load_model_with_hub(model_path):
|
76 |
+
custom_objects = {"KerasLayer": hub.KerasLayer}
|
77 |
+
return tf.keras.models.load_model(model_path, custom_objects=custom_objects)
|
78 |
+
|
79 |
+
|
80 |
+
# Load models (ensure your model paths are correct)
|
81 |
+
models = {
|
82 |
+
'sugarcane': load_model_with_hub("models/sugercane_model.h5"),
|
83 |
+
'maize': load_model_with_hub("models/maize_model.h5"),
|
84 |
+
'cotton': load_model_with_hub("models/cotton_model.h5"),
|
85 |
+
'rice': load_model_with_hub("models/rice.h5"),
|
86 |
+
'wheat': load_model_with_hub("models/wheat_model.h5"),
|
87 |
+
}
|
88 |
+
|
89 |
+
# Class names for each model
|
90 |
+
class_names = {
|
91 |
+
'sugarcane': ['Bacterial Blight', 'Healthy', 'Red Rot'],
|
92 |
+
'maize': ['Blight', 'Common_Rust', 'Gray_Leaf_Spot,Healthy'],
|
93 |
+
'cotton': ['Bacterial blight', 'curl_virus', 'fussarium_wilt', 'Healthy'],
|
94 |
+
'rice': ['Bacterial_blight', 'Blast', 'Brownspot', 'Tungro'],
|
95 |
+
'wheat': ['Healthy', 'septoria', 'strip_rust'],
|
96 |
+
}
|
97 |
+
|
98 |
+
|
99 |
+
def preprocess_image(image_file):
|
100 |
+
"""Preprocess the uploaded image: open, convert to RGB, resize, normalize, and add batch dimension."""
|
101 |
+
try:
|
102 |
+
image = Image.open(image_file).convert("RGB")
|
103 |
+
image = image.resize((224, 224))
|
104 |
+
img_array = np.array(image).astype("float32") / 255.0
|
105 |
+
return np.expand_dims(img_array, axis=0)
|
106 |
+
except Exception as e:
|
107 |
+
st.error("Error processing image. Please upload a valid image file.")
|
108 |
+
return None
|
109 |
+
|
110 |
+
|
111 |
+
def classify_image(model_name, image_file):
|
112 |
+
input_image = preprocess_image(image_file)
|
113 |
+
if input_image is None:
|
114 |
+
return None, None
|
115 |
+
predictions = models[model_name].predict(input_image)
|
116 |
+
predicted_index = np.argmax(predictions)
|
117 |
+
predicted_class = class_names[model_name][predicted_index]
|
118 |
+
recommended_pesticide = recommend_pesticide(predicted_class)
|
119 |
+
return predicted_class, recommended_pesticide
|
120 |
+
|
121 |
+
|
122 |
+
def get_plant_info(disease, plant_type="Unknown"):
|
123 |
+
"""
|
124 |
+
Retrieve detailed plant disease information from LM Studio using a fixed prompt.
|
125 |
+
"""
|
126 |
+
prompt = f"""
|
127 |
+
Disease Name: {disease}
|
128 |
+
Plant Type: {plant_type}
|
129 |
+
|
130 |
+
Explain this disease in a very simple and easy-to-understand way, as if you are talking to a farmer with no scientific background. Use simple words and avoid technical terms.
|
131 |
+
|
132 |
+
Include the following details:
|
133 |
+
|
134 |
+
- Symptoms: What signs will the farmer see on the plant? How will the leaves, stem, or fruit look?
|
135 |
+
- Causes: Why does this disease happen?
|
136 |
+
- Severity: How serious is this disease? Does it spread quickly? How much crop damage can it cause?
|
137 |
+
- How It Spreads: How does this disease grow? What will happen if the farmer does nothing?
|
138 |
+
- Treatment & Prevention: What pesticides or sprays should the farmer use and what steps can be taken to prevent the disease?
|
139 |
+
"""
|
140 |
+
try:
|
141 |
+
response = requests.post(LM_STUDIO_API_URL, json={"messages": [{"role": "user", "content": prompt}]})
|
142 |
+
response.raise_for_status()
|
143 |
+
data = response.json()
|
144 |
+
detailed_info = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
145 |
+
return {"detailed_info": detailed_info}
|
146 |
+
except Exception as e:
|
147 |
+
st.error("Error retrieving detailed plant info.")
|
148 |
+
return {"detailed_info": ""}
|
149 |
+
|
150 |
+
|
151 |
+
def get_web_pesticide_info(disease, plant_type="Unknown"):
|
152 |
+
"""
|
153 |
+
Query Google Custom Search for updated pesticide recommendations.
|
154 |
+
"""
|
155 |
+
query = f"site:agrowon.esakal.com {disease} in {plant_type}"
|
156 |
+
url = "https://www.googleapis.com/customsearch/v1"
|
157 |
+
params = {
|
158 |
+
"key": GOOGLE_API_KEY,
|
159 |
+
"cx": GOOGLE_CX,
|
160 |
+
"q": query,
|
161 |
+
"num": 3
|
162 |
+
}
|
163 |
+
try:
|
164 |
+
response = requests.get(url, params=params)
|
165 |
+
response.raise_for_status()
|
166 |
+
data = response.json()
|
167 |
+
if "items" in data and len(data["items"]) > 0:
|
168 |
+
item = data["items"][0]
|
169 |
+
title = item.get("title", "No title available")
|
170 |
+
link = item.get("link", "#")
|
171 |
+
snippet = item.get("snippet", "No snippet available")
|
172 |
+
return {"title": title, "link": link, "snippet": snippet, "summary": snippet}
|
173 |
+
except Exception as e:
|
174 |
+
st.error("Error retrieving web pesticide info.")
|
175 |
+
return None
|
176 |
+
|
177 |
+
|
178 |
+
def get_more_web_info(query):
|
179 |
+
"""
|
180 |
+
Query Google Custom Search for more articles or information.
|
181 |
+
"""
|
182 |
+
url = "https://www.googleapis.com/customsearch/v1"
|
183 |
+
params = {
|
184 |
+
"key": GOOGLE_API_KEY,
|
185 |
+
"cx": GOOGLE_CX,
|
186 |
+
"q": query,
|
187 |
+
"num": 3
|
188 |
+
}
|
189 |
+
try:
|
190 |
+
response = requests.get(url, params=params)
|
191 |
+
response.raise_for_status()
|
192 |
+
data = response.json()
|
193 |
+
results = []
|
194 |
+
if "items" in data:
|
195 |
+
for item in data["items"]:
|
196 |
+
title = item.get("title", "No title available")
|
197 |
+
link = item.get("link", "#")
|
198 |
+
snippet = item.get("snippet", "No snippet available")
|
199 |
+
results.append({"title": title, "link": link, "snippet": snippet})
|
200 |
+
return results
|
201 |
+
except Exception as e:
|
202 |
+
st.error("Error retrieving additional articles.")
|
203 |
+
return []
|
204 |
+
|
205 |
+
|
206 |
+
def get_commercial_product_info(recommendation):
|
207 |
+
"""
|
208 |
+
Query Google Custom Search for commercial product details from IndiaMART and Krishisevakendra.
|
209 |
+
"""
|
210 |
+
indiamart_query = f"site:indiamart.com pesticide '{recommendation}'"
|
211 |
+
krishi_query = f"site:krishisevakendra.in/products pesticide '{recommendation}'"
|
212 |
+
indiamart_results = get_more_web_info(indiamart_query)
|
213 |
+
krishi_results = get_more_web_info(krishi_query)
|
214 |
+
return indiamart_results + krishi_results
|
215 |
+
|
216 |
+
|
217 |
+
# LM Studio API endpoint for detailed info (do not change key prompt values)
|
218 |
+
LM_STUDIO_API_URL = os.getenv("LM_STUDIO_API_URL", "http://192.168.56.1:1234/v1/chat/completions")
|
219 |
+
|
220 |
+
# Google Custom Search API key and CX
|
221 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
222 |
+
GOOGLE_CX = os.getenv("GOOGLE_CX")
|
223 |
+
|
224 |
+
# Initialize session state for language if not already done
|
225 |
+
if "language" not in st.session_state:
|
226 |
+
st.session_state.language = "English"
|
227 |
+
|
228 |
+
# Initialize Google Translator
|
229 |
+
translator = Translator()
|
230 |
+
|
231 |
+
|
232 |
+
# --- Async translation functions ---
|
233 |
+
async def async_translate_text(text):
|
234 |
+
translated = await translator.translate(text, src='en', dest='mr')
|
235 |
+
return translated.text
|
236 |
+
|
237 |
+
|
238 |
+
def translate_text(text):
|
239 |
+
"""
|
240 |
+
Translate text to Marathi if selected, otherwise return original text.
|
241 |
+
"""
|
242 |
+
if st.session_state.language == "Marathi":
|
243 |
+
try:
|
244 |
+
return asyncio.get_event_loop().run_until_complete(async_translate_text(text))
|
245 |
+
except Exception as e:
|
246 |
+
st.error("Translation error.")
|
247 |
+
return text
|
248 |
+
return text
|
249 |
+
|
250 |
+
|
251 |
+
def main():
|
252 |
+
# Sidebar with settings and file uploader
|
253 |
+
st.sidebar.title("Settings")
|
254 |
+
st.sidebar.info("Choose language and plant type, then upload an image to classify the disease.")
|
255 |
+
language_option = st.sidebar.radio("Language", options=["English", "Marathi"], index=0)
|
256 |
+
st.session_state.language = language_option
|
257 |
+
plant_type = st.sidebar.selectbox("Select Plant Type", options=['sugarcane', 'maize', 'cotton', 'rice', 'wheat'])
|
258 |
+
uploaded_file = st.sidebar.file_uploader("Upload a plant image...", type=["jpg", "jpeg", "png"])
|
259 |
+
|
260 |
+
# Header with a banner image and introductory text
|
261 |
+
col1, col2 = st.columns([1, 2])
|
262 |
+
with col1:
|
263 |
+
st.image("https://via.placeholder.com/150x150.png?text=Plant", caption=translate_text("Plant Health"),
|
264 |
+
use_container_width=True)
|
265 |
+
with col2:
|
266 |
+
st.title(translate_text("Krushi Mitra "))
|
267 |
+
st.write(translate_text(
|
268 |
+
"Plant Disease Classification and Pesticide Recommendation.\n\n"
|
269 |
+
"Upload an image of your plant, select the plant type from the sidebar, and click on Classify to get the diagnosis and recommendations."))
|
270 |
+
|
271 |
+
if uploaded_file is not None:
|
272 |
+
# Display the uploaded image in an appealing container
|
273 |
+
st.markdown("---")
|
274 |
+
st.subheader(translate_text("Uploaded Image"))
|
275 |
+
st.image(uploaded_file, use_container_width=True)
|
276 |
+
|
277 |
+
if st.button(translate_text("Classify")):
|
278 |
+
with st.spinner(translate_text("Classifying...")):
|
279 |
+
predicted_class, pesticide = classify_image(plant_type, uploaded_file)
|
280 |
+
if predicted_class:
|
281 |
+
st.success(translate_text("Classification Complete!"))
|
282 |
+
st.markdown(
|
283 |
+
f"### {translate_text('Predicted Class')} ({plant_type.capitalize()}): {translate_text(predicted_class)}")
|
284 |
+
st.markdown(f"### {translate_text('Recommended Pesticide')}: {translate_text(pesticide)}")
|
285 |
+
|
286 |
+
# Display results in tabs for a cleaner layout
|
287 |
+
tabs = st.tabs([translate_text("Detailed Info"), translate_text("Commercial Products"),
|
288 |
+
translate_text("More Articles")])
|
289 |
+
|
290 |
+
# Detailed Info Tab
|
291 |
+
with tabs[0]:
|
292 |
+
with st.spinner(translate_text("Retrieving detailed plant information...")):
|
293 |
+
info = get_plant_info(predicted_class, plant_type)
|
294 |
+
if info and info.get("detailed_info"):
|
295 |
+
st.markdown(translate_text("#### Detailed Plant Disease Information"))
|
296 |
+
st.markdown(translate_text(info.get("detailed_info")))
|
297 |
+
else:
|
298 |
+
st.info(translate_text("Detailed information is not available at the moment."))
|
299 |
+
|
300 |
+
# Inline web pesticide recommendations
|
301 |
+
web_recommendation = get_web_pesticide_info(predicted_class, plant_type)
|
302 |
+
if web_recommendation:
|
303 |
+
st.markdown(translate_text("#### Additional Pesticide Recommendations"))
|
304 |
+
st.markdown(f"{translate_text('Title')}:** {translate_text(web_recommendation['title'])}")
|
305 |
+
st.markdown(f"{translate_text('Summary')}:** {translate_text(web_recommendation['summary'])}")
|
306 |
+
if web_recommendation['link']:
|
307 |
+
st.markdown(f"[{translate_text('Read More')}]({web_recommendation['link']})")
|
308 |
+
else:
|
309 |
+
st.info(translate_text("No additional pesticide recommendations available."))
|
310 |
+
|
311 |
+
|
312 |
+
# Commercial Products Tab
|
313 |
+
with tabs[1]:
|
314 |
+
with st.spinner(translate_text("Retrieving commercial product details...")):
|
315 |
+
commercial_products = get_commercial_product_info(pesticide)
|
316 |
+
if commercial_products:
|
317 |
+
for item in commercial_products:
|
318 |
+
st.markdown(f"{translate_text('Title')}:** {translate_text(item['title'])}")
|
319 |
+
st.markdown(f"{translate_text('Snippet')}:** {translate_text(item['snippet'])}")
|
320 |
+
if item['link']:
|
321 |
+
st.markdown(f"[{translate_text('Read More')}]({item['link']})")
|
322 |
+
st.markdown("---")
|
323 |
+
else:
|
324 |
+
st.info(translate_text("No commercial product details available."))
|
325 |
+
|
326 |
+
|
327 |
+
|
328 |
+
# More Articles Tab
|
329 |
+
with tabs[2]:
|
330 |
+
with st.spinner(translate_text("Retrieving additional articles...")):
|
331 |
+
more_info = get_more_web_info(f"{predicted_class} in {plant_type}")
|
332 |
+
if more_info:
|
333 |
+
for item in more_info:
|
334 |
+
st.markdown(f"{translate_text('Title')}:** {translate_text(item['title'])}")
|
335 |
+
st.markdown(f"{translate_text('Snippet')}:** {translate_text(item['snippet'])}")
|
336 |
+
if item['link']:
|
337 |
+
st.markdown(f"[{translate_text('Read More')}]({item['link']})")
|
338 |
+
st.markdown("---")
|
339 |
+
else:
|
340 |
+
st.info(translate_text("No additional articles available."))
|
341 |
+
else:
|
342 |
+
st.error(translate_text("Error in classification. Please try again."))
|
343 |
+
else:
|
344 |
+
st.info(translate_text("Please upload an image from the sidebar to get started."))
|
345 |
+
|
346 |
+
|
347 |
+
if __name__ == "_main_":
|
348 |
+
main()
|
models/cotton_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4916bb8bf15a1d68677cfcf999f9f101d114535192f0443cea62ea447a5f08d1
|
3 |
+
size 9349072
|
models/maize_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:420bbc37a4973c870e7a0dea8c4be38a1ba4ad9b8d893502df0b10c7c0cd792a
|
3 |
+
size 9349072
|
models/rice.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8023e08529b017c4a0171bb3c4b800491affcce183a0af31bbd08712dec9b2c4
|
3 |
+
size 9302448
|
models/sugercane_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5fc1829fe65593eb62269fe81f411c4e6de8c2db7cddc11f40b7914c6c989d11
|
3 |
+
size 9333712
|
models/wheat_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4e4f281ac3b830933dfc3599f139a11b952c61fb0f4afcba41b7865beb293748
|
3 |
+
size 9333712
|