2001muhammadumair commited on
Commit
1bb94c4
ยท
verified ยท
1 Parent(s): cd2e03c

Create app.py

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