File size: 11,514 Bytes
2620364
 
 
 
f6e5106
2620364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aa2ea0
 
2620364
 
 
 
 
 
 
 
 
 
 
 
 
f6e5106
2620364
 
 
 
f6e5106
2620364
f6e5106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2620364
 
 
 
 
 
f6e5106
2620364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import io
import json
import os
import secrets
from contextlib import asynccontextmanager

from fastapi import FastAPI, File, Header, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from starlette.concurrency import run_in_threadpool
from PIL import Image, ImageOps, UnidentifiedImageError
import torch
from transformers import CLIPModel, CLIPProcessor, pipeline

from recommendations import RECOMMENDATIONS
from storage import save_scan

# 8 classes (7 conditions + healthy). Chosen over 10- and 14-class models for accuracy on real photos.
DISEASE_MODEL = "cvmil/dinov2-base_rice-leaf-disease-augmented_fft"
# CLIP L/14: on our test set it got 28/28 rice vs not-rice right; base B/32 got 26/28. ~0.6 s per photo on CPU.
GATE_MODEL = "openai/clip-vit-large-patch14"
# (CLIP prompt, name shown to the user, is rice). Look-alike crops must be listed, otherwise any
# grass-like plant wins "rice" by default. Rice wins only if a rice prompt is the single best match.
GATE_LABELS = [
    ("rice plant leaves", "rice leaves", True),
    ("a close-up of a diseased rice leaf with spots or lesions", "a diseased rice leaf", True),
    ("rice plants growing in a paddy field", "a rice paddy", True),
    ("young rice seedlings", "rice seedlings", True),
    ("a rice panicle with grains on the plant", "a rice panicle", True),
    ("a corn plant", "a corn (maize) plant", False),
    ("a maize leaf", "a corn (maize) leaf", False),
    ("sugarcane stalks", "sugarcane", False),
    ("a wheat field", "wheat", False),
    ("sorghum plants", "sorghum", False),
    ("a grass lawn", "grass", False),
    ("weeds", "weeds", False),
    ("bamboo leaves", "bamboo", False),
    ("a banana plant leaf", "a banana leaf", False),
    ("a coconut palm tree", "a coconut palm", False),
    ("a vegetable garden plant", "a vegetable plant", False),
    ("a potted houseplant", "a houseplant", False),
    ("a tree", "a tree", False),
    ("a flower", "a flower", False),
    ("fruits", "fruit", False),
    ("a bowl of cooked rice", "rice grains or cooked rice (food)", False),
    ("uncooked rice grains", "rice grains or cooked rice (food)", False),
    ("a plate of food", "food", False),
    ("a selfie of a person's face", "a person (selfie)", False),
    ("a group of people", "people", False),
    ("a person's hand", "a hand", False),
    ("a dog", "a dog", False),
    ("a cat", "a cat", False),
    ("a bird", "a bird", False),
    ("a chicken", "a chicken", False),
    ("a carabao or water buffalo", "a carabao (water buffalo)", False),
    ("a cow or goat", "livestock", False),
    ("insects or bugs", "insects", False),
    ("a car or motorcycle", "a vehicle", False),
    ("a house or building", "a building", False),
    ("a room interior with furniture", "a room", False),
    ("a phone screenshot or computer screen", "a screenshot or screen", False),
    ("a document or page of printed text", "a document", False),
    ("a cartoon, drawing or logo", "a drawing or graphic", False),
    ("a landscape with sky and mountains", "a landscape", False),
    ("an everyday object", "an object", False),
    ("a blurry or very dark photo", "a blurry or dark photo", False),
]
# Fallback vocabulary for naming rejected photos the curated list doesn't cover (airplane, laptop, ...).
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "imagenet_labels.json"), encoding="utf-8") as f:
    NAME_VOCAB = list(dict.fromkeys(json.load(f)))
