lucid-hf commited on
Commit
fa19cf8
·
verified ·
1 Parent(s): 7c35a94

CI: deploy Docker/PDM Space

Browse files
pdm.lock CHANGED
@@ -5,7 +5,7 @@
5
  groups = ["default", "dev"]
6
  strategy = []
7
  lock_version = "4.5.0"
8
- content_hash = "sha256:1d312cf4f8d0ef95142688d9b41975eea7bae04876d293480ed8b68062da4b05"
9
 
10
  [[metadata.targets]]
11
  requires_python = "==3.11.*"
@@ -1554,3 +1554,13 @@ files = [
1554
  {file = "watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f"},
1555
  {file = "watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282"},
1556
  ]
 
 
 
 
 
 
 
 
 
 
 
5
  groups = ["default", "dev"]
6
  strategy = []
7
  lock_version = "4.5.0"
8
+ content_hash = "sha256:289ac07ce37c34043f1c46e3239eabc20812a81c95ce882483c35901afab3221"
9
 
10
  [[metadata.targets]]
11
  requires_python = "==3.11.*"
 
1554
  {file = "watchdog-6.0.0-py3-none-win_ia64.whl", hash = "sha256:a1914259fa9e1454315171103c6a30961236f508b9b623eae470268bbcc6a22f"},
1555
  {file = "watchdog-6.0.0.tar.gz", hash = "sha256:9ddf7c82fda3ae8e24decda1338ede66e1c99883db93711d8fb941eaa2d8c282"},
1556
  ]
1557
+
1558
+ [[package]]
1559
+ name = "yt-dlp"
1560
+ version = "2025.10.22"
1561
+ requires_python = ">=3.10"
1562
+ summary = "A feature-rich command-line audio/video downloader"
1563
+ files = [
1564
+ {file = "yt_dlp-2025.10.22-py3-none-any.whl", hash = "sha256:9c803a9598859f91d0d5bd3337f1506ecb40bbe97f6efbe93bc4461fed344fb2"},
1565
+ {file = "yt_dlp-2025.10.22.tar.gz", hash = "sha256:db2d48133222b1d9508c6de757859c24b5cefb9568cf68ccad85dac20b07f77b"},
1566
+ ]
pyproject.toml CHANGED
@@ -14,6 +14,7 @@ dependencies = [
14
  "torch>=2.8.0",
15
  "pandas>=2.3.2",
16
  "opencv-python>=4.12.0.88",
 
17
  ]
18
  requires-python = "==3.11.*"
19
  readme = "README.md"
 
14
  "torch>=2.8.0",
15
  "pandas>=2.3.2",
16
  "opencv-python>=4.12.0.88",
17
+ "yt-dlp>=2025.10.22",
18
  ]
19
  requires-python = "==3.11.*"
20
  readme = "README.md"
services/app_service/pages/signal_watch.py CHANGED
@@ -1,6 +1,11 @@
1
  import tempfile
2
  import time
3
  from pathlib import Path
 
 
 
 
 
4
 
5
  import cv2
6
  import numpy as np
@@ -57,6 +62,129 @@ MODEL_ENTRIES = _discover_model_entries()
57
 
58
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  @st.cache_resource
62
  def load_model(model_key: str, device: str = DEVICE):
@@ -77,7 +205,6 @@ def load_model(model_key: str, device: str = DEVICE):
77
  )
78
  return YOLO(str(weight_path))
79
 
80
-
81
  def draw_yolo_dets(frame_bgr, result, show_score=True):
82
  out = frame_bgr.copy()
83
  boxes = getattr(result, "boxes", None)
@@ -119,11 +246,37 @@ if VIDEO_DIR.exists():
119
  if p.suffix.lower() in {".mp4", ".mov", ".avi", ".mkv"}:
120
  video_map[p.name] = str(p)
121
 
