Mosensei commited on
Commit
b92d5b5
·
verified ·
1 Parent(s): ee3d19f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -46
app.py CHANGED
@@ -1,75 +1,80 @@
1
  import gradio as gr
2
  import mlflow
3
- import os
4
- import time
5
- import tempfile
6
- import shutil
7
  from ultralytics import YOLO
8
  from PIL import Image
9
  import cv2
10
  import numpy as np
 
 
 
11
 
12
  # ==============================
13
- # MLflow Configuration using Secrets ONLY
14
  # ==============================
15
  tracking_uri = os.getenv("MLFLOW_TRACKING_URI")
16
  username = os.getenv("MLFLOW_TRACKING_USERNAME")
17
  password = os.getenv("MLFLOW_TRACKING_PASSWORD")
18
 
19
  if not all([tracking_uri, username, password]):
20
- raise ValueError("MLflow Secrets مش مظبوطة! روح لـ Space Settings → Secrets وتأكد من الأسماء")
21
 
22
  os.environ["MLFLOW_TRACKING_URI"] = tracking_uri
23
  os.environ["MLFLOW_TRACKING_USERNAME"] = username
24
  os.environ["MLFLOW_TRACKING_PASSWORD"] = password
25
 
26
- # إنشاء experiment
 
 
 
27
  mlflow.set_experiment("YOLOv12s_Inference_Logs")
28
- print("✅ MLflow configured successfully using secrets!")
 
29
 
30
  # ==============================
31
- # Load Model
32
  # ==============================
33
- model = YOLO("Yolo12s.pt") # اسم الـ repo بتاعك
 
34
 
35
  # ==============================
36
- # Inference with Full MLflow Tracking
37
  # ==============================
38
  def run_inference(media_file, media_type):
39
  if media_file is None:
40
- return None, None, "ارفع ملف أولاً"
41
 
42
  media_path = media_file.name
43
 
44
- with mlflow.start_run(run_name=f"Inference_{int(time.time())}") as run:
45
  mlflow.log_param("media_type", media_type)
46
- mlflow.log_param("model", "YOLOv12s")
47
  mlflow.log_param("timestamp", time.strftime("%Y-%m-%d %H:%M:%S"))
48
 
 
 
49
  if media_type == "Image":
50
  img = Image.open(media_path).convert("RGB")
51
  img_array = np.array(img)
52
 
53
  results = model(img_array)[0]
54
  annotated = results.plot()
55
- output_img = Image.fromarray(annotated[..., ::-1]) # BGR → RGB
56
 
57
- # حفظ مؤقت ورفع artifacts
58
  with tempfile.TemporaryDirectory() as tmpdir:
59
  in_path = os.path.join(tmpdir, "input.jpg")
60
  out_path = os.path.join(tmpdir, "output.jpg")
61
  img.save(in_path)
62
  output_img.save(out_path)
63
 
64
- mlflow.log_artifact(in_path, artifact_path="input")
65
- mlflow.log_artifact(out_path, artifact_path="output")
66
 
67
  detections = len(results.boxes) if results.boxes is not None else 0
68
- mlflow.log_metric("detections_count", detections)
69
 
70
- 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}"
71
-
72
- return output_img, None, f"✅ تم التسجيل!\nRun ID: {run.info.run_id}\n[شوف الـ Log على DagsHub]({run_url})"
73
 
74
  else: # Video
75
  cap = cv2.VideoCapture(media_path)
@@ -96,48 +101,106 @@ def run_inference(media_file, media_type):
96
  cap.release()
97
  writer.release()
98
 
99
- # رفع الفيديوهات
100
- mlflow.log_artifact(media_path, artifact_path="input_video")
101
- mlflow.log_artifact(output_video, artifact_path="output_video")
102
-
103
- mlflow.log_metric("frames_processed", frame_count)
104
  mlflow.log_metric("total_detections", total_detections)
105
- mlflow.log_metric("avg_detections_per_frame", total_detections / frame_count if frame_count > 0 else 0)
106
-
107
- 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}"
108
 
109
- # حذف الفيديو المؤقت عشان المساحة
110
  if os.path.exists(output_video):
111
  os.remove(output_video)
112
 
113
- return None, output_video, f" تم التسجيل!\nRun ID: {run.info.run_id}\n[شوف الـ Log على DagsHub]({run_url})"
114
 
115
  # ==============================
116
- # Futuristic UI (الأجمل على الإطلاق)
117
  # ==============================
118
  css = """
119
- body { background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); color: #00ffff; font-family: 'Orbitron', sans-serif; }
120
- .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; }
121
- h1 { text-align: center; color: #00ffff; text-shadow: 0 0 20px #00ffff; font-size: 3.2em; }
122
- button { background: linear-gradient(45deg, #ff00ff, #00ffff); border: none; border-radius: 20px; height: 60px; font-size: 1.3em; box-shadow: 0 0 25px #00ffff; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  """
124
 