CURATED_NAME_MIN = 0.5  # below this, the curated label is a guess and the broad vocabulary names it better
# On test photos, leaf close-ups scored 86-100% and wide field shots 42-60%, so below this we flag the result.
CONFIDENT_MIN = 0.7
# The disease model was trained on single-leaf close-ups; paddy, seedling and panicle shots get a retake tip.
CLOSE_UP_NAMES = {"rice leaves", "a diseased rice leaf"}
MAX_BYTES = 10 * 1024 * 1024

# Load on CPU without automatic accelerator discovery before ZeroGPU forks a worker.
disease_clf = pipeline("image-classification", model=DISEASE_MODEL, device="cpu")
gate_model = CLIPModel.from_pretrained(GATE_MODEL).eval()
gate_processor = CLIPProcessor.from_pretrained(GATE_MODEL)


def _unit(features) -> torch.Tensor:
    # transformers 5 returns an output object; the projected embedding is its pooler_output.
    features = getattr(features, "pooler_output", features)
    return features / features.norm(dim=-1, keepdim=True)


def _embed_texts(texts: list[str]) -> torch.Tensor:
    return torch.cat([
        _unit(gate_model.get_text_features(**gate_processor(
            text=[f"a photo of {t}." for t in texts[i:i + 256]], return_tensors="pt", padding=True).to(gate_model.device)))
        for i in range(0, len(texts), 256)
    ])


_label_embeddings = None


def label_embeddings() -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """(gate_text, vocab_text, scale), embedded once per process; each upload then costs one image pass.
    Not run at import: torch compute in the ZeroGPU parent process breaks the GPU worker it forks."""
    global _label_embeddings
    if _label_embeddings is None:
        with torch.no_grad():
            _label_embeddings = (_embed_texts([prompt for prompt, _, _ in GATE_LABELS]),
                                 _embed_texts(NAME_VOCAB), gate_model.logit_scale.exp())
    return _label_embeddings


@asynccontextmanager
async def lifespan(_app):
    label_embeddings()  # warm up on server start so the first upload isn't slow
    yield


app = FastAPI(title="Rice Disease Detection API", lifespan=lifespan)
# Frontends may upload photos; storage credentials remain on the backend.
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["GET", "POST"], allow_headers=["*"])


def rice_check(image: Image.Image) -> tuple[bool, float, list[dict]]:
    """Returns (is rice, total rice probability, top 3 distinct guesses as {label, confidence})."""
    gate_text, vocab_text, gate_scale = label_embeddings()
    with torch.no_grad():
        image_emb = _unit(gate_model.get_image_features(**gate_processor(images=image, return_tensors="pt").to(gate_model.device)))
        probs = (gate_scale * image_emb @ gate_text.T).softmax(-1)[0].tolist()
    totals: dict[str, float] = {}  # prompts sharing a display name are merged
    for (_, name, _), p in zip(GATE_LABELS, probs):
        totals[name] = totals.get(name, 0.0) + p
    best = max(range(len(GATE_LABELS)), key=probs.__getitem__)
    share = sum(p for (_, _, rice), p in zip(GATE_LABELS, probs) if rice)
    guesses = sorted(totals.items(), key=lambda kv: kv[1], reverse=True)[:3]
    is_rice = GATE_LABELS[best][2]
    if not is_rice and guesses[0][1] < CURATED_NAME_MIN:
        with torch.no_grad():
            vocab_probs = (gate_scale * image_emb @ vocab_text.T).softmax(-1)[0]
        top = vocab_probs.topk(3)
        guesses = [(NAME_VOCAB[i], p) for p, i in zip(top.values.tolist(), top.indices.tolist())]
    return is_rice, share, [{"label": n, "confidence": round(c, 4)} for n, c in guesses]


@app.get("/health")
def health():
    return {"status": "ok", "disease_model": DISEASE_MODEL, "gate_model": GATE_MODEL}


