Mosensei commited on
Commit
663093c
·
verified ·
1 Parent(s): e201859

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -89
app.py CHANGED
@@ -1,47 +1,3 @@
1
- Hugging Face's logo
2
- Hugging Face
3
- Models
4
- Datasets
5
- Spaces
6
- Community
7
- Docs
8
- Enterprise
9
- Pricing
10
-
11
-
12
- Spaces:
13
- Mosensei
14
- /
15
- ObjectDetectionAutonomusCar_Yolo12s
16
-
17
-
18
- like
19
- 0
20
-
21
- Logs
22
- App
23
- Files
24
- Community
25
- Settings
26
- ObjectDetectionAutonomusCar_Yolo12s
27
- /
28
- app.py
29
-
30
- Mosensei's picture
31
- Mosensei
32
- Update app.py
33
- cb2ed27
34
- verified
35
- 6 minutes ago
36
- raw
37
-
38
- Copy download link
39
- history
40
- blame
41
- edit
42
- delete
43
-
44
- 10.9 kB
45
  import gradio as gr
46
  import mlflow
47
  import os
@@ -52,34 +8,28 @@ from PIL import Image
52
  import cv2
53
  import numpy as np
54
 
55
- # ==============================
56
  # MLflow Configuration using Secrets
57
- # ==============================
58
  tracking_uri = os.getenv("MLFLOW_TRACKING_URI")
59
  username = os.getenv("MLFLOW_TRACKING_USERNAME")
60
  password = os.getenv("MLFLOW_TRACKING_PASSWORD")
61
 
62
  if not all([tracking_uri, username, password]):
63
- raise ValueError("MLflow Secrets are not configured! Go to Space Settings → Secrets and verify the names")
64
 
65
  os.environ["MLFLOW_TRACKING_URI"] = tracking_uri
66
  os.environ["MLFLOW_TRACKING_USERNAME"] = username
67
  os.environ["MLFLOW_TRACKING_PASSWORD"] = password
68
 
69
  mlflow.set_experiment("YOLOv12s_Inference_Logs")
70
- print("MLflow configured successfully using secrets!")
71
 
72
- # ==============================
73
  # Load Model
74
- # ==============================
75
  model = YOLO("Yolo12s.pt")
76
 
77
- # ==============================
78
  # Inference with Full MLflow Tracking
79
- # ==============================
80
  def run_inference(media_file, media_type):
81
  if media_file is None:
82
- return None, None, None, None, "⚠️ Please upload a file first"
83
 
84
  media_path = media_file.name
85
 
@@ -106,9 +56,9 @@ def run_inference(media_file, media_type):
106
  detections = len(results.boxes) if results.boxes is not None else 0
107
  mlflow.log_metric("detections_count", detections)
108
 
109
- return img, output_img, None, None, f"✅ **Detection Complete!**\n\n🔍 **Objects Detected:** {detections}"
110
 
111
- else: # Video
112
  cap = cv2.VideoCapture(media_path)
113
  fps = cap.get(cv2.CAP_PROP_FPS) or 30
114
  w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
@@ -141,24 +91,25 @@ def run_inference(media_file, media_type):
141
  mlflow.log_metric("total_detections", total_detections)
142
  mlflow.log_metric("avg_detections_per_frame", total_detections / frame_count if frame_count > 0 else 0)
143
 
144
- result_message = f"✅ **Video Processing Complete!**\n\n📹 **Frames Processed:** {frame_count}\n🔍 **Total Detections:** {total_detections}\n📊 **Average per Frame:** {total_detections / frame_count:.2f}"
 
145
 
146
- # Return both input and output video paths
147
  result_video = output_video
148
 
149
  return None, None, media_path, result_video, result_message
150
 