125
- with gr.Blocks(css=css, theme=gr.themes.Monochrome()) as demo: # ✅ FIXED THEME HERE
126
  gr.Markdown("""
127
- # 🚀 YOLOv12s - كشف المركبات في الشوارع المصرية 🇪🇬
128
- **كل عملية كشف بتترفع تلقائيًا على DagsHub MLflow مع الـ input والـ output والإحصائيات**
 
129
  """)
130
 
131
  with gr.Row():
132
  with gr.Column(scale=1):
133
- media = gr.File(label="📤 ارفع صورة أو فيديو", file_types=[".jpg", ".jpeg", ".png", ".mp4", ".avi"])
134
- media_type = gr.Radio(["Image", "Video"], label="نوع الميديا", value="Image")
135
- btn = gr.Button("🚀 ابدأ الكشف", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
 
136
 
137
  with gr.Column(scale=2):
138
- img_out = gr.Image(label="🖼️ نتيجة الكشف", height=600)
139
- vid_out = gr.Video(label="🎥 نتيجة الكشف", height=600)
140
- info = gr.Markdown("**جاهز للكشف...**")
 
141
 
142
  btn.click(
143
  fn=run_inference,
 
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
 
12
  # ==============================
13
+ # MLflow Authentication via Secrets (زي ما أنت عايز بالظبط)
14
  # ==============================
15
  tracking_uri = os.getenv("MLFLOW_TRACKING_URI")
16
  username = os.getenv("MLFLOW_TRACKING_USERNAME")
17
  password = os.getenv("MLFLOW_TRACKING_PASSWORD")
18
 
19
  if not all([tracking_uri, username, password]):
20
+ raise ValueError("MLflow Secrets مش موجودة أو غلط! روح Settings → Secrets وتأكد من الأسماء التلاتة")
21
 
22
  os.environ["MLFLOW_TRACKING_URI"] = tracking_uri
23
  os.environ["MLFLOW_TRACKING_USERNAME"] = username
24
  os.environ["MLFLOW_TRACKING_PASSWORD"] = password
25
 
26
+ # تفعيل DagsHub
27
+ dagshub.init(repo_owner="Mosensei7", repo_name="AutonomousVehiclesDetectionDEPI", mlflow=True)
28
+
29
+ # إنشاء experiment مخصص
30
  mlflow.set_experiment("YOLOv12s_Inference_Logs")
31
+
32
+ print("✅ MLflow + DagsHub connected successfully via Secrets!")
33
 
34
  # ==============================
35
+ # تحميل الموديل الصحيح
36
  # ==============================
37
+ # لو رافع الموديل على HF كـ repo، استخدم الاسم الكامل
38
+ model = YOLO("Mosensei7/yolov12s-egyptian-autonomous-vehicles/best.pt") # غيّر الاسم لو مختلف
39
 
40
  # ==============================
41
+ # Inference مع رفع كل حاجة على DagsHub
42
  # ==============================
43
  def run_inference(media_file, media_type):
44
  if media_file is None:
45
+ return None, None, "⚠️ ارفع صورة أو فيديو أولاً"
46
 
47
  media_path = media_file.name
48
 
49
+ with mlflow.start_run(run_name=f"YOLOv12s_Inference_{int(time.time())}") as run:
50
  mlflow.log_param("media_type", media_type)
51
+ mlflow.log_param("model_version", "YOLOv12s")
52
  mlflow.log_param("timestamp", time.strftime("%Y-%m-%d %H:%M:%S"))
53
 
54
+ 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}"
55
+
56
  if media_type == "Image":
57
  img = Image.open(media_path).convert("RGB")
58
  img_array = np.array(img)
59
 
60
  results = model(img_array)[0]
61
  annotated = results.plot()
62
+ output_img = Image.fromarray(annotated[..., ::-1])
63
 
64
+ # رفع input/output
65
  with tempfile.TemporaryDirectory() as tmpdir:
66
  in_path = os.path.join(tmpdir, "input.jpg")
67
  out_path = os.path.join(tmpdir, "output.jpg")
68
  img.save(in_path)
69
  output_img.save(out_path)
70
 
71
+ mlflow.log_artifact(in_path, "input")
72
+ mlflow.log_artifact(out_path, "output")
73
 
74
  detections = len(results.boxes) if results.boxes is not None else 0
75
+ mlflow.log_metric("detections", detections)
76
 
77
+ return output_img, None, f"**✅ تم الكشف والتسجيل بنجاح!**\n\n**Run ID:** `{run.info.run_id}`\n[👀 شوف الـ Log كامل على DagsHub]({run_url})"
 
 
78
 
79
  else: # Video
80
  cap = cv2.VideoCapture(media_path)
 
101
  cap.release()
102
  writer.release()
103
 
104
+ mlflow.log_artifact(media_path, "input_video")
105
+ mlflow.log_artifact(output_video, "output_video")
106
+ mlflow.log_metric("frames", frame_count)
 
 
107
  mlflow.log_metric("total_detections", total_detections)
108
+ mlflow.log_metric("avg_detections_per_frame", round(total_detections / frame_count, 2) if frame_count > 0 else 0)
 
 
109
 
110
+ # حذف الفيديو المؤقت
111
  if os.path.exists(output_video):
112
  os.remove(output_video)
113
 
114
+ return None, output_video, f"**✅ تم معالجة الفيديو والتسجيل بنجاح!**\n\n**Run ID:** `{run.info.run_id}`\n[👀 شوف الـ Log كامل على DagsHub]({run_url})"
115
 
116
  # ==============================
117
+ # التصميم الفضائي الرهيب جدًا (Cyberpunk 2077 style)
118
  # ==============================
119
  css = """
120
+ body {
121
+ background: linear-gradient(135deg, #000428, #004e92);
122
+ color: #00ffea;
123
+ font-family: 'Rajdhani', sans-serif;
124
+ }
125
+ .gradio-container {
126
+ max-width: 1200px;
127
+ margin: 0 auto;
128
+ background: linear-gradient(145deg, rgba(0,20,40,0.9), rgba(0,10,30,0.95));
129
+ border: 3px solid #00ffea;
130
+ border-radius: 30px;
131
+ padding: 40px;
132
+ box-shadow:
133
+ 0 0 30px #00ffea,
134
+ inset 0 0 30px rgba(0,255,234,0.2);
135
+ }
136
+ h1 {
137
+ text-align: center;
138
+ font-size: 3.8em;
139
+ color: #00ffea;
140
+ text-shadow:
141
+ 0 0 10px #00ffea,
142
+ 0 0 20px #00ffea,
143
+ 0 0 40px #00ffea;
144
+ letter-spacing: 4px;
145
+ margin-bottom: 20px;
146
+ }
147
+ p {
148
+ text-align: center;
149
+ font-size: 1.4em;
150
+ color: #00ffea;
151
+ text-shadow: 0 0 10px #00ffea;
152
+ }
153
+ button {
154
+ background: linear-gradient(45deg, #ff00ff, #00ffff, #00ff00);
155
+ background-size: 300% 300%;
156
+ animation: gradient 5s ease infinite;
157
+ border: none;
158
+ border-radius: 25px;
159
+ font-size: 1.6em;
160
+ height: 70px;
161
+ font-weight: bold;
162
+ box-shadow: 0 0 30px #00ffff;
163
+ transition: all 0.3s;
164
+ }
165
+ button:hover {
166
+ transform: scale(1.05);
167
+ box-shadow: 0 0 50px #00ffff;
168
+ }
169
+ @keyframes gradient {
170
+ 0% { background-position: 0% 50%; }
171
+ 50% { background-position: 100% 50%; }
172
+ 100% { background-position: 0% 50%; }
173
+ }
174
  """
175
 
176
+ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
177
  gr.Markdown("""
178
+ # 🚀 YOLOv12s
179
+ ### كشف المركبات في الشوارع المصرية بذكاء اصطناعي 🇪🇬
180
+ **كل عملية كشف بتترفع تلقائيًا على DagsHub MLflow مع كل التفاصيل**
181
  """)
182
 
183
  with gr.Row():
184
  with gr.Column(scale=1):
185
+ gr.Markdown("### 📤 ارفع ملفك")
186
+ media = gr.File(
187
+ label="صورة أو فيديو",
188
+ file_types=[".jpg", ".jpeg", ".png", ".mp4", ".avi"],
189
+ height=200
190
+ )
191
+ media_type = gr.Radio(
192
+ ["Image", "Video"],
193
+ label="نوع الميديا",
194
+ value="Image",
195
+ info="اختار نوع الملف اللي هترفعه"
196
+ )
197
+ btn = gr.Button("🔥 ابدأ الكشف الآن", variant="primary", size="lg")
198
 
199
  with gr.Column(scale=2):
200
+ gr.Markdown("### 📊 النتيجة")
201
+ img_out = gr.Image(label="نتيجة الكشف على الصورة", height=550)
202
+ vid_out = gr.Video(label="نتيجة الكشف على الفيديو", height=550)
203
+ info = gr.Markdown("**جاهز للكشف... ارفع ملف واضغط ابدأ**")
204
 
205
  btn.click(
206
  fn=run_inference,