122
- source_options = ["Webcam (0)"] + list(video_map.keys()) + ["Custom URL…"]
123
  src_choice = st.sidebar.selectbox("Source", source_options, index=0)
124
 
125
  custom_url = None
126
- if src_choice == "Custom URL…":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  custom_url = st.sidebar.text_input(
128
  "RTSP/HTTP URL", placeholder="rtsp://... or https://..."
129
  )
@@ -148,7 +301,14 @@ model_label = st.sidebar.selectbox("Model", available_model_labels, index=0)
148
  model_key = label_to_key.get(model_label, "deim")
149
  confidence_threshold = st.sidebar.slider("Minimum Confidence", 0.0, 1.0, 0.5, 0.01)
150
  frame_stride = st.sidebar.slider("Process every Nth frame", 1, 10, 3, 1)
151
- max_seconds = st.sidebar.slider("Max seconds (webcam/live)", 3, 60, 12, 1)
 
 
 
 
 
 
 
152
  show_live_preview = st.sidebar.checkbox(
153
  "Show live preview",
154
  value=True,
@@ -164,15 +324,37 @@ if show_live_preview:
164
  40,
165
  help="Frames are downscaled before streaming to keep payloads small.",
166
  )
167
- run_detection = st.sidebar.button("🎥 Run Detection", use_container_width=True)
 
 
 
 
 
168
 
169
 
170
  # ---------- Main UI logic ----------
171
 
 
 
 
172
 
173
  def resolve_source():
174
  if src_choice == "Webcam (0)":
175
  return 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  if src_choice == "Custom URL…":
177
  return custom_url.strip() if custom_url else None
178
  return video_map.get(src_choice)
