iqramukhtiar commited on
Commit
8b6482d
·
verified ·
1 Parent(s): 8cb32c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -86
app.py CHANGED
@@ -1,44 +1,27 @@
1
  import gradio as gr
2
  import pandas as pd
3
  import os
 
4
  from PIL import Image
 
5
  from torchvision import transforms
6
- from langchain_community.embeddings import HuggingFaceEmbeddings
7
- from langchain_groq import ChatGroq
8
 
9
  # --- Load CSV Data ---
10
  def load_treatments_data():
11
  try:
12
  context = pd.read_csv('./crop_diseases_treatments.csv')
13
  print("CSV file loaded successfully.")
14
- context_data = []
15
- for i in range(len(context)):
16
- contextn = ""
17
- for j in range(len(context.columns)):
18
- contextn += context.columns[j] + ":" + str(context.iloc[i][j]) + " "
19
- context_data.append(contextn)
20
- return context, context_data
21
  except FileNotFoundError:
22
  print("Error: crop_diseases_treatments.csv not found.")
23
  # Create a minimal dataframe for demonstration
24
  return pd.DataFrame({
25
- 'Crop': ['Tomato', 'Apple'],
26
- 'Disease': ['Early Blight', 'Apple Scab'],
27
- 'Symptoms': ['Yellow spots on leaves', 'Dark scab-like lesions'],
28
- 'Treatment': ['Remove affected leaves', 'Prune affected branches'],
29
- 'Medicine/Chemical Control': ['Copper fungicide', 'Sulfur spray']
30
- }), ["Error: crop_diseases_treatments.csv not found."]
31
-
32
- # --- Load Groq LLM ---
33
- def initialize_llm():
34
- groq_key = os.environ.get('GROQ_API_KEY')
35
- if not groq_key:
36
- print("Warning: GROQ_API_KEY not found in environment variables. The chatbot may not work.")
37
- return ChatGroq(model="llama-3.3-70b-versatile", api_key=groq_key)
38
-
39
- # --- Load Embedding Model ---
40
- def initialize_embedding_model():
41
- return HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")
42
 
43
  # --- Disease Classification ---
44
  def prepare_disease_classifier():
@@ -71,10 +54,7 @@ def classify_disease(image):
71
 
72
  # Process the image
73
  if image is not None:
74
- img_tensor = transform(image).unsqueeze(0)
75
-
76
  # For demonstration, we'll randomly select a class
77
- import random
78
  class_idx = random.randint(0, len(class_names) - 1)
79
  class_name = class_names[class_idx]
80
 
@@ -132,41 +112,102 @@ def find_treatment(crop, disease, df):
132
  "medicine": "Consult a plant pathologist"
133
  }
134
 
135
- # Function to answer questions using Groq
136
- def answer_question_with_groq(question, df, llm):
137
- # Create context from the database
138
- context = ""
139
- for _, row in df.iterrows():
140
- context += f"Crop: {row['Crop']}, Disease: {row['Disease']}, "
141
- context += f"Symptoms: {row['Symptoms']}, Treatment: {row['Treatment']}, "
142
- context += f"Medicine: {row['Medicine/Chemical Control']}\n"
 
 
 
 
143
 
144
- # Prepare the prompt for Groq
145
- prompt = f"""
146
- You are a plant disease expert. Answer the following question about plant diseases and treatments.
147
- Use only the information provided in the context. If you don't know the answer, say so.
148
 
149
- Context:
150
- {context[:4000]} # Limit context size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
- Question: {question}
 
 
 
 
 
 
 
 
 
 
153
 
154
- Answer with the following format:
155
- Crop: [crop name if identified]
156
- Disease: [disease name if identified]
157
- Treatment: [treatment recommendations]
158
- Medicine: [chemical control options]
159
- """
160
 
161
- try:
162
- # Get response from Groq
163
- response = llm.invoke(prompt)
164
- return response.content
165
- except Exception as e:
166
- return f"Error getting response from Groq: {str(e)}\n\nPlease check your API key and try again."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
  # Function to process image uploads
169
- def process_image(image, df, llm):
170
  if image is None:
171
  return "Please upload an image to analyze.", None, None, None, None
172
 
@@ -176,37 +217,20 @@ def process_image(image, df, llm):
176
  # Get treatment information
177
  treatment_info = find_treatment(crop, disease, df)
178
 
