Bùi Thanh Lâm commited on
Commit
93ee7bf
·
verified ·
1 Parent(s): 9286a2f

Update download_dataset.py

Browse files
Files changed (1) hide show
  1. download_dataset.py +23 -23
download_dataset.py CHANGED
@@ -1,17 +1,17 @@
1
  """
2
- download_dataset.py — Tải xử ViLAP dataset từ YouTube.
3
 
4
- Yêu cầu:
5
  pip install yt-dlp mediapipe opencv-python librosa scipy numpy
6
 
7
- Cách dùng:
8
- # Tải tất cả (train + val + test)
9
  python download_dataset.py --output ./vilap_data
10
 
11
- # Chỉ tải test split
12
  python download_dataset.py --output ./vilap_data --splits test
13
 
14
- # Chỉ tải một số videos cụ thể
15
  python download_dataset.py --output ./vilap_data --video_ids 3p7dFrIx5bk xwsPD6xiPbI
16
  """
17
 
@@ -33,7 +33,7 @@ def load_sources():
33
 
34
 
35
  def clips_for_splits(splits):
36
- """Trả về dict {video_id: [clip_ids]} cho các split được chọn."""
37
  clips = {}
38
  for split in splits:
39
  path = FILELISTS_DIR / f'{split}.txt'
@@ -50,7 +50,7 @@ def clips_for_splits(splits):
50
 
51
  # ─── Step 1: Download raw video ───────────────────────────────────────────────
52
  def download_video(url, out_path):
