Spaces:
Sleeping
Sleeping
Initial commit from automated deployment script
Browse files- README.md +73 -13
- app.py +232 -0
- requirements.txt +8 -0
README.md
CHANGED
|
@@ -1,13 +1,73 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom: green
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version:
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Plant Disease Assistant
|
| 3 |
+
emoji: 🌱
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: yellow
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.0.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
short_description: Diagnose 22 crop diseases from a leaf. DINOv2-L on MI300X.
|
| 12 |
+
tags:
|
| 13 |
+
- plant-disease
|
| 14 |
+
- agriculture
|
| 15 |
+
- dinov2
|
| 16 |
+
- amd
|
| 17 |
+
- mi300x
|
| 18 |
+
- rocm
|
| 19 |
+
- image-classification
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
# 🌱 Plant Disease Assistant
|
| 23 |
+
|
| 24 |
+
Snap a leaf, name the disease, get a fix.
|
| 25 |
+
|
| 26 |
+
Upload a photo of a plant leaf and this Space will identify which of **22 crop diseases** it has, rate the model's confidence, and return a structured treatment + prevention guide.
|
| 27 |
+
|
| 28 |
+
## What's under the hood
|
| 29 |
+
|
| 30 |
+
| Component | Details |
|
| 31 |
+
|---|---|
|
| 32 |
+
| **Classifier** | DINOv2-Large (304M params, ViT-L/14), fine-tuned with a linear head |
|
| 33 |
+
| **Accuracy** | 97.06% top-1, 0.9713 macro F1 on the held-out test split |
|
| 34 |
+
| **Dataset** | [CCMT Crop Pest and Disease Detection](https://www.kaggle.com/datasets) — cashew, cassava, maize, tomato |
|
| 35 |
+
| **Hardware** | Fine-tuned on a single AMD Instinct **MI300X** (192 GB HBM3) via the AMD Developer Cloud |
|
| 36 |
+
| **Framework** | PyTorch 2.x + ROCm, [timm](https://github.com/huggingface/pytorch-image-models) |
|
| 37 |
+
| **Knowledge base** | Hand-curated treatment, prevention, and severity notes per class |
|
| 38 |
+
|
| 39 |
+
The classifier runs on CPU here for accessibility — inference takes a few seconds per image. The original training run used ROCm on MI300X.
|
| 40 |
+
|
| 41 |
+
## Crops & diseases covered
|
| 42 |
+
|
| 43 |
+
- **Cashew** — anthracnose, gumosis, leaf miner, red rust, healthy
|
| 44 |
+
- **Cassava** — bacterial blight, brown spot, green mite, mosaic, healthy
|
| 45 |
+
- **Maize** — fall armyworm, grasshopper, leaf beetle, leaf blight, leaf spot, streak virus, healthy
|
| 46 |
+
- **Tomato** — leaf blight, leaf curl, septoria leaf spot, verticilium wilt, healthy
|
| 47 |
+
|
| 48 |
+
## How it was built
|
| 49 |
+
|
| 50 |
+
This is **Track 2** of a multi-track entry in the lablab.ai AMD Developer Hackathon:
|
| 51 |
+
|
| 52 |
+
- **Track 2** — Fine-tune DINOv2-L on CCMT for plant disease classification (this Space)
|
| 53 |
+
- **Track 3** — Fine-tune Llama 3.2 11B Vision (LoRA) on the same data for conversational diagnosis ([adapter on HF](https://huggingface.co/iamcode6/llama32-vision-ccmt-mi300x))
|
| 54 |
+
- **Build in Public** — Documented the journey end-to-end on social
|
| 55 |
+
|
| 56 |
+
Both tracks were trained on the same MI300X droplet, demonstrating that a single AMD GPU can comfortably handle both a 304M-param classifier and an 11B-param vision-language model in the same workflow.
|
| 57 |
+
|
| 58 |
+
## Limitations
|
| 59 |
+
|
| 60 |
+
- Trained on a single dataset (CCMT) — performance on field photos with very different lighting, angles, or unseen crops will degrade.
|
| 61 |
+
- The treatment guidance is informational only and **not a substitute for advice from a qualified agronomist or extension officer**.
|
| 62 |
+
- CPU inference is intentionally slow (~5–10s/image). The original GPU pipeline runs in milliseconds.
|
| 63 |
+
|
| 64 |
+
## License
|
| 65 |
+
|
| 66 |
+
Apache 2.0. Model weights and code are open. CCMT dataset licensing applies to the training data only.
|
| 67 |
+
|
| 68 |
+
## Acknowledgements
|
| 69 |
+
|
| 70 |
+
- AMD for the Developer Cloud credits and MI300X access
|
| 71 |
+
- Meta for [DINOv2](https://github.com/facebookresearch/dinov2)
|
| 72 |
+
- The CCMT dataset authors
|
| 73 |
+
- lablab.ai for organizing the hackathon
|
app.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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""Plant Disease Assistant — Hugging Face Space (CPU, DINOv2-only).
|
| 2 |
+
|
| 3 |
+
Loads the DINOv2-L checkpoint from a HF model repo at startup, then runs
|
| 4 |
+
classification + template-based responses from a bundled knowledge file.
|
| 5 |
+
|
| 6 |
+
Configurable via environment variables:
|
| 7 |
+
DINOV2_REPO HF model repo containing best.pt and splits.json
|
| 8 |
+
(default: iamcode6/dinov2-l-ccmt-mi300x)
|
| 9 |
+
DINOV2_CKPT Filename of the checkpoint inside the repo
|
| 10 |
+
(default: best.pt)
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import gradio as gr
|
| 19 |
+
import numpy as np
|
| 20 |
+
import timm
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from huggingface_hub import hf_hub_download
|
| 24 |
+
from PIL import Image
|
| 25 |
+
from timm.data import create_transform
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
HERE = Path(__file__).parent
|
| 29 |
+
KNOWLEDGE_PATH = HERE / "treatment_knowledge.json"
|
| 30 |
+
SPLITS_PATH = HERE / "splits.json"
|
| 31 |
+
|
| 32 |
+
DINOV2_REPO = os.environ.get("DINOV2_REPO", "iamcode6/dinov2-l-ccmt-mi300x")
|
| 33 |
+
DINOV2_CKPT = os.environ.get("DINOV2_CKPT", "best.pt")
|
| 34 |
+
DEVICE = "cpu"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class PlantClassifier:
|
| 38 |
+
def __init__(self, checkpoint_path: Path, splits_path: Path):
|
| 39 |
+
self.device = torch.device(DEVICE)
|
| 40 |
+
|
| 41 |
+
splits = json.loads(splits_path.read_text())
|
| 42 |
+
self.idx_to_class = {v: k for k, v in splits["class_to_idx"].items()}
|
| 43 |
+
self.class_names = [self.idx_to_class[i] for i in range(len(self.idx_to_class))]
|
| 44 |
+
self.num_classes = len(self.class_names)
|
| 45 |
+
|
| 46 |
+
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 47 |
+
if isinstance(ckpt, dict) and "state_dict" in ckpt:
|
| 48 |
+
state_dict = ckpt["state_dict"]
|
| 49 |
+
cfg = ckpt.get("cfg", {})
|
| 50 |
+
else:
|
| 51 |
+
state_dict = ckpt
|
| 52 |
+
cfg = {}
|
| 53 |
+
state_dict = {k.replace("_orig_mod.", "", 1): v for k, v in state_dict.items()}
|
| 54 |
+
|
| 55 |
+
model_name = cfg.get("model", {}).get("name", "vit_large_patch14_dinov2.lvd142m")
|
| 56 |
+
img_size = cfg.get("model", {}).get("img_size", 224)
|
| 57 |
+
|
| 58 |
+
self.model = timm.create_model(
|
| 59 |
+
model_name, pretrained=False,
|
| 60 |
+
num_classes=self.num_classes, img_size=img_size,
|
| 61 |
+
)
|
| 62 |
+
self.model.load_state_dict(state_dict)
|
| 63 |
+
self.model.to(self.device).eval()
|
| 64 |
+
|
| 65 |
+
self.transform = create_transform(
|
| 66 |
+
input_size=img_size, is_training=False,
|
| 67 |
+
mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225),
|
| 68 |
+
interpolation="bicubic", crop_pct=0.95,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
@torch.no_grad()
|
| 72 |
+
def predict(self, image: Image.Image, top_k: int = 3) -> list[dict]:
|
| 73 |
+
x = self.transform(image).unsqueeze(0).to(self.device)
|
| 74 |
+
logits = self.model(x)
|
| 75 |
+
probs = F.softmax(logits, dim=-1).squeeze(0).float().cpu().numpy()
|
| 76 |
+
|
| 77 |
+
top_indices = np.argsort(probs)[::-1][:top_k]
|
| 78 |
+
return [
|
| 79 |
+
{"class": self.class_names[i], "confidence": float(probs[i]), "index": int(i)}
|
| 80 |
+
for i in top_indices
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class KnowledgeResponder:
|
| 85 |
+
def __init__(self, path: Path):
|
| 86 |
+
self.knowledge = json.loads(path.read_text())
|
| 87 |
+
|
| 88 |
+
def format_label(self, label: str) -> str:
|
| 89 |
+
return label.replace("_", " ").title()
|
| 90 |
+
|
| 91 |
+
def respond(self, predictions: list[dict]) -> str:
|
| 92 |
+
top = predictions[0]
|
| 93 |
+
label = top["class"]
|
| 94 |
+
confidence = top["confidence"]
|
| 95 |
+
|
| 96 |
+
if label not in self.knowledge:
|
| 97 |
+
return (
|
| 98 |
+
f"**Prediction:** {self.format_label(label)} "
|
| 99 |
+
f"(confidence: {confidence:.1%})\n\n"
|
| 100 |
+
"No detailed information available for this condition."
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
k = self.knowledge[label]
|
| 104 |
+
is_healthy = k["disease"] == "Healthy"
|
| 105 |
+
|
| 106 |
+
lines = []
|
| 107 |
+
if is_healthy:
|
| 108 |
+
lines.append(f"## {k['crop']} — Healthy")
|
| 109 |
+
lines.append(f"**Confidence:** {confidence:.1%}\n")
|
| 110 |
+
lines.append(f"{k['symptoms']}")
|
| 111 |
+
lines.append("\nKeep monitoring regularly and continue your current care routine.")
|
| 112 |
+
else:
|
| 113 |
+
lines.append(f"## {k['crop']} — {k['disease']}")
|
| 114 |
+
lines.append(f"**Confidence:** {confidence:.1%}\n")
|
| 115 |
+
if k.get("pathogen"):
|
| 116 |
+
lines.append(f"**Pathogen:** *{k['pathogen']}*\n")
|
| 117 |
+
lines.append("### Symptoms")
|
| 118 |
+
lines.append(f"{k['symptoms']}\n")
|
| 119 |
+
lines.append("### Severity Guide")
|
| 120 |
+
for level, desc in k["severity_cues"].items():
|
| 121 |
+
lines.append(f"- **{level.title()}:** {desc}")
|
| 122 |
+
lines.append("")
|
| 123 |
+
lines.append("### Treatment")
|
| 124 |
+
lines.append(f"{k['treatment']}\n")
|
| 125 |
+
lines.append("### Prevention")
|
| 126 |
+
lines.append(f"{k['prevention']}")
|
| 127 |
+
|
| 128 |
+
if len(predictions) > 1:
|
| 129 |
+
lines.append("\n---\n### Other Possibilities")
|
| 130 |
+
for p in predictions[1:]:
|
| 131 |
+
if p["confidence"] > 0.05:
|
| 132 |
+
lines.append(f"- {self.format_label(p['class'])} ({p['confidence']:.1%})")
|
| 133 |
+
|
| 134 |
+
return "\n".join(lines)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
print(f"[app] Downloading DINOv2-L checkpoint from {DINOV2_REPO}...")
|
| 138 |
+
checkpoint_path = Path(hf_hub_download(repo_id=DINOV2_REPO, filename=DINOV2_CKPT))
|
| 139 |
+
|
| 140 |
+
print("[app] Loading classifier on CPU (~30s)...")
|
| 141 |
+
classifier = PlantClassifier(checkpoint_path, SPLITS_PATH)
|
| 142 |
+
print(f"[app] Loaded {classifier.num_classes} classes")
|
| 143 |
+
|
| 144 |
+
knowledge = KnowledgeResponder(KNOWLEDGE_PATH)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def diagnose(image: Image.Image | None):
|
| 148 |
+
if image is None:
|
| 149 |
+
return "Please upload an image.", ""
|
| 150 |
+
|
| 151 |
+
image = image.convert("RGB")
|
| 152 |
+
predictions = classifier.predict(image, top_k=3)
|
| 153 |
+
|
| 154 |
+
table = "**DINOv2-L Classification (97% accuracy)**\n\n"
|
| 155 |
+
table += "| Rank | Disease | Confidence |\n"
|
| 156 |
+
table += "|------|---------|------------|\n"
|
| 157 |
+
for i, p in enumerate(predictions):
|
| 158 |
+
marker = " ←" if i == 0 else ""
|
| 159 |
+
table += (
|
| 160 |
+
f"| {i+1} | {knowledge.format_label(p['class'])} | "
|
| 161 |
+
f"{p['confidence']:.1%}{marker} |\n"
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
return table, knowledge.respond(predictions)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
CUSTOM_CSS = """
|
| 168 |
+
.prose, .prose *, [class*="markdown"], [class*="markdown"] * {
|
| 169 |
+
color: #1a1a1a !important;
|
| 170 |
+
opacity: 1 !important;
|
| 171 |
+
}
|
| 172 |
+
.prose strong, .prose h1, .prose h2, .prose h3 {
|
| 173 |
+
color: #000 !important;
|
| 174 |
+
font-weight: 700 !important;
|
| 175 |
+
}
|
| 176 |
+
.dark .prose, .dark .prose *,
|
| 177 |
+
.dark [class*="markdown"], .dark [class*="markdown"] * {
|
| 178 |
+
color: #f5f5f5 !important;
|
| 179 |
+
}
|
| 180 |
+
.dark .prose strong, .dark .prose h1, .dark .prose h2, .dark .prose h3 {
|
| 181 |
+
color: #ffffff !important;
|
| 182 |
+
}
|
| 183 |
+
.prose table { border-collapse: collapse; }
|
| 184 |
+
.prose th, .prose td { padding: 6px 10px; border: 1px solid #888; }
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
with gr.Blocks(title="Plant Disease Assistant", css=CUSTOM_CSS) as app:
|
| 188 |
+
gr.Markdown(
|
| 189 |
+
"# 🌱 Plant Disease Assistant\n"
|
| 190 |
+
"Upload a photo of a plant leaf to get an instant diagnosis, "
|
| 191 |
+
"severity assessment, and treatment recommendations.\n\n"
|
| 192 |
+
"*DINOv2-Large fine-tuned on AMD Instinct MI300X (ROCm) — "
|
| 193 |
+
"97.06% accuracy on the CCMT crop disease dataset.*"
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
with gr.Row():
|
| 197 |
+
with gr.Column(scale=1):
|
| 198 |
+
image_input = gr.Image(type="pil", label="Upload a plant leaf photo")
|
| 199 |
+
diagnose_btn = gr.Button("Diagnose", variant="primary", size="lg")
|
| 200 |
+
|
| 201 |
+
example_paths = sorted(str(p) for p in (HERE / "examples").glob("*.jpg"))
|
| 202 |
+
if example_paths:
|
| 203 |
+
gr.Examples(
|
| 204 |
+
examples=[[p] for p in example_paths],
|
| 205 |
+
inputs=image_input,
|
| 206 |
+
label="Or try one of these (click a thumbnail)",
|
| 207 |
+
examples_per_page=11,
|
| 208 |
+
)
|
| 209 |
+
with gr.Column(scale=2):
|
| 210 |
+
classification_output = gr.Markdown()
|
| 211 |
+
response_output = gr.Markdown()
|
| 212 |
+
|
| 213 |
+
diagnose_btn.click(
|
| 214 |
+
fn=diagnose, inputs=image_input,
|
| 215 |
+
outputs=[classification_output, response_output],
|
| 216 |
+
)
|
| 217 |
+
image_input.change(
|
| 218 |
+
fn=diagnose, inputs=image_input,
|
| 219 |
+
outputs=[classification_output, response_output],
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
gr.Markdown(
|
| 223 |
+
"---\n"
|
| 224 |
+
"**Model:** DINOv2-Large (304M params) — 97.06% accuracy, 0.9713 macro F1\n\n"
|
| 225 |
+
"**Hardware:** Fine-tuned on AMD Instinct MI300X (192 GB HBM3) via AMD Developer Cloud\n\n"
|
| 226 |
+
"**Dataset:** CCMT Crop Pest and Disease Detection — 22 classes across cashew, cassava, maize, and tomato\n\n"
|
| 227 |
+
"*Built for the lablab.ai AMD Developer Hackathon*"
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
app.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=5.0,<6
|
| 2 |
+
torch>=2.2
|
| 3 |
+
timm>=1.0.11
|
| 4 |
+
huggingface_hub>=0.25,<0.27
|
| 5 |
+
pydantic>=2.6,<2.11
|
| 6 |
+
numpy
|
| 7 |
+
Pillow
|
| 8 |
+
audioop-lts; python_version >= "3.13"
|