Depi / app.py
Mosensei7's picture
Update app.py
4c6612b verified
Raw History Blame Contribute Delete
5.17 kB
import os
import time
import tempfile
import cv2
import mlflow
import gradio as gr
from ultralytics import YOLO
# πŸ‘‡ fix Ultralytics warning
os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
# ======================================================
# 1) Load secrets safely
# ======================================================
# Fix YOLO config warning
os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"
# ======================================================
# 1) Databricks Authentication for MLflow in container
# ======================================================
HOST = "https://dbc-2d106fc4-eb47.cloud.databricks.com"
TOKEN = os.getenv("DATABRICKS_TOKEN", None)
if TOKEN is None:
raise ValueError("❌ DATABRICKS_TOKEN not set. Add it inside Hugging Face Secrets!")
# Set the exact variables MLflow needs βœ…
os.environ["DATABRICKS_HOST"] = HOST
os.environ["DATABRICKS_TOKEN"] = TOKEN
# Now point MLflow to Databricks tracking server
mlflow.set_tracking_uri("databricks")
mlflow.set_experiment("/Users/mohsenibrahim034@gmail.com/Autonomous-Vehicles-Inference-MLOps")
# ======================================================
# 2) Load Model
# ======================================================
model = YOLO("yolov11s_final.pt")
# ======================================================
# 3) Inference Functions with Metrics Logging
# ======================================================
def detect_video(video_path):
start = time.time()
try:
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
temp_out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
out = cv2.VideoWriter(temp_out, cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
# Statistics
class_counts = {}
num_detections = 0
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame, iou=0.4, verbose=False)
annotated = results[0].plot()
out.write(annotated)
# Aggregate stats per frame
for r in results:
for c in r.boxes.cls:
class_name = model.names[int(c)]
class_counts[class_name] = class_counts.get(class_name, 0) + 1
num_detections += 1
cap.release()
out.release()
latency = (time.time() - start) * 1000
# Log run to MLflow
with mlflow.start_run():
mlflow.log_param("inference_type", "video")
mlflow.log_metric("latency_ms", latency)
mlflow.log_metric("num_detections", num_detections)
# Log class counts
for cls, count in class_counts.items():
mlflow.log_metric(f"count_{cls}", count)
mlflow.log_artifact(temp_out, "output_video")
return temp_out
except Exception as e:
return f"Error: {e}"
def detect_image(img):
start = time.time()
try:
results = model(img, iou=0.4, verbose=False)
out_img = results[0].plot()
# Statistics
class_counts = {}
num_detections = 0
for r in results:
for c in r.boxes.cls:
class_name = model.names[int(c)]
class_counts[class_name] = class_counts.get(class_name, 0) + 1
num_detections += 1
latency = (time.time() - start) * 1000
with mlflow.start_run():
mlflow.log_param("inference_type", "image")
mlflow.log_metric("latency_ms", latency)
mlflow.log_metric("num_detections", num_detections)
# Log class counts
for cls, count in class_counts.items():
mlflow.log_metric(f"count_{cls}", count)
# Save output image
temp_img = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False).name
cv2.imwrite(temp_img, out_img)
mlflow.log_artifact(temp_img, "output_image")
os.remove(temp_img)
return out_img
except Exception as e:
return f"Error: {e}"
# ======================================================
# 4) Gradio Interface
# ======================================================
with gr.Blocks() as demo:
gr.Markdown("<h1 style='text-align:center;'>YOLO Autonomous Vehicle Detection πŸš—πŸ“‘</h1>")
with gr.Tab("πŸ“Έ Image Detection"):
img_in = gr.Image(type="numpy", label="Upload Image")
img_out = gr.Image(type="numpy", label="Detected Image")
btn_img = gr.Button("Detect")
btn_img.click(detect_image, inputs=img_in, outputs=img_out)
with gr.Tab("πŸŽ₯ Video Detection"):
vid_in = gr.Video(label="Upload Video")
vid_out = gr.Video(label="Detected Video")
btn_vid = gr.Button("Detect")
btn_vid.click(detect_video, inputs=vid_in, outputs=vid_out)
if __name__ == "__main__":
demo.launch()