File size: 6,060 Bytes
b50b4a1
 
 
 
0355705
b50b4a1
fcbab37
 
b50b4a1
 
 
 
 
fcbab37
b50b4a1
 
 
fcbab37
b50b4a1
 
 
 
 
 
 
 
 
 
 
 
 
fcbab37
b50b4a1
 
fcbab37
b50b4a1
 
 
f427345
b50b4a1
 
 
 
 
 
 
 
0355705
b50b4a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f427345
b50b4a1
 
 
 
 
 
 
 
 
 
 
f427345
b50b4a1
 
 
 
f427345
b50b4a1
 
f427345
b50b4a1
 
 
f427345
0355705
b50b4a1
 
 
 
 
0355705
b50b4a1
 
0355705
b50b4a1
 
 
0355705
 
 
b50b4a1
 
 
 
 
 
 
 
 
 
 
 
 
 
2bbc52e
 
b50b4a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab3f20f
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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()