Spaces:
Running on Zero
Running on Zero
File size: 2,298 Bytes
ba2ae67 2620364 ba2ae67 2620364 ba2ae67 2620364 ba2ae67 f6e5106 ba2ae67 2620364 ba2ae67 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 | """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)
|