karthikmn commited on
Commit
246e482
Β·
verified Β·
1 Parent(s): 92ff8ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -181
app.py CHANGED
@@ -1,185 +1,59 @@
1
- import gradio as gr
2
- import numpy as np
3
- import matplotlib.pyplot as plt
4
- import time
5
- import os
6
- import tempfile
7
- from PIL import Image
8
  from transformers import pipeline
9
- import logging
10
-
11
- # Setup logging
12
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
 
14
  # Load model
15
- model = pipeline("image-classification", model="linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification", top_k=5)
16
-
17
- # Mapping, treatments, and fertilizers
18
- DISEASE_MAPPING = {
19
- "Tomato___Late_blight": "Late Blight",
20
- "Tomato___Early_blight": "Early Blight",
21
- "Tomato___healthy": "Healthy"
22
- }
23
- TREATMENTS = {
24
- "Late Blight": "Apply chlorothalonil or mancozeb fungicides. Remove infected material.",
25
- "Early Blight": "Use copper fungicide and remove lower leaves.",
26
- "Healthy": "No treatment needed."
27
- }
28
- FERTILIZERS = {
29
- "Late Blight": "Low-nitrogen (5-10-10).",
30
- "Early Blight": "Balanced with calcium (10-10-10 + Ca).",
31
- "Healthy": "Standard NPK (10-10-10)."
32
- }
33
-
34
- def preprocess_image(image):
35
- if isinstance(image, np.ndarray):
36
- image = Image.fromarray(image.astype('uint8'), 'RGB')
37
- return image.resize((224, 224), Image.LANCZOS)
38
-
39
- def generate_confidence_plot(preds):
40
- labels = [p['label'] for p in preds]
41
- scores = [p['score'] * 100 for p in preds]
42
- plt.figure(figsize=(8, 5))
43
- bars = plt.barh(labels, scores, color=['#66bb6a' if 'healthy' in l.lower() else '#ef5350' for l in labels])
44
- plt.xlabel("Confidence (%)")
45
- plt.xlim(0, 100)
46
- plt.gca().invert_yaxis()
47
- for bar in bars:
48
- plt.text(bar.get_width() - 5, bar.get_y() + bar.get_height()/2,
49
- f"{bar.get_width():.1f}%", va='center', ha='right', color='white')
50
- path = os.path.join(tempfile.gettempdir(), f"plot_{int(time.time())}.png")
51
- plt.tight_layout()
52
- plt.savefig(path)
53
- plt.close()
54
- return path
55
-
56
- def generate_analysis(disease, confidence):
57
- if disease == "Healthy":
58
- return "🌱 Your plant looks healthy! No signs of disease detected."
59
- if confidence < 0.6:
60
- return f"⚠️ Possible signs of {disease.lower()} detected. Monitor closely."
61
- elif confidence < 0.8:
62
- return f"🟑 Likely {disease.lower()} detected. Preventive treatment advised."
63
- else:
64
- return f"πŸ”΄ Clear signs of {disease.lower()} detected. Treat immediately."
65
-
66
- def predict(image, plant_type, location, format):
67
- processed = preprocess_image(image)
68
- preds = model(processed)
69
- top = preds[0]
70
- disease = DISEASE_MAPPING.get(top['label'], top['label'])
71
- analysis = generate_analysis(disease, top['score'])
72
- treatment = TREATMENTS.get(disease, "Consult expert.")
73
- fertilizer = FERTILIZERS.get(disease, "Use balanced NPK.")
74
- plot_path = generate_confidence_plot(preds)
75
-
76
- table = "| Rank | Disease | Confidence |\n|------|---------|------------|\n"
77
- for i, p in enumerate(preds):
78
- name = DISEASE_MAPPING.get(p['label'], p['label'])
79
- table += f"| {i+1} | {name} | {p['score']*100:.1f}% |\n"
80
-
81
- report = f"""
82
- ### πŸͺ΄ Plant Type: {plant_type}
83
- πŸ“ **Location**: {location or 'Not specified'}
84
- πŸ§ͺ **Diagnosis**: {disease} ({top['score']*100:.1f}%)
85
- πŸ•’ **Time**: {time.strftime('%Y-%m-%d %H:%M:%S')}
86
-
87
- ---
88
-
89
- ### πŸ” AI Analysis
90
- {analysis}
91
-
92
- ### πŸ’Š Treatment Recommendation
93
- {treatment}
94
-
95
- ### 🌱 Fertilizer Suggestion
96
- {fertilizer}
97
-
98
- ---
99
-
100
- ### πŸ“Š Top Predictions
101
- {table}
102
- """
103
- report_file = os.path.join(tempfile.gettempdir(), f"report_{int(time.time())}.txt")
104
- with open(report_file, "w") as f:
105
- f.write(report)
106
-
107
- return report, plot_path, report_file
108
-
109
- # ───────────────────── STYLING ─────────────────────
110
-
111
- css = """
112
- @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap');
113
-
114
- body {
115
- font-family: 'Poppins', sans-serif;
116
- background: linear-gradient(to right, #e6f2e6, #cce0cc);
117
- background-image: url('https://images.unsplash.com/photo-1501004318641-b39e6451bec6?auto=format&fit=crop&w=1500&q=80');
118
- background-size: cover;
119
- background-attachment: fixed;
120
- margin: 0;
121
- padding: 0;
122
- }
123
- .gradio-container {
124
- max-width: 1000px;
125
- margin: 40px auto;
126
- background: rgba(255, 255, 255, 0.92);
127
- padding: 40px;
128
- border-radius: 20px;
129
- box-shadow: 0 8px 32px rgba(0, 50, 0, 0.3);
130
- }
131
- h1, h2 {
132
- color: #2e7d32;
133
- text-align: center;
134
- }
135
- button {
136
- font-weight: 600;
137
- background-color: #4caf50 !important;
138
- color: white !important;
139
- border-radius: 10px !important;
140
- }
141
- button:hover {
142
- background-color: #388e3c !important;
143
- }
144
- textarea, input, select {
145
- border-radius: 10px !important;
146
- padding: 8px;
147
- }
148
- .output-markdown {
149
- background-color: rgba(255,255,255,0.95);
150
- padding: 20px;
151
- border-radius: 15px;
152
- margin-top: 20px;
153
- box-shadow: 0 4px 20px rgba(0,0,0,0.1);
154
- }
155
- """
156
-
157
- # ���──────────────────── UI ─────────────────────
158
-
159
- with gr.Blocks(css=css) as app:
160
- gr.Markdown("# 🌿 Plant Disease Detector")
161
- gr.Markdown("Upload a plant leaf photo to diagnose disease and get treatment + fertilizer advice.")
162
-
163
- with gr.Row():
164
- with gr.Column(scale=1):
165
- image_input = gr.Image(type="numpy", label="πŸ“· Upload Leaf Image")
166
- plant_input = gr.Text(label="🌱 Plant Type", placeholder="e.g., Tomato")
167
- location_input = gr.Text(label="πŸ“ Location", placeholder="e.g., Greenhouse A")
168
- format_input = gr.Radio(["TXT"], label="πŸ“„ Report Format", value="TXT")
169
- submit = gr.Button("πŸ”¬ Analyze")
170
-
171
- with gr.Column(scale=2):
172
- report_output = gr.Markdown(elem_classes=["output-markdown"])
173
- plot_output = gr.Image(label="πŸ“Š Confidence Chart")
174
- file_output = gr.File(label="πŸ“₯ Download Diagnosis")
175
-
176
- submit.click(
177
- fn=predict,
178
- inputs=[image_input, plant_input, location_input, format_input],
179
- outputs=[report_output, plot_output, file_output]
180
- )
181
-
182
- # ───────────────────── RUN ─────────────────────
183
-
184
  if __name__ == "__main__":
