abdullahzunorain
commited on
Commit
β’
e9ead59
1
Parent(s):
39a22df
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
from transformers import AutoModelForImageClassification, AutoFeatureExtractor
|
5 |
+
from groq import Groq
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
import os
|
8 |
+
|
9 |
+
# Load environment variables from the .env file
|
10 |
+
load_dotenv()
|
11 |
+
|
12 |
+
# Securely get the GROQ API key from environment variables
|
13 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
14 |
+
if not groq_api_key:
|
15 |
+
raise ValueError("GROQ_API_KEY environment variable not set.")
|
16 |
+
|
17 |
+
# Initialize the client with the API key
|
18 |
+
client = Groq(api_key=groq_api_key)
|
19 |
+
|
20 |
+
# Expanded dictionary with treatments for various diseases
|
21 |
+
disease_treatments = {
|
22 |
+
"Grape with Black Rot": "Prune affected areas, avoid water on leaves, use fungicide if severe.",
|
23 |
+
"Potato with Early Blight": "Apply fungicides, avoid overhead watering, rotate crops yearly.",
|
24 |
+
"Tomato with Early Blight": "Remove infected leaves, use copper-based fungicide, maintain good airflow.",
|
25 |
+
"Apple with Scab": "Remove fallen leaves, prune trees, apply fungicide in early spring.",
|
26 |
+
"Wheat with Leaf Rust": "Apply resistant varieties, use fungicides, remove weeds.",
|
27 |
+
"Cucumber with Downy Mildew": "Use resistant varieties, ensure good air circulation, apply fungicide.",
|
28 |
+
"Rose with Powdery Mildew": "Use sulfur or potassium bicarbonate sprays, prune affected areas, avoid overhead watering.",
|
29 |
+
"Strawberry with Gray Mold": "Remove infected fruits, improve ventilation, avoid wetting the fruit when watering.",
|
30 |
+
"Peach with Leaf Curl": "Apply a fungicide in late fall or early spring, remove affected leaves.",
|
31 |
+
"Banana with Panama Disease": "Use disease-resistant varieties, ensure soil drainage, avoid overwatering.",
|
32 |
+
"Tomato with Septoria Leaf Spot": "Use resistant varieties, remove infected leaves, apply fungicide.",
|
33 |
+
"Corn with Smut": "Remove infected ears, use disease-free seed, rotate crops.",
|
34 |
+
"Carrot with Root Rot": "Ensure well-draining soil, avoid excessive watering, use crop rotation.",
|
35 |
+
"Onion with Downy Mildew": "Use fungicides, ensure adequate spacing, avoid overhead watering.",
|
36 |
+
"Potato with Late Blight": "Apply copper-based fungicides, remove affected foliage, practice crop rotation.",
|
37 |
+
"Citrus with Greening Disease": "Remove infected trees, control leafhopper population, plant disease-free trees.",
|
38 |
+
"Lettuce with Downy Mildew": "Ensure good air circulation, avoid overhead watering, apply fungicides.",
|
39 |
+
"Pepper with Bacterial Spot": "Use resistant varieties, apply copper-based bactericides, practice crop rotation.",
|
40 |
+
"Eggplant with Verticillium Wilt": "Use resistant varieties, solarize soil before planting, avoid soil disturbance.",
|
41 |
+
"Cotton with Boll Rot": "Improve drainage, remove infected bolls, apply fungicides if necessary.",
|
42 |
+
"Soybean with Soybean Rust": "Use fungicides, rotate crops, use resistant varieties if available.",
|
43 |
+
"Rice with Sheath Blight": "Reduce nitrogen application, maintain proper water levels, apply fungicides.",
|
44 |
+
"Sunflower with Downy Mildew": "Use resistant varieties, avoid waterlogging, apply fungicides.",
|
45 |
+
"Barley with Net Blotch": "Use resistant varieties, remove crop residues, apply fungicides.",
|
46 |
+
"Oat with Crown Rust": "Use resistant varieties, apply fungicides, avoid high nitrogen levels.",
|
47 |
+
"Sugarcane with Red Rot": "Use disease-free cuttings, control weeds, apply fungicides if necessary.",
|
48 |
+
"Pine with Pine Wilt": "Remove and destroy infected trees, control beetle population, avoid planting susceptible species.",
|
49 |
+
"Avocado with Anthracnose": "Prune infected branches, use copper-based fungicides, avoid wet foliage.",
|
50 |
+
"Papaya with Papaya Ringspot Virus": "Use virus-resistant varieties, remove infected plants, control aphid population.",
|
51 |
+
"Mango with Powdery Mildew": "Use sulfur-based fungicides, remove affected parts, avoid overhead watering.",
|
52 |
+
"Peanut with Leaf Spot": "Use resistant varieties, apply fungicides, rotate crops to reduce infection risk.",
|
53 |
+
"Chili with Anthracnose": "Apply copper fungicides, remove infected fruits, avoid overhead irrigation.",
|
54 |
+
"Garlic with White Rot": "Remove infected plants, improve soil drainage, practice crop rotation."
|
55 |
+
}
|
56 |
+
|
57 |
+
# Streamlit title and description
|
58 |
+
st.title("πΏ Plant Disease Detection πΏ")
|
59 |
+
st.write("Upload an image of a plant leaf, and the app will detect the disease and suggest a treatment.")
|
60 |
+
|
61 |
+
# File upload option
|
62 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp"])
|
63 |
+
|
64 |
+
if uploaded_file is not None:
|
65 |
+
# Open the image using PIL and display it
|
66 |
+
image = Image.open(uploaded_file)
|
67 |
+
image = image.convert("RGB")
|
68 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
69 |
+
|
70 |
+
# Initialize the feature extractor and model
|
71 |
+
extractor = AutoFeatureExtractor.from_pretrained("linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification")
|
72 |
+
model = AutoModelForImageClassification.from_pretrained("linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification")
|
73 |
+
|
74 |
+
# Preprocess the image
|
75 |
+
inputs = extractor(images=image, return_tensors="pt")
|
76 |
+
|
77 |
+
# Get the model's raw prediction (logits)
|
78 |
+
outputs = model(**inputs)
|
79 |
+
logits = outputs.logits
|
80 |
+
|
81 |
+
# Temperature scaling for logits (lowering temperature to adjust confidence)
|
82 |
+
temperature = 0.5
|
83 |
+
logits = logits / temperature
|
84 |
+
|
85 |
+
# Convert logits to probabilities using softmax
|
86 |
+
softmax = torch.nn.Softmax(dim=1)
|
87 |
+
probabilities = softmax(logits)
|
88 |
+
|
89 |
+
# Get the top prediction
|
90 |
+
top_k = 1
|
91 |
+
top_probs, top_indices = torch.topk(probabilities, top_k, dim=1)
|
92 |
+
top_probs = top_probs[0].tolist()
|
93 |
+
top_indices = top_indices[0].tolist()
|
94 |
+
|
95 |
+
# Define a confidence threshold
|
96 |
+
confidence_threshold = 0.7
|
97 |
+
class_labels = model.config.id2label
|
98 |
+
predicted_disease = "Unknown Disease"
|
99 |
+
predicted_confidence = top_probs[0]
|
100 |
+
|
101 |
+
# Handle low-confidence predictions
|
102 |
+
if predicted_confidence >= confidence_threshold:
|
103 |
+
predicted_disease = class_labels.get(top_indices[0], "Unknown Disease")
|
104 |
+
else:
|
105 |
+
predicted_disease = "Unknown Disease"
|
106 |
+
st.warning("The model could not confidently identify a disease. Please try again with a clearer image.")
|
107 |
+
|
108 |
+
# Fetch treatment from the dictionary
|
109 |
+
treatment = disease_treatments.get(predicted_disease, "No treatment information available.")
|
110 |
+
|
111 |
+
# Display prediction and treatment
|
112 |
+
st.write(f"**Predicted Disease:** {predicted_disease}")
|
113 |
+
st.write(f"**Confidence Level:** {predicted_confidence:.2f}")
|
114 |
+
|
115 |
+
|
116 |
+
# Generate detailed report (using prompts)
|
117 |
+
symptoms = "leaf discoloration, spots, mold, wilting" # This can be dynamically generated based on the image features
|
118 |
+
diagnosis_prompt = f"Identify the disease or pest affecting a plant with the following symptoms: {symptoms}."
|
119 |
+
treatment_prompt = f"Suggest treatments for a plant disease with symptoms like {symptoms}. Include organic and chemical treatment options if available."
|
120 |
+
preventive_prompt = f"Provide preventive measures for plant diseases with symptoms similar to {symptoms}."
|
121 |
+
|
122 |
+
# Combine the prompts into the chat context
|
123 |
+
chat_context = f"""
|
124 |
+
### π± Plant Disease Diagnosis Report π±
|
125 |
+
#### π Predicted Disease
|
126 |
+
- **Disease**: {predicted_disease}
|
127 |
+
- **Confidence Level**: {predicted_confidence:.2f}
|
128 |
+
#### π Disease Diagnosis and Symptoms
|
129 |
+
- **Diagnosis**: {diagnosis_prompt}
|
130 |
+
#### π Treatment Recommendations
|
131 |
+
- **Treatment**: {treatment_prompt}
|
132 |
+
#### π‘οΈ Preventive Measures
|
133 |
+
- **Prevention**: {preventive_prompt}
|
134 |
+
#### π Conclusion
|
135 |
+
- **Next Steps**: Consult a local expert for further advice.
|
136 |
+
"""
|
137 |
+
|
138 |
+
# Generate report using Groq (or any other service)
|
139 |
+
try:
|
140 |
+
chat_completion = client.chat.completions.create(
|
141 |
+
messages=[
|
142 |
+
{
|
143 |
+
"role": "system",
|
144 |
+
"content": (
|
145 |
+
"You are a plant disease analysis assistant. Your task is to provide a comprehensive, actionable diagnosis report."
|
146 |
+
"The report should include the predicted disease, its symptoms, recommended treatments, and prevention tips. "
|
147 |
+
|
148 |
+
"Ensure the report is actionable and easy to understand for non-experts in agriculture."
|
149 |
+
)
|
150 |
+
},
|
151 |
+
{
|
152 |
+
"role": "user",
|
153 |
+
"content": chat_context
|
154 |
+
}
|
155 |
+
],
|
156 |
+
model="mixtral-8x7b-32768", # Adjust this to the model you're using
|
157 |
+
temperature=0.7, # Adjust to balance creativity and precision
|
158 |
+
max_tokens=5000 # Limit to ensure the output is not cut off
|
159 |
+
)
|
160 |
+
|
161 |
+
# Display the generated report in the Streamlit app
|
162 |
+
st.markdown("---")
|
163 |
+
# Display the full HTML report generated by Groq
|
164 |
+
st.markdown(chat_completion.choices[0].message.content, unsafe_allow_html=True)
|
165 |
+
|
166 |
+
except Exception as e:
|
167 |
+
# If there's an error with the Groq API call, display an error message
|
168 |
+
st.error(f"Error generating report: {str(e)}")
|