Spaces:
Runtime error
Runtime error
Update app.py
Browse files
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
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
|
| 14 |
# Load model
|
| 15 |
-
model = pipeline("image-classification", model="linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification", top_k=
|
| 16 |
-
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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))
|