Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415164 unmodified lines212223242526272829303132333435363738393 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192import ioimport osimport base64import collectionsimport numpy as npfrom PIL import Imagefrom ultralytics import YOLOfrom huggingface_hub import hf_hub_downloadfrom fastapi import File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponseimport gradio as grimport spaces # Import Hugging Face's GPU scheduling library# 1. Initialize the YOLO11 model globallytry:4 unmodified linesprint(f"Error loading model: {e}")model = None# --- CRITICAL ZEROGPU JUGAAAD ---# We decorate our heavy-lifting inference function with @spaces.GPU.# Hugging Face will detect this at startup and grant us free GPU access!@spaces.GPUdef run_gpu_inference(img_array):# YOLO automatically transfers weights to the A100 GPU and runs predictionresults = model.predict(source=img_array, conf=0.25, device="cuda", save=False)# Draw prediction bounding boxes (runs on GPU)annotated_img = results[0].plot()# Convert BGR back to RGBannotated_img_rgb = annotated_img[:, :, ::-1]# Extract class countsdetected_boxes = results[0].boxes3 unmodified linesclass_names = [model.names[cid] for cid in class_ids]counts = dict(collections.Counter(class_names))return annotated_img_rgb, counts# ---------------------------------# 2. Define standard Gradio Blocks app to satisfy Hugging Face's SDKwith gr.Blocks(title="Kortiv AI - API Portal") as demo:gr.Markdown("# 🌱 Kortiv AI - SpecimenAI API Portal")gr.Markdown("The backend is running successfully on NVIDIA ZeroGPU. Send POST requests to `/api/predict`.")# 3. Access the underlying FastAPI app from Gradioapp = demo.app# 4. Inject CORS Middleware directly into Gradio's internal FastAPI appapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# 5. Inject our custom /api/predict route# Updated Route:@app.post("/api/diagnose")async def predict(file: UploadFile = File(...)):if not model:return JSONResponse(status_code=500, content={"error": "Model not loaded on server"})contents = await file.read()image = Image.open(io.BytesIO(contents)).convert("RGB")img_array = np.array(image)# Call our GPU-accelerated helper function safely!annotated_img_rgb, counts = run_gpu_inference(img_array)# Convert PIL Image directly to Base64 stringpil_img = Image.fromarray(annotated_img_rgb)buffered = io.BytesIO()pil_img.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")return {"image": f"data:image/jpeg;base64,{img_str}","metrics": counts}# 6. Launch the Gradio app globally (required by Hugging Face)demo.launch()123456789104 unmodified lines1516171819202122232425262728293031323334353 unmodified lines3940414243444546474849505152535455565758import gradio as grfrom PIL import Imageimport numpy as npfrom ultralytics import YOLOfrom huggingface_hub import hf_hub_downloadimport collectionsimport spaces # Import Hugging Face's GPU scheduler# 1. Initialize the YOLO11 model globallytry:4 unmodified linesprint(f"Error loading model: {e}")model = None# 2. Define the prediction function on ZeroGPU@spaces.GPUdef predict_leaf(img):if img is None:return None, {}# Run YOLO11 prediction directly on NVIDIA GPUresults = model.predict(source=img, conf=0.25, device="cuda", save=False)# Draw prediction bounding boxes (runs on GPU)annotated_img = results[0].plot()# Convert BGR back to RGBannotated_img_rgb = annotated_img[:, :, ::-1]pil_img = Image.fromarray(annotated_img_rgb)# Extract class countsdetected_boxes = results[0].boxes3 unmodified linesclass_names = [model.names[cid] for cid in class_ids]counts = dict(collections.Counter(class_names))return pil_img, counts# 3. Create the standard Gradio Interface# We expose the API endpoint with the name "predict_leaf"demo = gr.Interface(fn=predict_leaf,inputs=gr.Image(type="pil", label="Upload Leaf Specimen"),outputs=[gr.Image(type="pil", label="YOLO11 Output"),gr.JSON(label="Detected Metrics")],title="🌱 Kortiv AI - SpecimenAI API Portal",api_name="predict_leaf")# 4. Launch globally (required by HF)demo.launch()
app.py+26-60