151
- # ==============================
152
- # Modern Aesthetic UI
153
- # ==============================
154
  css = """
155
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
 
156
  * {
157
  font-family: 'Inter', sans-serif;
158
  }
 
159
  body {
160
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
161
  }
 
162
  .gradio-container {
163
  max-width: 1400px !important;
164
  margin: 40px auto !important;
@@ -168,13 +119,14 @@ body {
168
  padding: 0 !important;
169
  overflow: hidden !important;
170
  }
171
- /* Header Styling */
172
  .header-container {
173
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
174
  padding: 48px 40px;
175
  text-align: center;
176
  border-radius: 24px 24px 0 0;
177
  }
 
178
  .header-container h1 {
179
  color: white !important;
180
  font-size: 2.8em !important;
@@ -182,16 +134,17 @@ body {
182
  margin: 0 0 12px 0 !important;
183
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
184
  }
 
185
  .header-container p {
186
  color: rgba(255, 255, 255, 0.95) !important;
187
  font-size: 1.1em !important;
188
  margin: 0 !important;
189
  }
190
- /* Main Content Area */
191
  .main-content {
192
  padding: 48px 40px;
193
  }
194
- /* File Upload Area */
195
  .file-upload-area {
196
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
197
  border-radius: 16px;
@@ -199,12 +152,13 @@ body {
199
  border: 2px dashed #667eea;
200
  transition: all 0.3s ease;
201
  }
 
202
  .file-upload-area:hover {
203
  border-color: #764ba2;
204
  transform: translateY(-2px);
205
  box-shadow: 0 8px 16px rgba(102, 126, 234, 0.2);
206
  }
207
- /* Buttons */
208
  button.primary {
209
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
210
  border: none !important;
@@ -217,11 +171,12 @@ button.primary {
217
  transition: all 0.3s ease !important;
218
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
219
  }
 
220
  button.primary:hover {
221
  transform: translateY(-2px) !important;
222
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.6) !important;
223
  }
224
- /* Radio Buttons */
225
  .radio-group label {
226
  background: white;
227
  padding: 12px 24px;
@@ -230,39 +185,43 @@ button.primary:hover {
230
  cursor: pointer;
231
  transition: all 0.3s ease;
232
  }
 
233
  .radio-group label:hover {
234
  border-color: #667eea;
235
  background: #f5f7fa;
236
  }
237
- /* Output Areas */
238
  .output-image, .output-video {
239
  border-radius: 16px;
240
  overflow: hidden;
241
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
242
  background: white;
243
  }
244
- /* Info Box */
245
  .info-box {
246
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
247
  border-radius: 12px;
248
  padding: 24px;
249
  border-left: 4px solid #667eea;
250
  }
251
- /* Custom Scrollbar */
252
  ::-webkit-scrollbar {
253
  width: 8px;
254
  }
 
255
  ::-webkit-scrollbar-track {
256
  background: #f1f1f1;
257
  }
 
258
  ::-webkit-scrollbar-thumb {
259
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
260
  border-radius: 4px;
261
  }
 
262
  ::-webkit-scrollbar-thumb:hover {
263
  background: #764ba2;
264
  }
265
- /* Animations */
266
  @keyframes fadeIn {
267
  from {
268
  opacity: 0;
@@ -273,31 +232,30 @@ button.primary:hover {
273
  transform: translateY(0);
274
  }
275
  }
 
276
  .animate-in {
277
  animation: fadeIn 0.6s ease-out;
278
  }
279
  """
280
 
281
  with gr.Blocks() as demo:
282
- # Header
283
  gr.HTML("""
284
  <div class="header-container animate-in">
285
- <h1>🚗 YOLOv12s Vehicle Detection</h1>
286
- <p>Detect vehicles in Egyptian streets with state-of-the-art AI • All inferences logged to DagsHub MLflow</p>
287
  </div>
288
  """)
289
 
290
  with gr.Row(elem_classes="main-content"):
291
- # Left Column - Input
292
  with gr.Column(scale=1):
293
- gr.Markdown("### 📁 Upload Media")
294
  media = gr.File(
295
  label="Drop your image or video here",
296
  file_types=[".jpg", ".jpeg", ".png", ".mp4", ".avi"],
297
  elem_classes="file-upload-area"
298
  )
299
 
300
- gr.Markdown("### 🎯 Media Type")
301
  media_type = gr.Radio(
302
  ["Image", "Video"],
303
  label="Select type",
@@ -305,23 +263,22 @@ with gr.Blocks() as demo:
305
  elem_classes="radio-group"
306
  )
307
 
308
- btn = gr.Button("🚀 Run Detection", variant="primary", size="lg", elem_classes="primary")
309
 
310
  gr.Markdown("""
311
  ---
312
- ### 📊 Features
313
  - Real-time vehicle detection
314
- - Support for images & videos
315
  - Auto-logging to DagsHub
316
  - Detailed metrics tracking
317
  """)
318
 
319
- # Right Column - Output
320
  with gr.Column(scale=2):
321
- gr.Markdown("### 🎬 Detection Results")
322
 
323
  with gr.Tabs():
324
- with gr.Tab("📸 Image Results"):
325
  with gr.Row():
326
  img_original = gr.Image(
327
  label="Original Image",
@@ -334,7 +291,7 @@ with gr.Blocks() as demo:
334
  elem_classes="output-image"
335
  )