@@ -204,12 +386,31 @@ def run_video_feed_detection(
204
  st.error(str(exc))
205
  return
206
 
 
 
 
207
  cap = cv2.VideoCapture(cap_source)
208
  if not cap.isOpened():
209
  st.error("Failed to open the selected source.")
210
  return
211
 
212
- is_file = isinstance(cap_source, str) and Path(str(cap_source)).exists()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
214
  total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
215
 
@@ -268,16 +469,23 @@ def run_video_feed_detection(
268
 
269
  i += 1
270
 
271
- # Update progress more frequently for better UX
272
- if is_file and total:
273
- progress = min(i / total, 1.0)
274
- prog.progress(progress, text=f"Processing… {i}/{total}")
 
 
 
 
 
 
275
  else:
276
- elapsed = time.time() - start_t
277
- progress = min(elapsed / max(1, max_seconds), 1.0)
278
- prog.progress(progress, text=f"Live… {int(elapsed)}s")
 
279
  if elapsed >= max_seconds:
280
- break
281
 
282
  # Add small delay to prevent overwhelming the system
283
  if not is_file: # Only for live sources
@@ -291,7 +499,8 @@ def run_video_feed_detection(
291
  if writer is not None:
292
  writer.release()
293
 
294
- st.success("Done!")
 
295
  if out_path and out_path.exists():
296
  st.video(str(out_path))
297
  with open(out_path, "rb") as f:
@@ -317,4 +526,4 @@ if run_detection:
317
  preview_max_width=preview_width,
318
  )
319
  else:
320
- st.info("Pick a video source from the sidebar and click **Run Detection**.")
 
1
  import tempfile
2
  import time
3
  from pathlib import Path
4
+ import re
5
+ import subprocess
6
+ import json
7
+ import sys
8
+ import shutil
9
 
10
  import cv2
11
  import numpy as np
 
62
 
63
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
64
 
65
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
66
+
67
+
68
+ def find_ytdlp_executable() -> str | None:
69
+ """Find the yt-dlp executable, checking multiple possible locations."""
70
+ # First try the system PATH
71
+ ytdlp_path = shutil.which('yt-dlp')
72
+ if ytdlp_path:
73
+ return ytdlp_path
74
+
75
+ # Try common virtual environment locations
76
+ venv_paths = [
77
+ Path(sys.executable).parent / "yt-dlp",
78
+ Path(sys.executable).parent.parent / "bin" / "yt-dlp",
79
+ Path(__file__).parents[3] / ".venv" / "bin" / "yt-dlp",
80
+ Path(__file__).parents[3] / ".venv" / "Scripts" / "yt-dlp.exe", # Windows
81
+ ]
82
+
83
+ for path in venv_paths:
84
+ if path.exists() and path.is_file():
85
+ return str(path)
86
+
87
+ return None
88
+
89
+
90
+ def is_youtube_url(url: str) -> bool:
91
+ """Check if the URL is a YouTube URL."""
92
+ youtube_patterns = [
93
+ r'(?:https?://)?(?:www\.)?youtube\.com/watch\?v=',
94
+ r'(?:https?://)?(?:www\.)?youtu\.be/',
95
+ r'(?:https?://)?(?:www\.)?youtube\.com/live/',
96
+ r'(?:https?://)?(?:www\.)?youtube\.com/embed/',
97
+ ]
98
+ return any(re.search(pattern, url) for pattern in youtube_patterns)
99
+
100
+
101
+ def check_ytdlp_available() -> bool:
102
+ """Check if yt-dlp is available on the system."""
103
+ ytdlp_path = find_ytdlp_executable()
104
+ if not ytdlp_path:
105
+ return False
106
+
107
+ try:
108
+ result = subprocess.run([ytdlp_path, '--version'], capture_output=True, text=True, timeout=5)
109
+ return result.returncode == 0
110
+ except (FileNotFoundError, subprocess.TimeoutExpired):
111
+ return False
112
+
113
+
114
+ def extract_youtube_stream_url(url: str) -> str | None:
115
+ """Extract the actual stream URL from a YouTube URL using yt-dlp."""
116
+ # Find yt-dlp executable
117
+ ytdlp_path = find_ytdlp_executable()
118
+ if not ytdlp_path:
119
+ st.error("yt-dlp is not installed or not available in PATH.")
120
+ st.info("Please install yt-dlp: `pip install yt-dlp` or `brew install yt-dlp`")
121
+ return None
122
+
123
+ # Verify it's working
124
+ if not check_ytdlp_available():
125
+ st.error("yt-dlp found but not working properly.")
126
+ return None
127
+
128
+ try:
129
+ # Show progress message
130
+ with st.spinner("Extracting YouTube stream URL..."):
131
+ # Try multiple format options
132
+ format_options = [
133
+ 'best[height<=720]',
134
+ 'best[height<=480]',
135
+ 'best',
136
+ 'worst'
137
+ ]
138
+
139
+ for fmt in format_options:
140
+ cmd = [
141
+ ytdlp_path,
142
+ '--get-url',
143
+ '--format', fmt,
144
+ '--no-playlist',
145
+ '--no-warnings',
146
+ url
147
+ ]
148
+
149
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
150
+
151
+ if result.returncode == 0:
152
+ stream_url = result.stdout.strip()
153
+ if stream_url and stream_url.startswith('http'):
154
+ st.success(f"Successfully extracted YouTube stream URL! (format: {fmt})")
155
+ return stream_url
156
+ else:
157
+ st.warning(f"Invalid stream URL extracted with format {fmt}: {stream_url}")
158
+ else:
159
+ st.warning(f"yt-dlp failed with format {fmt}: {result.stderr}")
160
+
161
+ # If all formats failed, try a different approach
162
+ st.warning("Trying alternative extraction method...")
163
+ cmd = [
164
+ ytdlp_path,
165
+ '--get-url',
166
+ '--format', 'best',
167
+ '--no-playlist',
168
+ url
169
+ ]
170
+
171
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
172
+
173
+ if result.returncode == 0:
174
+ stream_url = result.stdout.strip()
175
+ if stream_url and stream_url.startswith('http'):
176
+ st.success("Successfully extracted YouTube stream URL with fallback method!")
177
+ return stream_url
178
+
179
+ except subprocess.TimeoutExpired:
180
+ st.error("Timeout while extracting YouTube stream URL. The video might be unavailable.")
181
+ except FileNotFoundError:
182
+ st.error("yt-dlp not found. Please install it: pip install yt-dlp")
183
+ except Exception as e:
184
+ st.error(f"Error extracting YouTube stream URL: {str(e)}")
185
+
186
+ return None
187
+
188
 
189
  @st.cache_resource
190
  def load_model(model_key: str, device: str = DEVICE):
 
205
  )
206
  return YOLO(str(weight_path))
207
 
 
208
  def draw_yolo_dets(frame_bgr, result, show_score=True):
209
  out = frame_bgr.copy()
210
  boxes = getattr(result, "boxes", None)
 
246
  if p.suffix.lower() in {".mp4", ".mov", ".avi", ".mkv"}:
247
  video_map[p.name] = str(p)
248
 
249
+ source_options = ["Webcam (0)"] + list(video_map.keys()) + ["YouTube URL", "Custom URL…"]
250
  src_choice = st.sidebar.selectbox("Source", source_options, index=0)
251
 
252
  custom_url = None
253
+ youtube_url = None
254
+ if src_choice == "YouTube URL":
255
+ youtube_url = st.sidebar.text_input(
256
+ "YouTube URL",
257
+ placeholder="https://www.youtube.com/watch?v=...",
258
+ value="https://www.youtube.com/watch?v=57w2gYXjRic"
259
+ )
260
+ if st.sidebar.button("Test YouTube URL", help="Test if the YouTube URL can be processed"):
261
+ if youtube_url and youtube_url.strip():
262
+ st.info(f"Testing URL: {youtube_url.strip()}")
263
+
264
+ # Debug: Show yt-dlp path
265
+ ytdlp_path = find_ytdlp_executable()
266
+ if ytdlp_path:
267
+ st.info(f"Found yt-dlp at: {ytdlp_path}")
268
+ else:
269
+ st.warning("yt-dlp executable not found")
270
+
271
+ stream_url = extract_youtube_stream_url(youtube_url.strip())
272
+ if stream_url:
273
+ st.success("✅ YouTube URL is valid and can be processed!")
274
+ st.info(f"Stream URL: {stream_url[:100]}...")
275
+ else:
276
+ st.error("❌ Failed to process YouTube URL")
277
+ else:
278
+ st.warning("Please enter a YouTube URL first")
279
+ elif src_choice == "Custom URL…":
280
  custom_url = st.sidebar.text_input(
281
  "RTSP/HTTP URL", placeholder="rtsp://... or https://..."
282
  )
 
301
  model_key = label_to_key.get(model_label, "deim")
302
  confidence_threshold = st.sidebar.slider("Minimum Confidence", 0.0, 1.0, 0.5, 0.01)
303
  frame_stride = st.sidebar.slider("Process every Nth frame", 1, 10, 3, 1)
304
+
305
+ # Time limit options for live streams
306
+ unlimited_mode = st.sidebar.checkbox("🔄 Unlimited Live Mode", help="Run detection indefinitely (use with caution)")
307
+ if unlimited_mode:
308
+ max_seconds = None # No time limit
309
+ st.sidebar.info("⚠️ Running in unlimited mode - use stop button to end")
310
+ else:
311
+ max_seconds = st.sidebar.slider("Max seconds (webcam/live)", 3, 60, 12, 1)
312
  show_live_preview = st.sidebar.checkbox(
313
  "Show live preview",
314
  value=True,
 
324
  40,
325
  help="Frames are downscaled before streaming to keep payloads small.",
326
  )
327
+
328
+ col1, col2 = st.sidebar.columns(2)
329
+ with col1:
330
+ run_detection = st.button("🎥 Run Detection", use_container_width=True)
331
+ with col2:
332
+ stop_detection = st.button("⏹️ Stop", use_container_width=True, help="Stop current detection")
333
 
334
 
335
  # ---------- Main UI logic ----------
336
 
337
+ # Initialize session state for stop functionality
338
+ if 'stop_processing' not in st.session_state:
339
+ st.session_state.stop_processing = False
340
 
341
  def resolve_source():
342
  if src_choice == "Webcam (0)":
343
  return 0
344
+ if src_choice == "YouTube URL":
345
+ if youtube_url and youtube_url.strip():
346
+ st.info(f"Processing YouTube URL: {youtube_url.strip()}")
347
+ # Extract the actual stream URL from YouTube
348
+ stream_url = extract_youtube_stream_url(youtube_url.strip())
349
+ if stream_url:
350
+ st.info(f"Extracted stream URL: {stream_url[:50]}...")
351
+ return stream_url
352
+ else:
353
+ st.error("Failed to extract YouTube stream URL. Please check the URL and try again.")
354
+ return None
355
+ else:
356
+ st.warning("Please enter a YouTube URL.")
357
+ return None
358
  if src_choice == "Custom URL…":
359
  return custom_url.strip() if custom_url else None
360
  return video_map.get(src_choice)
 
386
  st.error(str(exc))
387
  return
388
 
389
+ # Handle YouTube URLs specially
390
+ is_youtube = isinstance(cap_source, str) and is_youtube_url(cap_source)
391
+
392
  cap = cv2.VideoCapture(cap_source)
393
  if not cap.isOpened():
394
  st.error("Failed to open the selected source.")
395
  return
396
 
397
+ # Set buffer size for live streams to reduce latency
398
+ if is_youtube or isinstance(cap_source, str):
399
+ cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
400
+
401
+ # Check if it's a local file (not a URL)
402
+ is_file = False
403
+ if isinstance(cap_source, str):
404
+ # If it looks like a URL (starts with http/https/rtsp), it's not a file
405
+ if cap_source.startswith(('http://', 'https://', 'rtsp://')):
406
+ is_file = False
407
+ else:
408
+ # Only check if it's a file if it doesn't look like a URL
409
+ try:
410
+ is_file = Path(cap_source).exists()
411
+ except (OSError, ValueError):
412
+ # Handle cases where the path is too long or invalid
413
+ is_file = False
414
  fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
415
  total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
416
 
 
469
 
470
  i += 1
471
 
472
+ if is_file and total:
473
+ prog.progress(min(i / total, 1.0), text=f"Processing… {i}/{total}")
474
+ else:
475
+ elapsed = time.time() - start_t
476
+ stream_type = "YouTube" if is_youtube else "Live"
477
+
478
+ if max_seconds is None:
479
+ # Unlimited mode - show elapsed time without progress limit
480
+ prog.progress(0.0, text=f"{stream_type}… {int(elapsed)}s (unlimited)")
481
+ # In unlimited mode, continue indefinitely until manually stopped
482
  else:
483
+ # Limited mode - show progress and check time limit
484
+ prog.progress(
485
+ min(elapsed / max(1, max_seconds), 1.0), text=f"{stream_type}… {int(elapsed)}s"
486
+ )
487
  if elapsed >= max_seconds:
488
+ return
489
 
490
  # Add small delay to prevent overwhelming the system
491
  if not is_file: # Only for live sources
 
499
  if writer is not None:
500
  writer.release()
501
 
502
+ stream_type = "YouTube" if is_youtube else ("Live" if not is_file else "File")
503
+ st.success(f"Done processing {stream_type} stream!")
504
  if out_path and out_path.exists():
505
  st.video(str(out_path))
506
  with open(out_path, "rb") as f:
 
526
  preview_max_width=preview_width,
527
  )
528
  else:
529
+ st.info("Pick a video source from the sidebar (including YouTube URLs) and click **Run Detection**.")