Mosensei commited on
Commit
91c8ef0
·
verified ·
1 Parent(s): d92eb4b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -0
app.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import mlflow
3
+ import dagshub
4
+ from ultralytics import YOLO
5
+ from PIL import Image
6
+ import cv2
7
+ import numpy as np
8
+ import os
9
+ import time
10
+ import tempfile
11
+ import shutil
12
+
13
+ # ==============================
14
+ # MLflow / DagsHub Configuration using Secrets
15
+ # ==============================
16
+ # Secrets من HF Spaces
17
+ tracking_uri = os.getenv("MLFLOW_TRACKING_URI")
18
+ username = os.getenv("MLFLOW_TRACKING_USERNAME")
19
+ password = os.getenv("MLFLOW_TRACKING_PASSWORD")
20
+
21
+ if not all([tracking_uri, username, password]):
22
+ raise ValueError("MLflow Secrets مش مظبوطة! روح لـ Space Settings → Secrets وتأكد من الأسماء")
23
+
24
+ os.environ["MLFLOW_TRACKING_URI"] = tracking_uri
25
+ os.environ["MLFLOW_TRACKING_USERNAME"] = username
26
+ os.environ["MLFLOW_TRACKING_PASSWORD"] = password
27
+
28
+ # تفعيل DagsHub
29
+ dagshub.init(repo_owner="Mosensei7", repo_name="AutonomousVehiclesDetectionDEPI", mlflow=True)
30
+
31
+ # إنشاء experiment
32
+ mlflow.set_experiment("YOLOv12s_Inference_Logs")
33
+
34
+ print("MLflow connected successfully to DagsHub!")
35
+
36
+ # ==============================
37
+ # Load Model
38
+ # ==============================
39
+ model = YOLO("Mosensei7/yolov12s-egyptian-autonomous-vehicles/best.pt") # اسم الـ repo بتاعك
40
+
41
+ # ==============================
42
+ # Inference with Full MLflow Tracking
43
+ # ==============================
44
+ def run_inference(media_file, media_type):
45
+ if media_file is None:
46
+ return None, None, "ارفع ملف أولاً"
47
+
48
+ media_path = media_file.name
49
+
50
+ with mlflow.start_run(run_name=f"Inference_{int(time.time())}") as run:
51
+ mlflow.log_param("media_type", media_type)
52
+ mlflow.log_param("model", "YOLOv12s")
53
+ mlflow.log_param("timestamp", time.strftime("%Y-%m-%d %H:%M:%S"))
54
+
55
+ if media_type == "Image":
56
+ img = Image.open(media_path).convert("RGB")
57
+ img_array = np.array(img)
58
+
59
+ results = model(img_array)[0]
60
+ annotated = results.plot()
61
+ output_img = Image.fromarray(annotated[..., ::-1]) # BGR → RGB
62
+
63
+ # حفظ مؤقت ورفع artifacts
64
+ with tempfile.TemporaryDirectory() as tmpdir:
65
+ in_path = os.path.join(tmpdir, "input.jpg")
66
+ out_path = os.path.join(tmpdir, "output.jpg")
67
+ img.save(in_path)
68
+ output_img.save(out_path)
69
+
70
+ mlflow.log_artifact(in_path, artifact_path="input")
71
+ mlflow.log_artifact(out_path, artifact_path="output")
72
+
73
+ detections = len(results.boxes) if results.boxes is not None else 0
74
+ mlflow.log_metric("detections_count", detections)
75
+
76
+ run_url = f"https://dagshub.com/Mosensei7/AutonomousVehiclesDetectionDEPI/mlflow/#/experiments/{mlflow.get_experiment_by_name('YOLOv12s_Inference_Logs').experiment_id}/runs/{run.info.run_id}"
77
+
78
+ return output_img, None, f"✅ تم التسجيل!\nRun ID: {run.info.run_id}\n[شوف الـ Log على DagsHub]({run_url})"
79
+
80
+ else: # Video
81
+ cap = cv2.VideoCapture(media_path)
82
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30
83
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
84
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
85
+
86
+ output_video = "output_video.mp4"
87
+ writer = cv2.VideoWriter(output_video, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
88
+
89
+ frame_count = 0
90
+ total_detections = 0
91
+
92
+ while cap.isOpened():
93
+ ret, frame = cap.read()
94
+ if not ret:
95
+ break
96
+ results = model(frame)[0]
97
+ annotated = results.plot()
98
+ writer.write(annotated)
99
+ frame_count += 1
100
+ total_detections += len(results.boxes) if results.boxes is not None else 0
101
+
102
+ cap.release()
103
+ writer.release()
104
+
105
+ # رفع الفيديوهات
106
+ mlflow.log_artifact(media_path, artifact_path="input_video")
107
+ mlflow.log_artifact(output_video, artifact_path="output_video")
108
+
109
+ mlflow.log_metric("frames_processed", frame_count)
110
+ mlflow.log_metric("total_detections", total_detections)
111
+ mlflow.log_metric("avg_detections_per_frame", total_detections / frame_count if frame_count > 0 else 0)
112
+
113
+ run_url = f"https://dagshub.com/Mosensei7/AutonomousVehiclesDetectionDEPI/mlflow/#/experiments/{mlflow.get_experiment_by_name('YOLOv12s_Inference_Logs').experiment_id}/runs/{run.info.run_id}"
114
+
115
+ # حذف الفيديو المؤقت عشان المساحة
116
+ if os.path.exists(output_video):
117
+ os.remove(output_video)
118
+
119
+ return None, output_video, f"✅ تم التسجيل!\nRun ID: {run.info.run_id}\n[شوف الـ Log على DagsHub]({run_url})"
120
+
121
+ # ==============================
122
+ # Futuristic UI (الأجمل على الإطلاق)
123
+ # ==============================
124
+ css = """
125
+ body { background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); color: #00ffff; font-family: 'Orbitron', sans-serif; }
126
+ .gradio-container { max-width: 1100px; margin: auto; background: rgba(0,0,0,0.8); border: 3px solid #00ffff; border-radius: 30px; padding: 40px; box-shadow: 0 0 50px #00ffff; }
127
+ h1 { text-align: center; color: #00ffff; text-shadow: 0 0 20px #00ffff; font-size: 3.2em; }
128
+ button { background: linear-gradient(45deg, #ff00ff, #00ffff); border: none; border-radius: 20px; height: 60px; font-size: 1.3em; box-shadow: 0 0 25px #00ffff; }
129
+ """
130
+
131
+ with gr.Blocks(css=css, theme=gr.themes.Dark()) as demo:
132
+ gr.Markdown("""
133
+ # 🚀 YOLOv12s - كشف المركبات في الشوارع المصرية 🇪🇬
134
+ **كل عملية كشف بتترفع تلقائيًا على DagsHub MLflow مع الـ input والـ output والإحصائيات**
135
+ """)
136
+
137
+ with gr.Row():
138
+ with gr.Column(scale=1):
139
+ media = gr.File(label="📤 ارفع صورة أو فيديو", file_types=[".jpg", ".jpeg", ".png", ".mp4", ".avi"])
140
+ media_type = gr.Radio(["Image", "Video"], label="نوع الميديا", value="Image")
141
+ btn = gr.Button("🚀 ابدأ الكشف", variant="primary", size="lg")
142
+
143
+ with gr.Column(scale=2):
144
+ img_out = gr.Image(label="🖼️ نتيجة الكشف", height=600)
145
+ vid_out = gr.Video(label="🎥 نتيجة الكشف", height=600)
146
+ info = gr.Markdown("**جاهز للكشف...**")
147
+
148
+ btn.click(
149
+ fn=run_inference,
150
+ inputs=[media, media_type],
151
+ outputs=[img_out, vid_out, info]
152
+ )
153
+
154
+ demo.launch()