Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import pipeline
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
# Initialize the plant disease classification pipeline
|
6 |
+
# You can replace the model with any fine-tuned plant disease model hosted on Hugging Face
|
7 |
+
plant_disease_classifier = pipeline(
|
8 |
+
task="image-classification",
|
9 |
+
model="nielsr/plant-disease-model",
|
10 |
+
top_k=3 # return top 3 predictions
|
11 |
+
)
|
12 |
+
|
13 |
+
def diagnose_plant_health(image: Image.Image):
|
14 |
+
"""
|
15 |
+
Takes a PIL Image of a plant leaf and returns:
|
16 |
+
- Top predicted disease label
|
17 |
+
- Confidence score
|
18 |
+
- Care advice based on the label
|
19 |
+
"""
|
20 |
+
# Run the image through the classification pipeline
|
21 |
+
results = plant_disease_classifier(image)
|
22 |
+
|
23 |
+
# Format top-3 predictions
|
24 |
+
predictions = []
|
25 |
+
for res in results:
|
26 |
+
label = res['label']
|
27 |
+
score = res['score']
|
28 |
+
predictions.append(f"{label} ({score*100:.1f}%)")
|
29 |
+
|
30 |
+
# Determine advice based on the top prediction
|
31 |
+
top_label = results[0]['label'].lower()
|
32 |
+
if "healthy" in top_label:
|
33 |
+
advice = "Your plant looks healthy! Maintain regular watering and adequate sunlight."
|
34 |
+
else:
|
35 |
+
advice = (
|
36 |
+
f"Detected symptom: {results[0]['label']}. "
|
37 |
+
"Consider the following care steps:\n"
|
38 |
+
"1. Isolate the plant to prevent spread.\n"
|
39 |
+
"2. Prune affected areas with sterilized tools.\n"
|
40 |
+
"3. Apply an appropriate fungicide or treatment."
|
41 |
+
)
|
42 |
+
|
43 |
+
return "\n".join(predictions), advice
|
44 |
+
|
45 |
+
# Building the Gradio interface
|
46 |
+
iface = gr.Interface(
|
47 |
+
fn=diagnose_plant_health,
|
48 |
+
inputs=gr.Image(type="pil", label="Upload Plant Leaf Image"),
|
49 |
+
outputs=[
|
50 |
+
gr.Textbox(label="Predicted Diseases (Top 3)"),
|
51 |
+
gr.Textbox(label="Care Advice")
|
52 |
+
],
|
53 |
+
title="Home Plant Health Monitor",
|
54 |
+
description=(
|
55 |
+
"Upload a photo of your plant's leaf to diagnose diseases and receive care recommendations. "
|
56 |
+
"This app uses a fine-tuned image-classification model on common plant diseases."
|
57 |
+
),
|
58 |
+
examples=[
|
59 |
+
["example_images/leaf_healthy.jpg"],
|
60 |
+
["example_images/leaf_spot.jpg"]
|
61 |
+
],
|
62 |
+
allow_flagging="never"
|
63 |
+
)
|
64 |
+
|
65 |
+
if __name__ == "__main__":
|
66 |
+
iface.launch(server_name="0.0.0.0", server_port=7860)
|