53
- """Tải video với yt-dlp, chất lượng tốt nhất dưới 1080p."""
54
  cmd = [
55
  'yt-dlp', '-f', 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best',
56
  '--merge-output-format', 'mp4',
@@ -64,9 +64,9 @@ def download_video(url, out_path):
64
 
65
  # ─── Step 2: Cut clips ────────────────────────────────────────────────────────
66
  def cut_clips(raw_video, clips_dir, clip_ids, fps=25):
67
- """Cắt video thành clips 5 giây theo clip index."""
68
  clips_dir.mkdir(parents=True, exist_ok=True)
69
- # Lấy duration
70
  probe = subprocess.run(
71
  ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
72
  '-of', 'default=noprint_wrappers=1:nokey=1', str(raw_video)],
@@ -78,7 +78,7 @@ def cut_clips(raw_video, clips_dir, clip_ids, fps=25):
78
  print(f' [WARN] cannot get duration for {raw_video.name}')
79
  return
80
 
81
- # Đọc clip indices từ tên như "spk_c0017" → index 17
82
  for clip_id in clip_ids:
83
  idx = int(clip_id.split('_c')[-1])
84
  start_sec = idx * 5.0
@@ -99,7 +99,7 @@ def cut_clips(raw_video, clips_dir, clip_ids, fps=25):
99
 
100
  # ─── Step 3: Extract faces ────────────────────────────────────────────────────
101
  def extract_faces(clips_dir, face_dir, clip_id):
102
- """Dùng MediaPipe Face Detection để crop resize khuôn mặt 128x128."""
103
  try:
104
  import cv2, mediapipe as mp
105
  except ImportError:
@@ -129,7 +129,7 @@ def extract_faces(clips_dir, face_dir, clip_id):
129
  y1 = max(0, int(bb.ymin * h))
130
  x2 = min(w, int((bb.xmin + bb.width) * w))
131
  y2 = min(h, int((bb.ymin + bb.height) * h))
132
- # Thêm margin 20%
133
  margin_x = int((x2 - x1) * 0.2)
134
  margin_y = int((y2 - y1) * 0.2)
135
  x1 = max(0, x1 - margin_x); y1 = max(0, y1 - margin_y)
@@ -145,7 +145,7 @@ def extract_faces(clips_dir, face_dir, clip_id):
145
 
146
  # ─── Step 4: Extract landmarks ───────────────────────────────────────────────
147
  def extract_landmarks(face_dir, lm_dir, clip_id):
148
- """Dùng MediaPipe Face Mesh để extract 478 landmarks, lưu pose + content."""
149
  try:
150
  import cv2, mediapipe as mp
151
  import numpy as np
@@ -166,11 +166,11 @@ def extract_landmarks(face_dir, lm_dir, clip_id):
166
  CONTENT_IDS = [
167
  61,185,40,39,37,0,267,269,270,409,291,375,321,405,314,17,84,181,91,146,
168
  78,191,80,81,82,13,312,311,310,415,308,324,318,402,317,14,87,178,88,95,
169
- # jaw (inner portion)
170
  162,127,234,93,132,58,172,136,150,149,176,148,152,
171
  377,400,378,379,
172
  ]
173
- # Dùng đúng 57 content points theo IP-LAP convention
174
  CONTENT_IDS = [
175
  61,185,40,39,37,0,267,269,270,409,291,375,321,405,314,17,84,181,91,146,
176
  78,191,80,81,82,13,312,311,310,415,308,324,318,402,317,14,87,178,88,95,
@@ -207,7 +207,7 @@ def extract_landmarks(face_dir, lm_dir, clip_id):
207
 
208
  # ─── Step 5: Extract audio ───────────────────────────────────────────────────
209
  def extract_audio(clips_dir, audio_dir, clip_id):
210
- """Trích xuất WAV + mel spectrogram theo IP-LAP convention."""
211
  try:
212
  import numpy as np, librosa
213
  from scipy import signal as scipy_signal
@@ -228,7 +228,7 @@ def extract_audio(clips_dir, audio_dir, clip_id):
228
  if not wav_path.exists():
229
  return False
230
 
231
- # Mel spectrogram theo IP-LAP convention
232
  wav, _ = librosa.load(str(wav_path), sr=AUDIO_SR)
233
  preemph = scipy_signal.lfilter([1, -0.97], [1], wav)
234
  D = librosa.stft(preemph, n_fft=800, hop_length=200, win_length=800)
@@ -250,7 +250,7 @@ def process_video(video_id, url, clip_ids, out_base):
250
 
251
  raw_video = raw_dir / f'{video_id}.mp4'
252
 
253
- # Step 1: Download
254
  if not raw_video.exists():
255
  print(f' Downloading {url}...')
256
  if not download_video(url, raw_video):
@@ -259,7 +259,7 @@ def process_video(video_id, url, clip_ids, out_base):
259
  else:
260
  print(f' [SKIP] already downloaded')
261
 
262
- # Step 2–5: Per-clip
263
  for clip_id in clip_ids:
264
  full_clip_id = clip_id # e.g. "3p7dFrIx5bk_c0017"
265
  clip_path = clips_dir / f'{full_clip_id}.mp4'
@@ -299,7 +299,7 @@ def main():
299
  sources = load_sources()
300
  clips_map = clips_for_splits(args.splits)
301
 
302
- # Copy filelists
303
  fl_out = out_base / 'filelists'
304
  fl_out.mkdir(exist_ok=True)
305
  for split in args.splits:
@@ -307,7 +307,7 @@ def main():
307
  if src.exists():
308
  shutil.copy(src, fl_out / f'{split}.txt')
309
 
310
- # Filter by video_ids if specified
311
  if args.video_ids:
312
  clips_map = {k: v for k, v in clips_map.items() if k in args.video_ids}
313
 
@@ -338,4 +338,4 @@ def main():
338
 
339
 
340
  if __name__ == '__main__':
341
- main()
 
1
  """
2
+ download_dataset.py — Download and process the ViLAP dataset from YouTube.
3
 
4
+ Requirements:
5
  pip install yt-dlp mediapipe opencv-python librosa scipy numpy
6
 
7
+ Usage:
8
+ # Download all splits (train + val + test)
9
  python download_dataset.py --output ./vilap_data
10
 
11
+ # Download only the test split
12
  python download_dataset.py --output ./vilap_data --splits test
13
 
14
+ # Download only specific videos
15
  python download_dataset.py --output ./vilap_data --video_ids 3p7dFrIx5bk xwsPD6xiPbI
16
  """
17
 
 
33
 
34
 
35
  def clips_for_splits(splits):
36
+ """Return a dictionary {video_id: [clip_ids]} for the selected splits."""
37
  clips = {}
38
  for split in splits:
39
  path = FILELISTS_DIR / f'{split}.txt'
 
50
 
51
  # ─── Step 1: Download raw video ───────────────────────────────────────────────
52
  def download_video(url, out_path):
53
+ """Download a video with yt-dlp using the best available quality below 1080p."""
54
  cmd = [
55
  'yt-dlp', '-f', 'bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720][ext=mp4]/best',
56
  '--merge-output-format', 'mp4',
 
64
 
65
  # ─── Step 2: Cut clips ────────────────────────────────────────────────────────
66
  def cut_clips(raw_video, clips_dir, clip_ids, fps=25):
67
+ """Cut the video into 5-second clips based on the clip index."""
68
  clips_dir.mkdir(parents=True, exist_ok=True)
69
+ # Get the video duration.
70
  probe = subprocess.run(
71
  ['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
72
  '-of', 'default=noprint_wrappers=1:nokey=1', str(raw_video)],
 
78
  print(f' [WARN] cannot get duration for {raw_video.name}')
79
  return
80
 
81
+ # Read the clip index from names such as "spk_c0017" → index 17.
82
  for clip_id in clip_ids:
83
  idx = int(clip_id.split('_c')[-1])
84
  start_sec = idx * 5.0
 
99
 
100
  # ─── Step 3: Extract faces ────────────────────────────────────────────────────
101
  def extract_faces(clips_dir, face_dir, clip_id):
102
+ """Use MediaPipe Face Detection to crop and resize the face to 128x128."""
103
  try:
104
  import cv2, mediapipe as mp
105
  except ImportError:
 
129
  y1 = max(0, int(bb.ymin * h))
130
  x2 = min(w, int((bb.xmin + bb.width) * w))
131
  y2 = min(h, int((bb.ymin + bb.height) * h))
132
+ # Add a 20% margin around the detected face.
133
  margin_x = int((x2 - x1) * 0.2)
134
  margin_y = int((y2 - y1) * 0.2)
135
  x1 = max(0, x1 - margin_x); y1 = max(0, y1 - margin_y)
 
145
 
146
  # ─── Step 4: Extract landmarks ───────────────────────────────────────────────
147
  def extract_landmarks(face_dir, lm_dir, clip_id):
148
+ """Use MediaPipe Face Mesh to extract 478 landmarks and save pose + content landmarks."""
149
  try:
150
  import cv2, mediapipe as mp
151
  import numpy as np
 
166
  CONTENT_IDS = [
167
  61,185,40,39,37,0,267,269,270,409,291,375,321,405,314,17,84,181,91,146,
168
  78,191,80,81,82,13,312,311,310,415,308,324,318,402,317,14,87,178,88,95,
169
+ # Jaw landmarks from the inner portion.
170
  162,127,234,93,132,58,172,136,150,149,176,148,152,
171
  377,400,378,379,
172
  ]
173
+ # Use exactly 57 content points following the IP-LAP convention.
174
  CONTENT_IDS = [
175
  61,185,40,39,37,0,267,269,270,409,291,375,321,405,314,17,84,181,91,146,
176
  78,191,80,81,82,13,312,311,310,415,308,324,318,402,317,14,87,178,88,95,
 
207
 
208
  # ─── Step 5: Extract audio ───────────────────────────────────────────────────
209
  def extract_audio(clips_dir, audio_dir, clip_id):
210
+ """Extract WAV audio and mel spectrograms following the IP-LAP convention."""
211
  try:
212
  import numpy as np, librosa
213
  from scipy import signal as scipy_signal
 
228
  if not wav_path.exists():
229
  return False
230
 
231
+ # Compute the mel spectrogram following the IP-LAP convention.
232
  wav, _ = librosa.load(str(wav_path), sr=AUDIO_SR)
233
  preemph = scipy_signal.lfilter([1, -0.97], [1], wav)
234
  D = librosa.stft(preemph, n_fft=800, hop_length=200, win_length=800)
 
250
 
251
  raw_video = raw_dir / f'{video_id}.mp4'
252
 
253
+ # Step 1: Download the raw video.
254
  if not raw_video.exists():
255
  print(f' Downloading {url}...')
256
  if not download_video(url, raw_video):
 
259
  else:
260
  print(f' [SKIP] already downloaded')
261
 
262
+ # Steps 2–5: Process each clip.
263
  for clip_id in clip_ids:
264
  full_clip_id = clip_id # e.g. "3p7dFrIx5bk_c0017"
265
  clip_path = clips_dir / f'{full_clip_id}.mp4'
 
299
  sources = load_sources()
300
  clips_map = clips_for_splits(args.splits)
301
 
302
+ # Copy filelists to the output directory.
303
  fl_out = out_base / 'filelists'
304
  fl_out.mkdir(exist_ok=True)
305
  for split in args.splits:
 
307
  if src.exists():
308
  shutil.copy(src, fl_out / f'{split}.txt')
309
 
310
+ # Filter by video_ids if specified.
311
  if args.video_ids:
312
  clips_map = {k: v for k, v in clips_map.items() if k in args.video_ids}
313
 
 
338
 
339
 
340
  if __name__ == '__main__':
341
+ main()