@app.get("/diseases")
def diseases():
    items = [
        {"disease": v["name"], "category": v["category"], "pathogen": v["pathogen"], "severity": v["severity"]}
        for v in RECOMMENDATIONS.values() if v["category"] != "Healthy"
    ]
    return {"count": len(items), "diseases": items}


@app.post("/predict")
async def predict(file: UploadFile = File(...)):
    data = await file.read(MAX_BYTES + 1)
    if len(data) > MAX_BYTES:
        raise HTTPException(413, "Image too large (max 10 MB).")
    try:
        # Phones store portrait shots sideways plus an EXIF rotate flag; apply it so models and storage see it upright.
        image = ImageOps.exif_transpose(Image.open(io.BytesIO(data))).convert("RGB")
    except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
        raise HTTPException(400, "File is not a valid image.")

    # Keep the same result format for FastAPI and the Gradio ZeroGPU adapter.
    result = await run_in_threadpool(classify_image, image)
    result["storage"] = await run_in_threadpool(store_image, image, result)
    return result


def classify_image(image: Image.Image) -> dict:
    is_rice, score, guesses = rice_check(image)
    if not is_rice:
        top = guesses[0]
        sure = top["confidence"] >= 0.5
        what = f"{top['label']} ({top['confidence']:.0%})"
        raise HTTPException(
            422,
            {"is_rice": False, "rice_confidence": round(score, 4), "looks_like": top["label"],
             "looks_like_confidence": top["confidence"], "guesses": guesses,
             "message": (f"This looks like {what}, not a rice plant." if sure
                         else f"This doesn't look like a rice plant. Best guess: {what}.")
                        + " Upload a clear, close-up photo of a rice leaf."},
        )

    # transformers 5 treats top_k=None as 5; ask for every class so readings match the model output.
    raw = disease_clf(image, top_k=disease_clf.model.config.num_labels)
    readings = [
        {
            "disease": RECOMMENDATIONS[r["label"]]["name"],
            "category": RECOMMENDATIONS[r["label"]]["category"],
            "pathogen": RECOMMENDATIONS[r["label"]]["pathogen"],
            "confidence": round(r["score"], 4),
        }
        for r in raw
    ]
    top = readings[0]
    info = RECOMMENDATIONS[raw[0]["label"]]
    result = {
        "is_rice": True,
        "rice_confidence": round(score, 4),
        **top,
        "severity": info["severity"],
        "readings": readings,
        "recommendation": {"treatment": info["treatment"], "prevention": info["prevention"]},
    }
    result["uncertain"] = top["confidence"] < CONFIDENT_MIN
    close_up = bool(guesses) and guesses[0]["label"] in CLOSE_UP_NAMES
    result["note"] = (
        f"Low confidence ({top['confidence']:.0%}). Retake a sharp, close-up photo of one affected leaf in daylight."
        if result["uncertain"] else
        None if close_up else
        "This looks like a wide shot. For a reliable diagnosis, photograph one leaf up close."
    )
    return result


def store_image(image: Image.Image, result: dict) -> dict:
    # The database schema excludes these UI fields; don't mutate the response.
    row = {key: value for key, value in result.items() if key not in {"uncertain", "note", "storage"}}
    photo = io.BytesIO()
    image.save(photo, format="JPEG", quality=90)
    return save_scan(photo.getvalue(), row)


@app.post("/device/predict")
async def device_predict(file: UploadFile = File(...), x_api_key: str = Header("")):
    # The capture device authenticates with DEVICE_API_KEY; the web UI keeps using the open /predict.
    expected = os.environ.get("DEVICE_API_KEY", "")
    if not expected:
        raise HTTPException(503, "Device access is not configured on the server.")
    if not secrets.compare_digest(x_api_key.encode(), expected.encode()):
        raise HTTPException(401, "Invalid or missing API key.")
    return await predict(file)


if __name__ == "__main__":
    import uvicorn

    # Local dev reads backend/.env; hosted deploys set real environment variables instead.
    env_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".env")
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 7860)),
                env_file=env_file if os.path.exists(env_file) else None)