testingtessting / app.py
arthainfotama's picture
Upload 3 files
a52b57c verified
Raw History Blame Contribute Delete
3.64 kB
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
)