Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import 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:model_path = hf_hub_download(repo_id="kortivai/SpecimenAI-PlantDoc", filename="best.pt")model = YOLO(model_path)print("YOLO11 Model loaded successfully!")except Exception as e:print(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].boxescounts = {}if len(detected_boxes) > 0:class_ids = detected_boxes.cls.cpu().numpy().astype(int)class_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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151import 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 HF ZeroGPU scheduling# =====================================================================# STEP 1: DYNAMICALLY DOWNLOAD ALL 3 ENGINES FROM KORTIV AI# =====================================================================try:print("Downloading Model 1: Plant Segmenter...")seg_path = hf_hub_download(repo_id="kortivai/SpecimenAI-PlantDoc", filename="plant_segmenter.pt")segmenter = YOLO(seg_path)print("Downloading Model 2: Label Detector...")lbl_path = hf_hub_download(repo_id="kortivai/SpecimenAI-PlantDoc", filename="label_detector.pt")label_detector = YOLO(lbl_path)print("Downloading Model 3: Organ Counter...")org_path = hf_hub_download(repo_id="kortivai/SpecimenAI-PlantDoc", filename="organ_counter.pt")organ_counter = YOLO(org_path)print("✔ All 3 YOLO11/YOLO26-s engines loaded successfully into memory!")except Exception as e:print(f"Error loading models: {e}")segmenter, label_detector, organ_counter = None, None, None# =====================================================================# STEP 2: THE CHAINED PIPELINE ENGINE (RUNS ON A100 GPU)# =====================================================================@spaces.GPUdef run_scientific_pipeline(img_array):if img_array is None:return None, "", 0.0, {}# --- PIPELINE STAGE 1: DETECT & CROP THE PAPER LABEL ---cropped_label_b64 = ""label_results = label_detector.predict(source=img_array, conf=0.25, device="cuda", save=False)label_boxes = label_results[0].boxesif len(label_boxes) > 0:# Take the label box with the highest confidencebest_idx = label_boxes.conf.cpu().numpy().argmax()xyxy = label_boxes.xyxy[best_idx].cpu().numpy().astype(int)x1, y1, x2, y2 = xyxy# Crop the label out of the raw image arraycropped_label = img_array[y1:y2, x1:x2]# Convert cropped array to PIL -> Base64cropped_pil = Image.fromarray(cropped_label)buffered = io.BytesIO()cropped_pil.save(buffered, format="JPEG")cropped_label_b64 = "data:image/jpeg;base64," + base64.b64encode(buffered.getvalue()).decode("utf-8")# --- PIPELINE STAGE 2: CALCULATE PLANT COVERAGE (%) ---plant_coverage_pct = 0.0seg_results = segmenter.predict(source=img_array, conf=0.25, device="cuda", save=False)plant_boxes = seg_results[0].boxesif len(plant_boxes) > 0:total_pixels = img_array.shape[0] * img_array.shape[1]plant_pixels = 0# Calculate sum of detected specimen bounding box areasfor box in plant_boxes.xyxy.cpu().numpy():x1, y1, x2, y2 = boxplant_pixels += (x2 - x1) * (y2 - y1)plant_coverage_pct = min(100.0, (plant_pixels / total_pixels) * 100.0)# --- PIPELINE STAGE 3: DETECT & COUNT BIOLOGICAL ORGANS ---organ_results = organ_counter.predict(source=img_array, conf=0.25, device="cuda", save=False)# Draw organ detections (Leaf, Flower, Fruit)annotated_img = organ_results[0].plot()annotated_img_rgb = annotated_img[:, :, ::-1] # BGR to RGBpil_annotated = Image.fromarray(annotated_img_rgb)# Count organsorgan_boxes = organ_results[0].boxescounts = {}if len(organ_boxes) > 0:class_ids = organ_boxes.cls.cpu().numpy().astype(int)class_names = [organ_counter.names[cid] for cid in class_ids]counts = dict(collections.Counter(class_names))return pil_annotated, cropped_label_b64, round(plant_coverage_pct, 2), counts# =====================================================================# STEP 3: DEFINE GRADIO INTERFACE# =====================================================================demo = gr.Interface(fn=run_scientific_pipeline,inputs=gr.Image(type="numpy", label="Upload Specimen Sheet"),outputs=[gr.Image(type="pil", label="Annotated Specimen"),gr.Textbox(label="Cropped Label (Base64)"),gr.Number(label="Plant Coverage (%)"),gr.JSON(label="Detected Metrics")],title="🌱 Kortiv AI - SpecimenAI API Portal",api_name="predict_leaf")# =====================================================================# STEP 4: FASTAPI CORS OVERRIDES (FOR DECOUPLED VERCEL APP)# =====================================================================app = demo.appapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Injected route for direct REST API queries (if required)@app.post("/api/diagnose")async def predict_api(file: UploadFile = File(...)):if not segmenter or not label_detector or not organ_counter:return JSONResponse(status_code=500, content={"error": "One or more pipeline models failed to load"})contents = await file.read()image = Image.open(io.BytesIO(contents)).convert("RGB")img_array = np.array(image)# Execute the GPU-accelerated pipelinepil_annotated, cropped_label_b64, plant_coverage_pct, counts = run_scientific_pipeline(img_array)# Convert annotated image to Base64buffered = io.BytesIO()pil_annotated.save(buffered, format="JPEG")img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")return {"image": f"data:image/jpeg;base64,{img_str}","cropped_label": cropped_label_b64,"plant_coverage": plant_coverage_pct,"metrics": counts}# Launch the server globallydemo.launch()
app.py+128-35