import os import gradio as gr from ultralytics import YOLO import tempfile import cv2 import numpy as np import mlflow from datetime import datetime import time import pandas as pd from collections import defaultdict DAGSHUB_REPO_OWNER = os.getenv("DAGSHUB_REPO_OWNER") DAGSHUB_REPO_NAME = os.getenv("DAGSHUB_REPO_NAME") MLFLOW_ENABLED = False if DAGSHUB_REPO_OWNER and DAGSHUB_REPO_NAME: mlflow.set_tracking_uri(f"https://dagshub.com/{DAGSHUB_REPO_OWNER}/{DAGSHUB_REPO_NAME}.mlflow" ) MLFLOW_ENABLED = True print("MLflow tracking is configured for DagsHub.") else: print("DagsHub secrets not found. MLflow logging will be disabled.") os.environ.setdefault("YOLO_CONFIG_DIR", "/tmp/Ultralytics") MODEL_PATH = "yolov11s_final.pt" model = YOLO(MODEL_PATH) def log_image_prediction(input_img_pil, output_image_path, conf, inference_time, detections_df): if not MLFLOW_ENABLED: return try: with mlflow.start_run(run_name=f"Image_Prediction_{datetime.now().strftime('%Y%m%d-%H%M%S')}"): mlflow.log_param("confidence_threshold", conf) mlflow.log_param("prediction_type", "image") mlflow.log_metric("inference_time_seconds", inference_time) mlflow.log_metric("total_detections", len(detections_df)) if not detections_df.empty: class_counts = defaultdict(int) for _, row in detections_df.iterrows(): class_name = row['class_name'] confidence = row['confidence'] class_counts[class_name] += 1 metric_name = f"detection_{class_name}_{class_counts[class_name]}" mlflow.log_metric(metric_name, confidence) input_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name input_img_pil.save(input_path) mlflow.log_artifact(input_path, "input_image") mlflow.log_artifact(output_image_path, "output_image") print(f"Successfully logged image prediction.") except Exception as e: print(f"Error logging to MLflow: {e}") def log_video_prediction(input_path, output_path, conf): if not MLFLOW_ENABLED: return try: with mlflow.start_run(run_name=f"Video_Prediction_{datetime.now().strftime('%Y%m%d-%H%M%S')}"): mlflow.log_param("confidence_threshold", conf) mlflow.log_param("prediction_type", "video") mlflow.log_artifact(input_path, "input") mlflow.log_artifact(output_path, "output") print(f"Successfully logged video prediction.") except Exception as e: print(f"Error logging to MLflow: {e}") def run_image_inference(img_pil, conf=0.25): if img_pil is None: return None, 0.0, pd.DataFrame() img_np = np.array(img_pil) img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR) start_time = time.time() results = model(img_bgr, conf=conf, iou=0.4, verbose=False, imgsz=640) end_time = time.time() inference_time = end_time - start_time result = results[0] detections = [] for box in result.boxes: class_id = int(box.cls.cpu().item()) class_name = result.names[class_id] confidence = float(box.conf.cpu().item()) detections.append({"class_name": class_name, "confidence": round(confidence, 4)}) detections_df = pd.DataFrame(detections) annotated_img = result.plot() annotated_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB) out_path = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name cv2.imwrite(out_path, cv2.cvtColor(annotated_rgb, cv2.COLOR_RGB2BGR)) return out_path, inference_time, detections_df def run_video_inference(video_path, conf=0.25, frame_skip=2): if video_path is None: return None temp_out = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name results_generator = model(video_path, conf=conf, iou=0.4, verbose=False, stream=True, imgsz=640) try: first_result = next(results_generator) except StopIteration: return None cap = cv2.VideoCapture(video_path) fps = cap.get(cv2.CAP_PROP_FPS) or 25.0 h, w = first_result.orig_shape output_fps = fps / (frame_skip + 1) if frame_skip > -1 else fps fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(temp_out, fourcc, output_fps, (w, h)) out.write(first_result.plot()) frame_count = 0 for result in results_generator: frame_count += 1 if frame_skip > -1 and frame_count % (frame_skip + 1) != 0: continue annotated_frame = result.plot() out.write(annotated_frame) cap.release() out.release() return temp_out dark_css = """""" with gr.Blocks() as demo: gr.HTML(dark_css) gr.Markdown("# ๐ฏ YOLO Detection Studio โ Image & Video") gr.Markdown("