Sumeshbuilds's picture
Update app.py
b50b4a1 verified
Raw History Blame Contribute Delete
6.06 kB
import io
import os
import base64
import collections
import numpy as np
from PIL import Image
from ultralytics import YOLO
from huggingface_hub import hf_hub_download
from fastapi import File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import gradio as gr
import 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.GPU
def 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].boxes
if len(label_boxes) > 0:
# Take the label box with the highest confidence
best_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 array
cropped_label = img_array[y1:y2, x1:x2]
# Convert cropped array to PIL -> Base64
cropped_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.0
seg_results = segmenter.predict(source=img_array, conf=0.25, device="cuda", save=False)
plant_boxes = seg_results[0].boxes
if len(plant_boxes) > 0:
total_pixels = img_array.shape[0] * img_array.shape[1]
plant_pixels = 0
# Calculate sum of detected specimen bounding box areas
for box in plant_boxes.xyxy.cpu().numpy():
x1, y1, x2, y2 = box
plant_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 RGB
pil_annotated = Image.fromarray(annotated_img_rgb)
# Count organs
organ_boxes = organ_results[0].boxes
counts = {}
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.app
app.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 pipeline
pil_annotated, cropped_label_b64, plant_coverage_pct, counts = run_scientific_pipeline(img_array)
# Convert annotated image to Base64
buffered = 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 globally
demo.launch()