Spaces:
Running on Zero
Running on Zero
Download main.py from DevDenz/rice-detection-api: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/DevDenz/rice-detection-api/resolve/main/main.py
- Command line
-
hf download hf://spaces/DevDenz/rice-detection-api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/DevDenz/rice-detection-api/resolve/main/main.py
11.5 kB
| 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 | |
| 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] | |
| def health(): | |
| return {"status": "ok", "disease_model": DISEASE_MODEL, "gate_model": GATE_MODEL} | |
| 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} | |
| 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) | |
| 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) | |