sana088 commited on
Commit
1cefcdc
·
verified ·
1 Parent(s): a5d3d1c

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +354 -0
  2. config.toml +3 -0
  3. leaf_disease_model.h5 +3 -0
  4. requirements.txt +8 -3
app.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import tensorflow as tf
4
+ from PIL import Image, ImageOps
5
+ import numpy as np
6
+ from deep_translator import GoogleTranslator
7
+ from groq import Groq
8
+ from gtts import gTTS
9
+ import base64
10
+ from streamlit_mic_recorder import speech_to_text
11
+
12
+ # --- PAGE CONFIG & THEME ---
13
+ st.set_page_config(page_title="AgroIntel", page_icon="🌿", layout="wide")
14
+
15
+ # Custom CSS for Green & White Theme + Mobile Responsiveness + Dabbe + Drag&Drop
16
+ page_bg_css = """
17
+ <style>
18
+ [data-testid="stAppViewContainer"] {
19
+ background-color: #F9FFF6; /* Very light mint white */
20
+ color: #1B5E20; /* Dark Green Text */
21
+ }
22
+ [data-testid="stSidebar"] {
23
+ background-color: #E8F5E9; /* Light Green Sidebar */
24
+ }
25
+ h1, h2, h3, h4, span, p {
26
+ color: #1B5E20 !important;
27
+ }
28
+
29
+ /* Tab Container Adjustments */
30
+ .stTabs [data-baseweb="tab-list"] {
31
+ gap: 10px;
32
+ overflow-x: auto;
33
+ padding-bottom: 5px;
34
+ }
35
+
36
+ /* Default Desktop Tab Styling */
37
+ .stTabs [data-baseweb="tab"] {
38
+ height: auto;
39
+ min-height: 45px;
40
+ white-space: nowrap !important;
41
+ background-color: #ffffff;
42
+ border-radius: 5px;
43
+ box-shadow: 0px 2px 5px rgba(0,0,0,0.1);
44
+ padding: 10px 15px;
45
+ font-size: 16px;
46
+ }
47
+
48
+ .stTabs [aria-selected="true"] {
49
+ background-color: #4CAF50 !important;
50
+ color: white !important;
51
+ }
52
+
53
+ /* 🎨 Make Radio Buttons look like clickable Cards (Dabbe) */
54
+ div[role="radiogroup"] {
55
+ display: flex;
56
+ flex-direction: row;
57
+ flex-wrap: wrap;
58
+ gap: 15px;
59
+ width: 100%;
60
+ }
61
+ div[role="radiogroup"] > label {
62
+ background-color: #ffffff;
63
+ border: 2px solid #E8F5E9;
64
+ border-radius: 12px;
65
+ padding: 12px 15px;
66
+ box-shadow: 0px 2px 5px rgba(0,0,0,0.05);
67
+ flex: 1;
68
+ min-width: 110px;
69
+ white-space: nowrap;
70
+ justify-content: center;
71
+ cursor: pointer;
72
+ transition: all 0.3s ease;
73
+ margin: 0 !important;
74
+ }
75
+ div[role="radiogroup"] > label:hover {
76
+ border-color: #4CAF50;
77
+ background-color: #F1F8E9;
78
+ }
79
+
80
+ /* ☁️ BRUTE-FORCE BADA DABBA */
81
+ div[data-testid="stFileUploader"] section {
82
+ border: 2px dashed #4CAF50 !important;
83
+ background-color: #FAFAFA !important;
84
+ border-radius: 15px !important;
85
+ padding: 60px 20px !important;
86
+ min-height: 200px !important;
87
+ display: flex !important;
88
+ flex-direction: column !important;
89
+ align-items: center !important;
90
+ justify-content: center !important;
91
+ }
92
+
93
+ div[data-testid="stFileUploader"] section:hover {
94
+ background-color: #F1F8E9 !important;
95
+ border-color: #1B5E20 !important;
96
+ }
97
+
98
+ /* Make the upload icon inside bigger */
99
+ [data-testid="stFileUploadDropzone"] svg {
100
+ width: 60px !important;
101
+ height: 60px !important;
102
+ color: #4CAF50 !important;
103
+ }
104
+
105
+ /* Mobile Specific Styling */
106
+ @media (max-width: 768px) {
107
+ .stTabs [data-baseweb="tab"] {
108
+ padding: 8px 12px;
109
+ font-size: 14px;
110
+ min-height: 38px;
111
+ }
112
+ div[role="radiogroup"] > label {
113
+ padding: 10px 5px;
114
+ font-size: 14px;
115
+ min-width: 80px;
116
+ }
117
+ }
118
+ </style>
119
+ """
120
+ st.markdown(page_bg_css, unsafe_allow_html=True)
121
+ # --- LOAD MODEL ---
122
+ @st.cache_resource
123
+ def load_my_model():
124
+ return tf.keras.models.load_model('leaf_disease_model.h5')
125
+
126
+ model = load_my_model()
127
+
128
+ # --- DATASETS & LABELS (15 Classes) ---
129
+ labels = [
130
+ 'Pepper__bell___Bacterial_spot', 'Pepper__bell___healthy',
131
+ 'Potato___Early_blight', 'Potato___Late_blight', 'Potato___healthy',
132
+ 'Tomato_Bacterial_spot', 'Tomato_Early_blight', 'Tomato_Late_blight',
133
+ 'Tomato_Leaf_Mold', 'Tomato_Septoria_leaf_spot',
134
+ 'Tomato_Spider_mites_Two_spotted_spider_mite', 'Tomato__Target_Spot',
135
+ 'Tomato__Tomato_YellowLeaf__Curl_Virus', 'Tomato__Tomato_mosaic_virus',
136
+ 'Tomato_healthy'
137
+ ]
138
+
139
+ remedies_dict = {
140
+ 'Pepper__bell___Bacterial_spot': "Remove infected plants immediately. Use copper-based fungicides every week. Avoid watering the leaves to keep the foliage dry.",
141
+ 'Pepper__bell___healthy': "Your plant is perfectly healthy! Ensure consistent watering and well-draining soil.",
142
+ 'Potato___Early_blight': "Use chlorothalonil fungicides. Rotate your crops yearly and avoid planting potatoes in the same spot.",
143
+ 'Potato___Late_blight': "Destroy infected debris immediately. Use systemic fungicides like Ridomil and harvest only in dry weather.",
144
+ 'Potato___healthy': "Healthy potato leaf! Monitor water levels and maintain proper spacing for good airflow.",
145
+ 'Tomato_Bacterial_spot': "Apply copper sprays immediately. Avoid watering leaves directly to prevent the spread of bacteria. Always disinfect pruning tools.",
146
+ 'Tomato_Early_blight': "Improve airflow by pruning bottom leaves. Use organic mulch to prevent soil splashing and apply natural bio-fungicides.",
147
+ 'Tomato_Late_blight': "This is highly contagious! Pull out and burn infected plants. Treat nearby healthy plants with protective fungicides.",
148
+ 'Tomato_Leaf_Mold': "Increase ventilation around your plants. Keep humidity below 85 percent and avoid wetting the leaves during watering.",
149
+ 'Tomato_Septoria_leaf_spot': "Remove the lowest affected leaves. Apply a fungicide spray containing Mancozeb and avoid overhead watering.",
150
+ 'Tomato_Spider_mites_Two_spotted_spider_mite': "Use Neem Oil spray directly on the pests. Lightly mist the leaves as mites hate high humidity.",
151
+ 'Tomato__Target_Spot': "Keep foliage dry and ensure excellent air circulation. Apply appropriate fungicides weekly and remove older infected leaves.",
152
+ 'Tomato__Tomato_YellowLeaf__Curl_Virus': "Use sticky traps for whiteflies which spread the virus. Control weeds and uproot severely stunted plants.",
153
+ 'Tomato__Tomato_mosaic_virus': "There is no cure for this virus. Burn the infected plants immediately and disinfect all your gardening tools.",
154
+ 'Tomato_healthy': "Your tomato plant is thriving! Continue your current watering schedule and ensure it gets enough sunlight."
155
+ }
156
+
157
+ # --- TRACKER HELPER FUNCTION ---
158
+ def calculate_green_ratio(image):
159
+ img_array = np.array(image.convert('RGB'))
160
+ green_mask = (img_array[:,:,1] > img_array[:,:,0]) & (img_array[:,:,1] > img_array[:,:,2])
161
+ green_ratio = np.sum(green_mask) / (img_array.shape[0] * img_array.shape[1]) * 100
162
+ return round(green_ratio, 2)
163
+
164
+ # --- HEADER & LANGUAGE SETTINGS ---
165
+ st.title("🌿 AgroIntel")
166
+ language = st.selectbox("🌐 Select Language", ("English", "Hindi", "Kannada"))
167
+ lang_map = {"English": "en", "Hindi": "hi", "Kannada": "kn"}
168
+
169
+ # --- TABS NAVIGATION ---
170
+ tab_home, tab_detect, tab_track, tab_chat = st.tabs([
171
+ "🏠 Home / Guide",
172
+ "📸 Disease Detection",
173
+ "📈 Recovery Tracker",
174
+ "💬 AgroBot"
175
+ ])
176
+
177
+ # --- TAB 1: HOME / GUIDE ---
178
+ with tab_home:
179
+ st.subheader("Welcome to AgroIntel")
180
+ st.write("An AI-powered agricultural assistant to help farmers diagnose crop diseases and track plant health.")
181
+ st.divider()
182
+ guide_lang = st.radio("Read 'How to Use' in your language:", ("English", "Hindi", "Kannada", "Telugu"), horizontal=True)
183
+
184
+ guides = {
185
+ "English": "**How to Use AgroIntel:**\n1. Go to **Disease Detection** tab to upload/click a photo.\n2. Wait for AI analysis and translated remedies.\n3. Use **Recovery Tracker** to compare old and new photos.\n4. Ask any farming query in **AgroBot** tab.",
186
+ "Hindi": "**AgroIntel का उपयोग कैसे करें:**\n1. फोटो अपलोड/खींचने के लिए **Disease Detection** टैब पर जाएं।\n2. AI विश्लेषण और अनुवादित उपायों का इंतज़ार करें।\n3. पुरानी और नई फोटो की तुलना के लिए **Recovery Tracker** का उपयोग करें।\n4. खेती के किसी भी सवाल के लिए **AgroBot** टैब पर पूछेंं।",
187
+ "Kannada": "**AgroIntel ಹೇಗೆ ಬಳಸುವುದು:**\n1. ಫೋಟೋ ಅಪ್‌ಲೋಡ್ ಮಾಡಲು **Disease Detection** ಟ್ಯಾಬ್‌ಗೆ ಹೋಗಿ.\n2. AI ವಿಶ್ಲೇಷಣೆ ಮತ್ತು ಪರಿಹಾರಗಳಿಗಾಗಿ ಕಾಯಿರಿ.\n3. ಹಳೆಯ ಮತ್ತು ಹೊಸ ಫೋಟೋ ಹೋಲಿಸಲು **Recovery Tracker** ಬಳಸಿ.\n4. ಕೃಷಿ ಪ್ರಶ್ನೆಗಳಿಗಾಗಿ **AgroBot** ಬಳಸಿ.",
188
+
189
+ }
190
+ st.info(guides[guide_lang])
191
+
192
+ # --- TAB 2: DISEASE DETECTION ---
193
+ with tab_detect:
194
+ col1, col2 = st.columns([1, 1])
195
+ with col1:
196
+ st.subheader("Input Image")
197
+ # Horizontal setting and emojis make it look like premium cards
198
+ source_option = st.radio("Choose Input Source:", ("📁 Upload File", "📸 Camera"), horizontal=True)
199
+ if source_option == "📁 Upload File":
200
+ file = st.file_uploader("Select an image file", type=["jpg", "png", "jpeg"])
201
+ else:
202
+ file = st.camera_input("Take a picture of the leaf")
203
+
204
+ if file:
205
+ img = Image.open(file)
206
+ with col1:
207
+ st.image(img, use_container_width=True)
208
+ with col2:
209
+ st.subheader("AI Analysis Results")
210
+ with st.spinner("Analyzing cell structure..."):
211
+ expected_shape = model.input_shape
212
+ target_size = (expected_shape[1], expected_shape[2])
213
+ image_resized = ImageOps.fit(img, target_size, Image.Resampling.LANCZOS).convert('RGB')
214
+
215
+ img_array = np.asarray(image_resized) / 255.0
216
+ img_reshape = img_array[np.newaxis, ...]
217
+ prediction = model.predict(img_reshape)
218
+ raw_result = labels[np.argmax(prediction)]
219
+
220
+ if language == "English":
221
+ translated_result = raw_result.replace("_", " ")
222
+ translated_remedy = remedies_dict.get(raw_result, "No specific remedy found.")
223
+ else:
224
+ translated_result = GoogleTranslator(source='auto', target=lang_map[language]).translate(raw_result)
225
+ remedy = remedies_dict.get(raw_result, "No specific remedy found.")
226
+ try:
227
+ translated_remedy = GoogleTranslator(source='auto', target=lang_map[language]).translate(remedy)
228
+ if not translated_remedy or translated_remedy.strip() == "":
229
+ translated_remedy = remedy
230
+ except Exception:
231
+ translated_remedy = remedy
232
+
233
+ st.success(f"### 🦠 {translated_result}")
234
+ st.warning(f"**🩺 Remedy / Treatment:** \n\n {translated_remedy}")
235
+
236
+ # --- TAB 3: RECOVERY TRACKER ---
237
+ with tab_track:
238
+ st.subheader("📈 Plant Health & Recovery Tracker")
239
+ st.write("Upload or capture photos to analyze plant healing metrics over time.")
240
+ track_col1, track_col2 = st.columns(2)
241
+
242
+ with track_col1:
243
+ st.write("**📅 Day 1 (Infected) Image**")
244
+ day1_source = st.radio("Source for Day 1:", ("📁 Upload File", "📸 Camera"), key="d1_radio", horizontal=True)
245
+ if day1_source == "📁 Upload File":
246
+ day1_file = st.file_uploader("Select Day 1 Image", type=["jpg", "png", "jpeg"], key="d1_up")
247
+ else:
248
+ day1_file = st.camera_input("Take Day 1 Picture", key="d1_cam")
249
+
250
+ with track_col2:
251
+ st.write("**🌿 Current (Recent) Image**")
252
+ current_source = st.radio("Source for Current Day:", ("📁 Upload File", "📸 Camera"), key="cur_radio", horizontal=True)
253
+ if current_source == "📁 Upload File":
254
+ current_file = st.file_uploader("Select Current Image", type=["jpg", "png", "jpeg"], key="cur_up")
255
+ else:
256
+ current_file = st.camera_input("Take Current Picture", key="cur_cam")
257
+
258
+ if day1_file and current_file:
259
+ img_day1 = Image.open(day1_file)
260
+ img_current = Image.open(current_file)
261
+ st.divider()
262
+ st.write("### 🔍 Visual Comparison")
263
+ show_col1, show_col2 = st.columns(2)
264
+
265
+ with show_col1:
266
+ st.image(img_day1, caption="Day 1", use_container_width=True)
267
+ day1_green = calculate_green_ratio(img_day1)
268
+ st.metric(label="Healthy Green Area (Day 1)", value=f"{day1_green}%")
269
+ with show_col2:
270
+ st.image(img_current, caption="Current Day", use_container_width=True)
271
+ current_green = calculate_green_ratio(img_current)
272
+ diff = round(current_green - day1_green, 2)
273
+ st.metric(label="Healthy Green Area (Current)", value=f"{current_green}%", delta=f"{diff}%")
274
+
275
+ if diff > 0:
276
+ st.success("✅ The plant shows signs of recovery! The healthy green surface area has increased.")
277
+ else:
278
+ st.error("⚠️ The infection might still be spreading or unchanged. Check AgroBot for remedies.")
279
+
280
+ # --- TAB 4: CHATBOT ASSISTANT (Final & Bulletproof) ---
281
+ with tab_chat:
282
+ st.subheader(f"💬 AgroBot (Responding in {language})")
283
+ st.write("Discuss plant health, get farming tips, or ask about specific diseases.")
284
+ st.divider()
285
+
286
+ # 1. Initialize Chat History
287
+ if "messages" not in st.session_state:
288
+ st.session_state.messages = []
289
+
290
+ # 2. Display Chat History
291
+ for message in st.session_state.messages:
292
+ with st.chat_message(message["role"], avatar="🌿" if message["role"] == "assistant" else "👤"):
293
+ st.markdown(message["content"])
294
+
295
+ # 3. Handle Voice Input
296
+ audio_query = None
297
+ with st.expander("🎤 Use Voice Input (English/Hindi/Kannada)", expanded=False):
298
+ # We use speech_to_text to convert voice directly into words!
299
+ spoken_text = speech_to_text(
300
+ language=lang_map[language],
301
+ start_prompt="🎤 Click to Speak",
302
+ stop_prompt="🛑 Stop & Send",
303
+ key='voice_input'
304
+ )
305
+ if spoken_text:
306
+ audio_query = spoken_text
307
+ st.success(f"Recognized Voice: {audio_query}")
308
+
309
+ # 4. Handle Text Input
310
+ user_prompt = st.chat_input("Type your farming question here...")
311
+ final_prompt = user_prompt or audio_query
312
+
313
+ # 5. Process Input & Generate Response
314
+ if final_prompt:
315
+ # Display user message
316
+ st.session_state.messages.append({"role": "user", "content": final_prompt})
317
+ with st.chat_message("user", avatar="👤"):
318
+ st.markdown(final_prompt)
319
+
320
+ api_key = "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"
321
+ if not api_key:
322
+ st.warning("⚠️ GROQ_API_KEY is not set in the environment variables.")
323
+ else:
324
+ client = Groq(api_key=api_key)
325
+ with st.spinner("AgroBot is thinking and generating voice..."):
326
+ system_prompt = f"You are an expert farmer's assistant. Answer ONLY in {language} language. Keep the answer to 2-3 short, actionable sentences."
327
+ try:
328
+ # Get AI Text Response
329
+ response = client.chat.completions.create(
330
+ messages=[{"role": "system", "content": system_prompt}, {"role": "user", "content": final_prompt}],
331
+ model="llama-3.1-8b-instant",
332
+ )
333
+ ans = response.choices[0].message.content
334
+
335
+ # Display AI Text
336
+ st.session_state.messages.append({"role": "assistant", "content": ans})
337
+ with st.chat_message("assistant", avatar="🌿"):
338
+ st.markdown(ans)
339
+
340
+ # Generate & Play AI Voice (Fail-Safe)
341
+ if lang_map[language] in ["en", "hi", "kn"]:
342
+ try:
343
+ # Truncate text for audio if it's too long (saves API calls and prevents 429 error)
344
+ audio_text = ans[:500] if len(ans) > 500 else ans
345
+ tts = gTTS(text=audio_text, lang=lang_map[language])
346
+ tts.save("bot_voice.mp3")
347
+ # Autoplay is True so the bot speaks automatically!
348
+ st.audio("bot_voice.mp3", format="audio/mp3", autoplay=True)
349
+ except Exception:
350
+ # Silently ignore TTS 429 errors, keep UI clean
351
+ pass
352
+
353
+ except Exception as e:
354
+ st.error(f"Error generating text response: {e}")
config.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [theme]
2
+ base="light"
3
+ primaryColor="#4CAF50"
leaf_disease_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72b608956c36cace280375c144a8b58066568155360d55ef68ddfc3459445072
3
+ size 134097816
requirements.txt CHANGED
@@ -1,3 +1,8 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
1
+ streamlit
2
+ tensorflow
3
+ pillow
4
+ deep-translator
5
+ groq
6
+ numpy
7
+ gTTS
8
+ streamlit-mic-recorder