185
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
1
  from transformers import pipeline
2
+ from PIL import Image
3
+ import base64
4
+ import io
5
+ import json
6
 
7
  # Load model
8
+ model = pipeline("image-classification", model="linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification", top_k=1)
9
+
10
+ # Load mapping data
11
+ def load_map(file_path):
12
+ with open(file_path, 'r', encoding='utf-8') as f:
13
+ return dict(line.strip().split(":", 1) for line in f if ":" in line)
14
+
15
+ disease_map = load_map("diseases.txt")
16
+ treatment_map = load_map("treatments.txt")
17
+ fertilizer_map = load_map("fertilizers.txt")
18
+
19
+ with open("critical_diseases.txt", "r") as f:
20
+ critical_diseases = set(line.strip() for line in f)
21
+
22
+ def predict_disease(base64_img):
23
+ # Decode base64
24
+ try:
25
+ img_bytes = base64.b64decode(base64_img)
26
+ image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
27
+ except Exception as e:
28
+ return {"error": f"Invalid image: {str(e)}"}
29
+
30
+ # Predict
31
+ try:
32
+ result = model(image)[0]
33
+ label = result["label"]
34
+ confidence = float(result["score"])
35
+ disease = disease_map.get(label, label)
36
+ treatment = treatment_map.get(disease, "Consult an expert for treatment.")
37
+ fertilizer = fertilizer_map.get(disease, "Use a general NPK 10-10-10 fertilizer.")
38
+
39
+ output = {
40
+ "disease_prediction": disease,
41
+ "confidence": round(confidence, 4),
42
+ "suggested_treatment": treatment,
43
+ "fertilizer_recommendation": fertilizer
44
+ }
45
+
46
+ # Alerts (for integration)
47
+ if confidence < 0.6 or disease in critical_diseases:
48
+ output["alert"] = True
49
+
50
+ return output
51
+ except Exception as e:
52
+ return {"error": f"Prediction failed: {str(e)}"}
53
+
54
+ # Test hook
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  if __name__ == "__main__":
56
+ with open("example_image.b64", "r") as f:
57
+ base64_img = f.read()
58
+ response = predict_disease(base64_img)
59
+ print(json.dumps(response, indent=2))