336
 
337
- with gr.Tab("🎥 Video Results"):
338
  with gr.Row():
339
  vid_original = gr.Video(
340
  label="Original Video",
@@ -347,25 +304,22 @@ with gr.Blocks() as demo:
347
  elem_classes="output-video"
348
  )
349
 
350
- gr.Markdown("### 📈 Run Information")
351
  info = gr.Markdown(
352
- "**Ready to detect...** Upload a file and click 'Run Detection' to start!",
353
  elem_classes="info-box"
354
  )
355
 
356
- # Event Handler
357
  btn.click(
358
  fn=run_inference,
359
  inputs=[media, media_type],
360
  outputs=[img_original, img_detected, vid_original, vid_detected, info]
361
  )
362
 
363
- # Footer
364
  gr.HTML("""
365
  <div style="text-align: center; padding: 32px; color: #6b7280;">
366
- <p>Powered by YOLOv12s MLflow Tracking DagsHub Integration</p>
367
  </div>
368
  """)
369
 
370
- # Fixed for Gradio 6.0: moved css and theme to launch()
371
- demo.launch(css=css, theme=gr.themes.Soft())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import mlflow
3
  import os
 
8
  import cv2
9
  import numpy as np
10
 
 
11
  # MLflow Configuration using Secrets
 
12
  tracking_uri = os.getenv("MLFLOW_TRACKING_URI")
13
  username = os.getenv("MLFLOW_TRACKING_USERNAME")
14
  password = os.getenv("MLFLOW_TRACKING_PASSWORD")
15
 
16
  if not all([tracking_uri, username, password]):
17
+ raise ValueError("MLflow Secrets are not configured! Go to Space Settings and verify the names")
18
 
19
  os.environ["MLFLOW_TRACKING_URI"] = tracking_uri
20
  os.environ["MLFLOW_TRACKING_USERNAME"] = username
21
  os.environ["MLFLOW_TRACKING_PASSWORD"] = password
22
 
23
  mlflow.set_experiment("YOLOv12s_Inference_Logs")
24
+ print("MLflow configured successfully using secrets!")
25
 
 
26
  # Load Model
 
27
  model = YOLO("Yolo12s.pt")
28
 
 
29
  # Inference with Full MLflow Tracking
 
30
  def run_inference(media_file, media_type):
31
  if media_file is None:
32
+ return None, None, None, None, "Please upload a file first"
33
 
34
  media_path = media_file.name
35
 
 
56
  detections = len(results.boxes) if results.boxes is not None else 0
57
  mlflow.log_metric("detections_count", detections)
58
 
59
+ return img, output_img, None, None, f"Detection Complete! Objects Detected: {detections}"
60
 
61
+ else:
62
  cap = cv2.VideoCapture(media_path)
63
  fps = cap.get(cv2.CAP_PROP_FPS) or 30
64
  w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
 
91
  mlflow.log_metric("total_detections", total_detections)
92
  mlflow.log_metric("avg_detections_per_frame", total_detections / frame_count if frame_count > 0 else 0)
93
 
94
+ avg_det = total_detections / frame_count if frame_count > 0 else 0
95
+ result_message = f"Video Processing Complete! Frames: {frame_count}, Total Detections: {total_detections}, Average per Frame: {avg_det:.2f}"
96
 
 
97
  result_video = output_video
98
 
99
  return None, None, media_path, result_video, result_message
100
 
