File size: 3,636 Bytes
a52b57c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import tempfile

import gradio as gr
import cv2
import numpy as np
from ultralytics import YOLO

# ==================================================
# Base directory (safe for local / HF / Docker)
# ==================================================
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# ==================================================
# Model path
# ==================================================
MODEL_PATH = os.path.join(BASE_DIR, "best.onnx")

if not os.path.exists(MODEL_PATH):
    raise FileNotFoundError(f"ONNX model not found at: {MODEL_PATH}")

print(f"Loading ONNX model from: {MODEL_PATH}")
model = YOLO(MODEL_PATH)
print("Model loaded successfully")

# ==================================================
# Inference function
# ==================================================
def detect_objects(

    image: np.ndarray,

    conf_threshold: float = 0.5,

    iou_threshold: float = 0.2,

    max_det: int = 10

):
    if image is None:
        return None

    # Convert RGB -> BGR (OpenCV)
    img_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    # Save temp image (Ultralytics prefers path)
    with tempfile.NamedTemporaryFile(
        suffix=".jpg",
        delete=False
    ) as tmp:
        temp_path = tmp.name
        cv2.imwrite(temp_path, img_bgr)

    try:
        # Run inference
        results = model(
            source=temp_path,
            conf=conf_threshold,
            iou=iou_threshold,
            max_det=max_det
        )

        # Draw detections
        annotated = results[0].plot()

        # Convert BGR -> RGB for Gradio
        annotated_rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB)
        return annotated_rgb

    finally:
        # Always cleanup temp file
        if os.path.exists(temp_path):
            os.remove(temp_path)

# ==================================================
# Gradio UI
# ==================================================
with gr.Blocks(title="YOLO ONNX Object Detection") as demo:
    gr.Markdown(
        """

        # ๐Ÿ” YOLO ONNX Object Detection  

        Upload an image and run inference using a YOLO ONNX model.

        """
    )

    with gr.Row():
        with gr.Column(scale=1):
            input_image = gr.Image(
                type="numpy",
                label="Upload Image"
            )

            conf = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.5,
                step=0.05,
                label="Confidence Threshold"
            )

            iou = gr.Slider(
                minimum=0.1,
                maximum=1.0,
                value=0.2,
                step=0.05,
                label="IoU Threshold"
            )

            max_det = gr.Slider(
                minimum=1,
                maximum=100,
                value=10,
                step=1,
                label="Max Detections"
            )

            run_btn = gr.Button("Run Detection ๐Ÿš€")

        with gr.Column(scale=1):
            output_image = gr.Image(
                label="Detection Result"
            )

    run_btn.click(
        fn=detect_objects,
        inputs=[input_image, conf, iou, max_det],
        outputs=output_image
    )

# ==================================================
# Launch
# ==================================================
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.environ.get("PORT", 7860)),
        show_error=True
    )