PabsCanCode
Claude Opus 5.5
Embed CLIP label text lazily instead of at import
f6e5106
Raw History Blame Contribute Delete
2.3 kB
"""Gradio entry point for the free ZeroGPU Space (upload as app.py)."""
import io
import os
# Availability checks must not initialize the CUDA runtime in the parent process.
os.environ.setdefault("PYTORCH_NVML_BASED_CUDA_CHECK", "1")
# Import spaces before torch/transformers so ZeroGPU can enable CUDA emulation.
import spaces
import gradio as gr
import torch
from fastapi import HTTPException
from PIL import Image, ImageOps, UnidentifiedImageError
import main as backend
# ZeroGPU requires CUDA placement at module scope, outside the decorated function.
# Label text embeddings are computed lazily inside the GPU worker (see main.label_embeddings).
backend.disease_clf.model.to("cuda")
backend.disease_clf.device = torch.device("cuda")
backend.gate_model.to("cuda")
@spaces.GPU(duration=20)
def infer(image):
try:
return backend.classify_image(image)
except HTTPException as exc:
return {"detail": exc.detail}
def predict(file):
if not file:
return {"detail": "Choose an image first."}
try:
with open(file, "rb") as uploaded:
data = uploaded.read(backend.MAX_BYTES + 1)
if len(data) > backend.MAX_BYTES:
return {"detail": "Image too large (max 10 MB)."}
image = ImageOps.exif_transpose(Image.open(io.BytesIO(data))).convert("RGB")
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
return {"detail": "File is not a valid image."}
result = infer(image)
if "detail" not in result:
# Persist only accepted scans, after releasing the GPU allocation.
result["storage"] = backend.store_image(image, result)
return result
with gr.Blocks(title="Rice Disease Detection") as demo:
gr.Markdown("# Rice Disease Detection\nUpload a clear, close-up photo of one rice leaf.")
photo = gr.File(label="Rice leaf photo", file_types=["image"], type="filepath")
result = gr.JSON(label="Diagnosis")
gr.Button("Analyze").click(predict, inputs=photo, outputs=result, api_name="predict", concurrency_limit=1)
catalog = gr.JSON(visible=False)
demo.load(backend.diseases, inputs=None, outputs=catalog, api_name="diseases", queue=False)
if __name__ == "__main__":
demo.queue(max_size=10).launch(max_file_size="10mb", show_error=True)