179
- # Use Groq to enhance the analysis
180
- image_description = f"Image shows a {crop} plant with possible {disease} disease."
181
- prompt = f"""
182
- You are a plant disease expert. Analyze this plant image description and provide detailed information.
183
-
184
- Image description: {image_description}
185
-
186
- Based on the database information, this appears to be {disease} affecting {crop}.
187
-
188
- Provide a detailed analysis with the following format:
189
- Crop: {crop}
190
- Disease: {disease}
191
- Symptoms: [describe typical symptoms]
192
- Treatment: [provide treatment recommendations]
193
- Medicine: [suggest chemical control options]
194
- """
195
 
196
- try:
197
- # Get enhanced analysis from Groq
198
- groq_analysis = llm.invoke(prompt)
199
- return groq_analysis.content, treatment_info["crop"], treatment_info["disease"], treatment_info["treatment"], treatment_info["medicine"]
200
- except Exception as e:
201
- # Fallback to basic information if Groq fails
202
- return f"Analysis: {crop} affected by {disease}", treatment_info["crop"], treatment_info["disease"], treatment_info["treatment"], treatment_info["medicine"]
203
 
204
  # Main function to set up the Gradio interface
205
  def main():
206
- # Load data and initialize models
207
- df, context_data = load_treatments_data()
208
- llm = initialize_llm()
209
- embed_model = initialize_embedding_model()
210
 
211
  # Create a simplified Gradio interface
212
  with gr.Blocks(title="Plant Disease Assistant") as app:
@@ -244,13 +268,13 @@ def main():
244
 
245
  # Set up event handlers
246
  image_submit.click(
247
- fn=lambda img: process_image(img, df, llm),
248
  inputs=[image_input],
249
  outputs=[analysis_output, crop_output, disease_output, treatment_output, medicine_output]
250
  )
251
 
252
  question_submit.click(
253
- fn=lambda q: (answer_question_with_groq(q, df, llm), "", "", "", ""),
254
  inputs=[question_input],
255
  outputs=[analysis_output, crop_output, disease_output, treatment_output, medicine_output]
256
  )
 
1
  import gradio as gr
2
  import pandas as pd
3
  import os
4
+ import random
5
  from PIL import Image
6
+ import torch
7
  from torchvision import transforms
 
 
8
 
9
  # --- Load CSV Data ---
10
  def load_treatments_data():
11
  try:
12
  context = pd.read_csv('./crop_diseases_treatments.csv')
13
  print("CSV file loaded successfully.")
14
+ return context
 
 
 
 
 
 
15
  except FileNotFoundError:
16
  print("Error: crop_diseases_treatments.csv not found.")
17
  # Create a minimal dataframe for demonstration
18
  return pd.DataFrame({
19
+ 'Crop': ['Tomato', 'Apple', 'Corn', 'Rice', 'Potato'],
20
+ 'Disease': ['Early Blight', 'Apple Scab', 'Common Rust', 'Bacterial Leaf Blight', 'Late Blight'],
21
+ 'Symptoms': ['Yellow spots on leaves', 'Dark scab-like lesions', 'Rust-colored pustules', 'Yellow-orange lesions', 'Dark water-soaked spots'],
22
+ 'Treatment': ['Remove affected leaves', 'Prune affected branches', 'Remove infected plants', 'Drain fields', 'Apply fungicide early'],
23
+ 'Medicine/Chemical Control': ['Copper fungicide', 'Sulfur spray', 'Propiconazole', 'Streptomycin sulfate', 'Chlorothalonil']
24
+ })
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  # --- Disease Classification ---
27
  def prepare_disease_classifier():
 
54
 
55
  # Process the image
56
  if image is not None:
 
 
57
  # For demonstration, we'll randomly select a class
 
58
  class_idx = random.randint(0, len(class_names) - 1)
59
  class_name = class_names[class_idx]
60
 
 
112
  "medicine": "Consult a plant pathologist"
113
  }
114
 
115
+ # Simple function to answer questions based on the database
116
+ def answer_question(question, df):
117
+ question = question.lower()
118
+
119
+ # Look for crop and disease mentions in the question
120
+ crop_match = None
121
+ disease_match = None
122
+
123
+ for crop in df['Crop'].unique():
124
+ if crop.lower() in question:
125
+ crop_match = crop
126
+ break
127
 
128
+ for disease in df['Disease'].unique():
129
+ if disease.lower() in question:
130
+ disease_match = disease
131
+ break
132
 