101
+ # Modern Aesthetic UI CSS
 
 
102
  css = """
103
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
104
+
105
  * {
106
  font-family: 'Inter', sans-serif;
107
  }
108
+
109
  body {
110
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
111
  }
112
+
113
  .gradio-container {
114
  max-width: 1400px !important;
115
  margin: 40px auto !important;
 
119
  padding: 0 !important;
120
  overflow: hidden !important;
121
  }
122
+
123
  .header-container {
124
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
125
  padding: 48px 40px;
126
  text-align: center;
127
  border-radius: 24px 24px 0 0;
128
  }
129
+
130
  .header-container h1 {
131
  color: white !important;
132
  font-size: 2.8em !important;
 
134
  margin: 0 0 12px 0 !important;
135
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
136
  }
137
+
138
  .header-container p {
139
  color: rgba(255, 255, 255, 0.95) !important;
140
  font-size: 1.1em !important;
141
  margin: 0 !important;
142
  }
143
+
144
  .main-content {
145
  padding: 48px 40px;
146
  }
147
+
148
  .file-upload-area {
149
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
150
  border-radius: 16px;
 
152
  border: 2px dashed #667eea;
153
  transition: all 0.3s ease;
154
  }
155
+
156
  .file-upload-area:hover {
157
  border-color: #764ba2;
158
  transform: translateY(-2px);
159
  box-shadow: 0 8px 16px rgba(102, 126, 234, 0.2);
160
  }
161
+
162
  button.primary {
163
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
164
  border: none !important;
 
171
  transition: all 0.3s ease !important;
172
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
173
  }
174
+
175
  button.primary:hover {
176
  transform: translateY(-2px) !important;
177
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.6) !important;
178
  }
179
+
180
  .radio-group label {
181
  background: white;
182
  padding: 12px 24px;
 
185
  cursor: pointer;
186
  transition: all 0.3s ease;
187
  }
188
+
189
  .radio-group label:hover {
190
  border-color: #667eea;
191
  background: #f5f7fa;
192
  }
193
+
194
  .output-image, .output-video {
195
  border-radius: 16px;
196
  overflow: hidden;
197
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
198
  background: white;
199
  }
200
+
201
  .info-box {
202
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
203
  border-radius: 12px;
204
  padding: 24px;
205
  border-left: 4px solid #667eea;
206
  }
207
+
208
  ::-webkit-scrollbar {
209
  width: 8px;
210
  }
211
+
212
  ::-webkit-scrollbar-track {
213
  background: #f1f1f1;
214
  }
215
+
216
  ::-webkit-scrollbar-thumb {
217
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
218
  border-radius: 4px;
219
  }
220
+
221
  ::-webkit-scrollbar-thumb:hover {
222
  background: #764ba2;
223
  }
224
+
225
  @keyframes fadeIn {
226
  from {
227
  opacity: 0;
 
232
  transform: translateY(0);
233
  }
234
  }
235
+
236
  .animate-in {
237
  animation: fadeIn 0.6s ease-out;
238
  }
239
  """
240
 
241
  with gr.Blocks() as demo:
 
242
  gr.HTML("""
243
  <div class="header-container animate-in">
244
+ <h1>YOLOv12s Vehicle Detection</h1>
245
+ <p>Detect vehicles in Egyptian streets with state-of-the-art AI</p>
246
  </div>
247
  """)
248
 
249
  with gr.Row(elem_classes="main-content"):
 
250
  with gr.Column(scale=1):
251
+ gr.Markdown("### Upload Media")
252
  media = gr.File(
253
  label="Drop your image or video here",
254
  file_types=[".jpg", ".jpeg", ".png", ".mp4", ".avi"],
255
  elem_classes="file-upload-area"
256
  )
257
 
258
+ gr.Markdown("### Media Type")
259
  media_type = gr.Radio(
260
  ["Image", "Video"],
261
  label="Select type",
 
263
  elem_classes="radio-group"
264
  )
265
 
266
+ btn = gr.Button("Run Detection", variant="primary", size="lg", elem_classes="primary")
267
 
268
  gr.Markdown("""
269
  ---
270
+ ### Features
271
  - Real-time vehicle detection
272
+ - Support for images and videos
273
  - Auto-logging to DagsHub
274
  - Detailed metrics tracking
275
  """)
276
 
 
277
  with gr.Column(scale=2):
278
+ gr.Markdown("### Detection Results")
279
 
280
  with gr.Tabs():
281
+ with gr.Tab("Image Results"):
282
  with gr.Row():
283
  img_original = gr.Image(
284
  label="Original Image",
 
291
  elem_classes="output-image"
292
  )
293
 
294
+ with gr.Tab("Video Results"):
295
  with gr.Row():
296
  vid_original = gr.Video(
297
  label="Original Video",
 
304
  elem_classes="output-video"
305
  )
306
 
307
+ gr.Markdown("### Run Information")
308
  info = gr.Markdown(
309
+ "Ready to detect... Upload a file and click Run Detection to start!",
310
  elem_classes="info-box"
311
  )
312
 
 
313
  btn.click(
314
  fn=run_inference,
315
  inputs=[media, media_type],
316
  outputs=[img_original, img_detected, vid_original, vid_detected, info]
317
  )
318
 
 
319
  gr.HTML("""
320
  <div style="text-align: center; padding: 32px; color: #6b7280;">
321
+ <p>Powered by YOLOv12s - MLflow Tracking - DagsHub Integration</p>
322
  </div>
323
  """)
324
 
325
+ demo.launch(css=css, theme=gr.themes.Soft())