Thai Quang Nguyen commited on
Commit
bb24dbf
·
1 Parent(s): 4f55570

update for streaming youtube url

Browse files
Files changed (2) hide show
  1. app.py +155 -40
  2. requirements.txt +2 -0
app.py CHANGED
@@ -5,6 +5,7 @@ from qdrant_client import QdrantClient
5
  import subprocess
6
  import os
7
  import uuid
 
8
 
9
  # Setup CLIP
10
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -18,37 +19,145 @@ client = QdrantClient(
18
  COLLECTION_NAME = "video_segments"
19
 
20
  # Paths
21
- VIDEO_BASE_DIR = "/project/phan/tqn/RAG-VideoReferencing/"
22
  CLIP_OUTPUT_DIR = "generated_clips"
23
  os.makedirs(CLIP_OUTPUT_DIR, exist_ok=True)
24
 
25
- DEFAULT_VIDEO_FILENAME = "temp_video_0.mp4"
26
- DEFAULT_VIDEO_PATH = os.path.join(VIDEO_BASE_DIR, DEFAULT_VIDEO_FILENAME)
27
-
28
-
29
- def extract_video_clip(input_path, start_time, end_time):
 
 
 
 
 
 
 
 
 
 
30
  """
31
- Use ffmpeg to extract a clip from the video.
32
  """
33
  clip_name = f"clip_{uuid.uuid4().hex}.mp4"
34
  output_path = os.path.join(CLIP_OUTPUT_DIR, clip_name)
35
-
36
- command = [
37
- "ffmpeg",
38
- "-ss", str(start_time),
39
- "-i", input_path,
40
- "-to", str(end_time - start_time),
41
- "-c", "copy",
42
- output_path,
43
- "-y" # Overwrite if exists
44
- ]
45
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  try:
47
- subprocess.run(command, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
48
- return output_path
49
- except subprocess.CalledProcessError as e:
50
- print(f"[ERROR] FFmpeg failed: {e}")
51
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  def time_to_seconds(time_str):
54
  h, m, s = time_str.split(':')
@@ -62,8 +171,8 @@ def search_and_clip_video(text_query: str):
62
  text_tokens = clip.tokenize([text_query]).to(device)
63
  text_features = model.encode_text(text_tokens)
64
  text_features /= text_features.norm(dim=1, keepdim=True)
65
-
66
- # Query Qdrant
67
  search_result = client.search(
68
  collection_name=COLLECTION_NAME,
69
  query_vector=text_features.cpu().numpy()[0].tolist(),
@@ -72,34 +181,40 @@ def search_and_clip_video(text_query: str):
72
 
73
  if not search_result:
74
  print("[WARN] No result found.")
75
- return DEFAULT_VIDEO_PATH
76
 
77
  hit = search_result[0]
78
  start = hit.payload.get("start", 0)
79
  end = hit.payload.get("end", 0)
80
- start = time_to_seconds(start)
81
- end = time_to_seconds(end)
82
- video_filename = hit.payload.get("video_path", DEFAULT_VIDEO_FILENAME)
83
 
84
- full_video_path = os.path.join(VIDEO_BASE_DIR, video_filename)
 
85
 
86
  print(f"[INFO] Found: {video_filename} ({start} - {end})")
 
 
 
 
 
 
 
87
 
88
- # Extract clip using ffmpeg
89
- clip_path = extract_video_clip(full_video_path, float(start), float(end))
90
  if clip_path and os.path.exists(clip_path):
91
  print(f"[INFO] Returning clip: {clip_path}")
92
- return clip_path
93
  else:
94
  print("[WARN] Failed to extract clip, returning default video.")
95
- return DEFAULT_VIDEO_PATH
96
 
97
-
98
- # Fallback test interface
99
  def get_test_video():
100
- print("[INFO] Returning test video path")
101
- return DEFAULT_VIDEO_PATH
102
-
103
 
104
  # Gradio Interfaces
105
  search_demo = gr.Interface(
@@ -124,4 +239,4 @@ demo = gr.TabbedInterface(
124
  )
125
 
126
  if __name__ == "__main__":
127
- demo.launch(share=True)
 
5
  import subprocess
6
  import os
7
  import uuid
8
+ import yt_dlp
9
 
10
  # Setup CLIP
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
19
  COLLECTION_NAME = "video_segments"
20
 
21
  # Paths
 
22
  CLIP_OUTPUT_DIR = "generated_clips"
23
  os.makedirs(CLIP_OUTPUT_DIR, exist_ok=True)
24
 
25
+ # YouTube URLs mapping
26
+ VIDEO_URLS = {
27
+ "temp_video_0.mp4": 'https://www.youtube.com/watch?v=9CGGh6ivg68',
28
+ "temp_video_1.mp4": 'https://www.youtube.com/watch?v=WXoOohWU28Y',
29
+ "temp_video_2.mp4": 'https://www.youtube.com/watch?v=TV-DjM8242s',
30
+ "temp_video_3.mp4": 'https://www.youtube.com/watch?v=rCVlIVKqqGE',
31
+ "temp_video_4.mp4": 'https://www.youtube.com/watch?v=lb_5AdUpfuA',
32
+ "temp_video_5.mp4": 'https://www.youtube.com/watch?v=FCQ-rih6cHY',
33
+ "temp_video_6.mp4": 'https://www.youtube.com/watch?v=eQ6UE968Xe4',
34
+ "temp_video_7.mp4": 'https://www.youtube.com/watch?v=eFgkZKhNUdM'
35
+ }
36
+
37
+ DEFAULT_VIDEO_URL = VIDEO_URLS["temp_video_0.mp4"]
38
+
39
+ def extract_video_clip(video_url, start_time, end_time):
40
  """
41
+ Use yt-dlp and ffmpeg to extract a clip directly from YouTube.
42
  """
43
  clip_name = f"clip_{uuid.uuid4().hex}.mp4"
44
  output_path = os.path.join(CLIP_OUTPUT_DIR, clip_name)
45
+ duration = end_time - start_time
46
+
47
+ print(f"[INFO] Attempting to extract clip from {video_url} ({start_time} - {end_time})")
48
+
49
+ # Method 1: Use youtube-dl with ffmpeg
50
+ try:
51
+ # First, get the best direct URL from youtube-dl
52
+ ydl_opts = {
53
+ 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
54
+ 'quiet': True
55
+ }
56
+
57
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
58
+ info = ydl.extract_info(video_url, download=False)
59
+ formats = info.get('formats', [info])
60
+
61
+ # Get the best format URL
62
+ best_url = None
63
+ for f in formats:
64
+ if f.get('ext') == 'mp4' and f.get('url'):
65
+ best_url = f['url']
66
+ break
67
+
68
+ if not best_url and info.get('url'):
69
+ best_url = info['url']
70
+
71
+ if not best_url:
72
+ print("[WARN] Could not find a suitable direct URL")
73
+ raise Exception("No suitable URL found")
74
+
75
+ # Use ffmpeg to download the segment
76
+ command = [
77
+ "ffmpeg",
78
+ "-ss", str(start_time),
79
+ "-i", best_url,
80
+ "-t", str(duration),
81
+ "-c:v", "libx264",
82
+ "-c:a", "aac",
83
+ "-preset", "ultrafast",
84
+ output_path,
85
+ "-y"
86
+ ]
87
+
88
+ print(f"[INFO] Running ffmpeg command: {' '.join(command)}")
89
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
90
+
91
+ if result.returncode != 0:
92
+ print(f"[WARN] ffmpeg command failed with code {result.returncode}")
93
+ print(f"[WARN] stderr: {result.stderr.decode('utf-8')}")
94
+ raise Exception(f"ffmpeg failed with code {result.returncode}")
95
+
96
+ if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
97
+ print(f"[INFO] Successfully extracted clip to {output_path}")
98
+ return output_path
99
+ else:
100
+ print(f"[WARN] Output file missing or empty: {output_path}")
101
+ raise Exception("Output file missing or empty")
102
+
103
+ except Exception as e:
104
+ print(f"[ERROR] Method 1 failed: {str(e)}")
105
+
106
+ # Method 2: Download whole video first
107
  try:
108
+ print("[INFO] Trying Method 2: Download full video first")
109
+ temp_video = os.path.join(CLIP_OUTPUT_DIR, f"temp_{uuid.uuid4().hex}.mp4")
110
+
111
+ ydl_opts = {
112
+ 'format': 'best[ext=mp4]/best',
113
+ 'outtmpl': temp_video,
114
+ 'quiet': True
115
+ }
116
+
117
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
118
+ ydl.download([video_url])
119
+
120
+ if os.path.exists(temp_video) and os.path.getsize(temp_video) > 0:
121
+ # Extract clip from the downloaded video
122
+ command = [
123
+ "ffmpeg",
124
+ "-ss", str(start_time),
125
+ "-i", temp_video,
126
+ "-t", str(duration),
127
+ "-c:v", "copy",
128
+ "-c:a", "copy",
129
+ output_path,
130
+ "-y"
131
+ ]
132
+
133
+ print(f"[INFO] Running ffmpeg command: {' '.join(command)}")
134
+ result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
135
+
136
+ # Clean up temp file regardless of success
137
+ try:
138
+ os.remove(temp_video)
139
+ print(f"[INFO] Removed temporary file {temp_video}")
140
+ except Exception as cleanup_error:
141
+ print(f"[WARN] Failed to remove temp file: {cleanup_error}")
142
+
143
+ if result.returncode != 0:
144
+ print(f"[WARN] ffmpeg command failed with code {result.returncode}")
145
+ print(f"[WARN] stderr: {result.stderr.decode('utf-8')}")
146
+ raise Exception(f"ffmpeg failed with code {result.returncode}")
147
+
148
+ if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
149
+ print(f"[INFO] Successfully extracted clip to {output_path}")
150
+ return output_path
151
+ else:
152
+ print(f"[WARN] Output file missing or empty: {output_path}")
153
+ raise Exception("Output file missing or empty")
154
+
155
+ except Exception as e:
156
+ print(f"[ERROR] Method 2 failed: {str(e)}")
157
+
158
+ # Both methods failed
159
+ print("[ERROR] All extraction methods failed")
160
+ return None
161
 
162
  def time_to_seconds(time_str):
163
  h, m, s = time_str.split(':')
 
171
  text_tokens = clip.tokenize([text_query]).to(device)
172
  text_features = model.encode_text(text_tokens)
173
  text_features /= text_features.norm(dim=1, keepdim=True)
174
+
175
+ # Always use the original search method
176
  search_result = client.search(
177
  collection_name=COLLECTION_NAME,
178
  query_vector=text_features.cpu().numpy()[0].tolist(),
 
181
 
182
  if not search_result:
183
  print("[WARN] No result found.")
184
+ return DEFAULT_VIDEO_URL
185
 
186
  hit = search_result[0]
187
  start = hit.payload.get("start", 0)
188
  end = hit.payload.get("end", 0)
189
+ start = time_to_seconds(start) if isinstance(start, str) else float(start)
190
+ end = time_to_seconds(end) if isinstance(end, str) else float(end)
191
+ video_filename = hit.payload.get("video_path", "temp_video_0.mp4")
192
 
193
+ # Get YouTube URL from filename
194
+ video_url = VIDEO_URLS.get(video_filename, DEFAULT_VIDEO_URL)
195
 
196
  print(f"[INFO] Found: {video_filename} ({start} - {end})")
197
+ print(f"[INFO] Using YouTube URL: {video_url}")
198
+
199
+ # Handle very short clips or invalid timestamps
200
+ if end <= start or end - start < 1.0:
201
+ print("[WARN] Invalid clip duration, using default start/end times")
202
+ start = max(0, start - 5) # Start 5 seconds before
203
+ end = start + 10 # 10 second clip
204
 
205
+ # Extract clip from YouTube
206
+ clip_path = extract_video_clip(video_url, float(start), float(end))
207
  if clip_path and os.path.exists(clip_path):
208
  print(f"[INFO] Returning clip: {clip_path}")
209
+ return clip_path
210
  else:
211
  print("[WARN] Failed to extract clip, returning default video.")
212
+ return DEFAULT_VIDEO_URL
213
 
214
+ # Function to get a test video
 
215
  def get_test_video():
216
+ print("[INFO] Returning test YouTube URL")
217
+ return DEFAULT_VIDEO_URL
 
218
 
219
  # Gradio Interfaces
220
  search_demo = gr.Interface(
 
239
  )
240
 
241
  if __name__ == "__main__":
242
+ demo.launch(share=True)
requirements.txt CHANGED
@@ -5,4 +5,6 @@ opencv-python
5
  qdrant-client
6
  uuid
7
  git+https://github.com/openai/CLIP.git
 
 
8
  ffmpeg-python
 
5
  qdrant-client
6
  uuid
7
  git+https://github.com/openai/CLIP.git
8
+ ffmpeg-python
9
+ yt-dlp
10
  ffmpeg-python