133
+ # If we found both crop and disease
134
+ if crop_match and disease_match:
135
+ matches = df[(df['Crop'] == crop_match) & (df['Disease'] == disease_match)]
136
+ if not matches.empty:
137
+ match = matches.iloc[0]
138
+ return f"""
139
+ Crop: {match['Crop']}
140
+ Disease: {match['Disease']}
141
+ Symptoms: {match['Symptoms']}
142
+ Treatment: {match['Treatment']}
143
+ Medicine: {match['Medicine/Chemical Control']}
144
+ """
145
+
146
+ # If we found only crop
147
+ elif crop_match:
148
+ matches = df[df['Crop'] == crop_match]
149
+ if not matches.empty:
150
+ response = f"Information about diseases affecting {crop_match}:\n\n"
151
+ for _, row in matches.iterrows():
152
+ response += f"Disease: {row['Disease']}\n"
153
+ response += f"Symptoms: {row['Symptoms']}\n"
154
+ response += f"Treatment: {row['Treatment']}\n"
155
+ response += f"Medicine: {row['Medicine/Chemical Control']}\n\n"
156
+ return response
157
 
158
+ # If we found only disease
159
+ elif disease_match:
160
+ matches = df[df['Disease'] == disease_match]
161
+ if not matches.empty:
162
+ response = f"Information about {disease_match} affecting various crops:\n\n"
163
+ for _, row in matches.iterrows():
164
+ response += f"Crop: {row['Crop']}\n"
165
+ response += f"Symptoms: {row['Symptoms']}\n"
166
+ response += f"Treatment: {row['Treatment']}\n"
167
+ response += f"Medicine: {row['Medicine/Chemical Control']}\n\n"
168
+ return response
169
 
170
+ # General search
171
+ keywords = question.split()
172
+ relevant_rows = []
 
 
 
173
 
174
+ for _, row in df.iterrows():
175
+ score = 0
176
+ for keyword in keywords:
177
+ if len(keyword) < 3: # Skip short words
178
+ continue
179
+ if keyword in str(row['Crop']).lower():
180
+ score += 3
181
+ if keyword in str(row['Disease']).lower():
182
+ score += 5
183
+ if keyword in str(row['Symptoms']).lower():
184
+ score += 2
185
+ if keyword in str(row['Treatment']).lower():
186
+ score += 1
187
+ if keyword in str(row['Medicine/Chemical Control']).lower():
188
+ score += 1
189
+
190
+ if score > 0:
191
+ relevant_rows.append((score, row))
192
+
193
+ if relevant_rows:
194
+ # Sort by relevance score
195
+ relevant_rows.sort(key=lambda x: x[0], reverse=True)
196
+ top_matches = relevant_rows[:3] # Get top 3 matches
197
+
198
+ response = "Here's what I found based on your question:\n\n"
199
+ for _, row in top_matches:
200
+ response += f"Crop: {row['Crop']}\n"
201
+ response += f"Disease: {row['Disease']}\n"
202
+ response += f"Symptoms: {row['Symptoms']}\n"
203
+ response += f"Treatment: {row['Treatment']}\n"
204
+ response += f"Medicine: {row['Medicine/Chemical Control']}\n\n"
205
+ return response
206
+
207
+ return "I couldn't find specific information related to your question in the database. Please try asking about specific crops or diseases."
208
 
209
  # Function to process image uploads
210
+ def process_image(image, df):
211
  if image is None:
212
  return "Please upload an image to analyze.", None, None, None, None
213
 
 
217
  # Get treatment information
218
  treatment_info = find_treatment(crop, disease, df)
219
 
220
+ # Create analysis text
221
+ if disease.lower() == "healthy":
222
+ analysis = f"Good news! This {crop} plant appears to be healthy."
223
+ else:
224
+ analysis = f"Analysis: This {crop} plant appears to be affected by {disease}.\n\n"
225
+ analysis += f"Typical symptoms of {disease} include {treatment_info['symptoms']}.\n\n"
226
+ analysis += f"Recommended treatment: {treatment_info['treatment']}"
 
 
 
 
 
 
 
 
 
227
 
228
+ return analysis, treatment_info["crop"], treatment_info["disease"], treatment_info["treatment"], treatment_info["medicine"]
 
 
 
 
 
 
229
 
230
  # Main function to set up the Gradio interface
231
  def main():
232
+ # Load data
233
+ df = load_treatments_data()
 
 
234
 
235
  # Create a simplified Gradio interface
236
  with gr.Blocks(title="Plant Disease Assistant") as app:
 
268
 
269
  # Set up event handlers
270
  image_submit.click(
271
+ fn=lambda img: process_image(img, df),
272
  inputs=[image_input],
273
  outputs=[analysis_output, crop_output, disease_output, treatment_output, medicine_output]
274
  )
275
 
276
  question_submit.click(
277
+ fn=lambda q: (answer_question(q, df), "", "", "", ""),
278
  inputs=[question_input],
279
  outputs=[analysis_output, crop_output, disease_output, treatment_output, medicine_output]
280
  )