sindhuhegde commited on
Commit
a278321
·
1 Parent(s): c271ff7

Update dataset download instructions

Browse files
Files changed (6) hide show
  1. .DS_Store +0 -0
  2. README.md +7 -12
  3. avs-spot.py +0 -29
  4. dataset.csv → avs_spot.csv +0 -0
  5. download_videos.py +0 -136
  6. preprocess_videos.py +0 -588
.DS_Store ADDED
Binary file (6.15 kB). View file
 
README.md CHANGED
@@ -21,13 +21,11 @@ source_datasets:
21
 
22
  # Dataset Card for AVS-Spot Benchmark
23
 
24
-
25
 
26
  This dataset is associated with the paper: "Understanding Co-Speech Gestures in-the-wild"
27
 
28
  - 📝 ArXiv:
29
-
30
- - 🌐 Project page: https://www.robots.ox.ac.uk/~vgg/research/jegal
31
 
32
  <p align="center">
33
  <img src="assets/teaser.gif", width="450"/>
@@ -37,9 +35,9 @@ We present **JEGAL**, a **J**oint **E**mbedding space for **G**estures, **A**udi
37
 
38
  ## 📋 Table of Contents
39
 
40
- - [Dataset Card for AVS-Spot Benchmark?](#dataset-card-for-avs-spot-benchmark)
41
  - [📋 Table of Contents](#📋-table-of-contents)
42
- - [📚 What is the AVS-Spot Benchmark](#📚-dataset-description)
43
  - [Summary](#summary)
44
  - [Download instructions](#download-instructions)
45
  - [📝 Dataset Structure](#📝-dataset-structure)
@@ -51,7 +49,6 @@ We present **JEGAL**, a **J**oint **E**mbedding space for **G**estures, **A**udi
51
  - [🙏 Acknowledgements](#🙏-acknowledgements)
52
 
53
 
54
-
55
 
56
 
57
  ## 📚 What is the AVS-Spot Benchmark?
@@ -90,13 +87,11 @@ from datasets import load_dataset
90
  # Load the dataset csv file with annotations
91
  dataset = load_dataset("sindhuhegde/avs-spot")
92
  ```
93
- ```bash
94
- # Download the videos from YouTube-ids and timestamps
95
- python download_videos.py --video_root=<dataset-path>
96
 
97
- # Obtain the crops with the target speaker
98
- python preprocess_videos.py --data_root=<dataset-path> --preprocessed_root=<path-to-save-the-preprocessed-data> --merge_dir=<path-to-save-audio-video-merged-results> --temp_dir=<path-to-save-intermediate-results> --metadata_root=<path-to-save-the-metadata>
99
- ```
 
100
 
101
  Once the dataset is downloaded and pre-processed, the structure of the folders will be as follows:
102
 
 
21
 
22
  # Dataset Card for AVS-Spot Benchmark
23
 
 
24
 
25
  This dataset is associated with the paper: "Understanding Co-Speech Gestures in-the-wild"
26
 
27
  - 📝 ArXiv:
28
+ - 🌐 Project page: https://www.robots.ox.ac.uk/~vgg/research/jegal
 
29
 
30
  <p align="center">
31
  <img src="assets/teaser.gif", width="450"/>
 
35
 
36
  ## 📋 Table of Contents
37
 
38
+ - [Dataset Card for AVS-Spot Benchmark](#dataset-card-for-avs-spot-benchmark)
39
  - [📋 Table of Contents](#📋-table-of-contents)
40
+ - [📚 Dataset Description](#📚-dataset-description)
41
  - [Summary](#summary)
42
  - [Download instructions](#download-instructions)
43
  - [📝 Dataset Structure](#📝-dataset-structure)
 
49
  - [🙏 Acknowledgements](#🙏-acknowledgements)
50
 
51
 
 
52
 
53
 
54
  ## 📚 What is the AVS-Spot Benchmark?
 
87
  # Load the dataset csv file with annotations
88
  dataset = load_dataset("sindhuhegde/avs-spot")
89
  ```
 
 
 
90
 
91
+ The csv file contains the video-ids and annotations.
92
+
93
+ Please refer to [download scripts](https://github.com/Sindhu-Hegde/jegal/dataset) to download and pre-process AVS-Spot.
94
+
95
 
96
  Once the dataset is downloaded and pre-processed, the structure of the folders will be as follows:
97
 
avs-spot.py DELETED
@@ -1,29 +0,0 @@
1
- from datasets import load_dataset_builder, GeneratorBasedBuilder, SplitGenerator, DatasetInfo, Value, Split
2
-
3
- class GestureVideoDataset(GeneratorBasedBuilder):
4
- def _info(self):
5
- return DatasetInfo(
6
- features={
7
- "video_id": Value("string"),
8
- "start_time": Value("float"),
9
- "end_time": Value("float"),
10
- "filename": Value("string"),
11
- "num_frames": Value("int32"),
12
- "phrase": Value("string"),
13
- "target_word": Value("string"),
14
- "target_word_boundary": Value("string"),
15
- "word_boundaries": Value("string"),
16
- "stress_label": Value("int32"),
17
- }
18
- )
19
-
20
- def _split_generators(self, dl_manager):
21
- data_path = dl_manager.download_and_extract("https://huggingface.co/datasets/sindhuhegde/avs-spot/resolve/main/dataset.csv")
22
- return [SplitGenerator(name=Split.TRAIN, gen_kwargs={"filepath": data_path})]
23
-
24
- def _generate_examples(self, filepath):
25
- import csv
26
- with open(filepath, encoding="utf-8") as f:
27
- reader = csv.DictReader(f)
28
- for i, row in enumerate(reader):
29
- yield i, row
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dataset.csv → avs_spot.csv RENAMED
File without changes
download_videos.py DELETED
@@ -1,136 +0,0 @@
1
- import argparse
2
- import pandas as pd
3
- import numpy as np
4
- import os, subprocess
5
- from tqdm import tqdm
6
- import math
7
- from datasets import load_dataset
8
-
9
- import traceback
10
- import executor
11
- import concurrent.futures
12
- from concurrent.futures import ThreadPoolExecutor, as_completed
13
-
14
- import warnings
15
- warnings.filterwarnings("ignore", category=DeprecationWarning)
16
-
17
- os.environ["LC_ALL"]="en_US.utf-8"
18
- os.environ["LANG"]="en_US.utf-8"
19
-
20
- parser = argparse.ArgumentParser(description="Code to download the videos from the input csv file")
21
- parser.add_argument('--video_root', type=str, required=True, help="Path to the directory to save the videos")
22
-
23
- args = parser.parse_args()
24
-
25
- def is_valid_video(file_path):
26
-
27
- '''
28
- This function validates the video file using the following checks:
29
- (i) Check if duration > 0
30
- (ii) Check if audio is present
31
-
32
- Args:
33
- - file_path (str): Path to the video file.
34
- Returns:
35
- - True if the video is valid, False otherwise.
36
- '''
37
-
38
- if not os.path.exists(file_path):
39
- return False # File does not exist
40
-
41
- # Use ffmpeg to get duration
42
- try:
43
- result = subprocess.run(
44
- ["ffmpeg", "-i", file_path, "-f", "null", "-"],
45
- stdout=subprocess.DEVNULL,
46
- stderr=subprocess.DEVNULL
47
- )
48
- return result.returncode == 0 # If return code is 0, it's a valid video
49
- except Exception:
50
- return False # If ffmpeg fails, assume it's invalid
51
-
52
- # Check if audio exists
53
- cmd_audio = f'ffmpeg -i "{video_path}" -map 0:a:0 -f null - 2>&1 | grep "Output"'
54
- try:
55
- audio_output = subprocess.check_output(cmd_audio, shell=True, text=True)
56
- if not audio_output.strip():
57
- print(f"Invalid video (no audio): {video_path}")
58
- os.remove(video_path)
59
- return False
60
- except Exception:
61
- print(f"Error checking audio: {video_path}")
62
- os.remove(video_path)
63
- return False
64
-
65
-
66
- def mp_handler(i, df, result_dir):
67
-
68
- '''
69
- This function handles the multiprocessing of the video download
70
-
71
- Args:
72
- - i (int): Index of the video.
73
- - df (pd.DataFrame): DataFrame containing the video information.
74
- - result_dir (str): Directory to save the video.
75
- '''
76
-
77
- try:
78
- data = df.iloc[i]
79
- vid = data['video_id']
80
- video_link = "https://www.youtube.com/watch?v={}".format(vid)
81
- start = data['start_time']
82
- end = data['end_time']
83
- start = format(float(start), '.6f')
84
- end = format(float(end), '.6f')
85
- time = "*{}-{}".format(start,end)
86
- # print(vid, video_link, start, end, time)
87
-
88
- output_fname = os.path.join(result_dir, "{}_{}-{}.mp4".format(vid, start, end))
89
-
90
- if os.path.exists(output_fname):
91
- # Validate file
92
- if is_valid_video(output_fname):
93
- return
94
-
95
- # Download the video
96
- cmd = "yt-dlp --geo-bypass -f b --download-sections {} --format=mp4 -o {} {}".format(time, output_fname, video_link)
97
- subprocess.call(cmd, shell=True)
98
-
99
- # Validate file and delete if invalid
100
- if not is_valid_video(output_fname):
101
- print(f"Invalid file detected: {output_fname}. Deleting...")
102
- os.remove(output_fname)
103
-
104
- except KeyboardInterrupt:
105
- exit(0)
106
- except:
107
- traceback.print_exc()
108
-
109
- def download_data(args):
110
-
111
- '''
112
- This function downloads the videos from the given csv file
113
-
114
- Args:
115
- - args (argparse.Namespace): Arguments.
116
- '''
117
-
118
- # Load the dataset csv file with annotations
119
- dataset = load_dataset("sindhuhegde/avs-spot")
120
- df = dataset.to_pandas()
121
- print("Total files: ", len(df))
122
-
123
- # Create the result directory
124
- if not os.path.exists(args.result_dir):
125
- os.makedirs(args.result_dir)
126
-
127
- # Create the multiprocessing pool and submit the jobs to download the videos
128
- jobs = [idx for idx in range(len(df))]
129
- p = ThreadPoolExecutor(8)
130
- futures = [p.submit(mp_handler, j, df, args.video_root) for j in jobs]
131
- res = [r.result() for r in tqdm(as_completed(futures), total=len(futures))]
132
-
133
- if __name__ == '__main__':
134
-
135
- # Download the videos
136
- download_data(args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocess_videos.py DELETED
@@ -1,588 +0,0 @@
1
- import sys, os, argparse, pickle, subprocess, cv2, math
2
- import numpy as np
3
- import random
4
- from shutil import rmtree, copy
5
- from datasets import load_dataset
6
-
7
- from tqdm import tqdm
8
- from glob import glob
9
-
10
- from scipy.interpolate import interp1d
11
- from scipy import signal
12
-
13
- from ultralytics import YOLO
14
- from decord import VideoReader
15
- import mediapipe as mp
16
- from protobuf_to_dict import protobuf_to_dict
17
-
18
- import pandas as pd
19
- import warnings
20
- warnings.filterwarnings("ignore")
21
- warnings.filterwarnings('ignore', category=UserWarning)
22
- warnings.filterwarnings("ignore", message="Feedback manager requires a model with a single signature inference")
23
-
24
- parser = argparse.ArgumentParser(description="Code to preprocess the videos and obtain target speaker crops")
25
- parser.add_argument('--data_root', type=str, required=True, default="", help='Path of the folder containing full uncropped videos')
26
- parser.add_argument('--preprocessed_root', type=str, required=True, help='Path to save the output crops')
27
- parser.add_argument('--merge_dir', type=str, required=True, help='Path to save the audio-video merged output')
28
- parser.add_argument('--temp_dir', type=str, required=True, help='Path to save intermediate results')
29
- parser.add_argument('--metadata_root', type=str, required=True, help='Path to save metadata files')
30
-
31
- parser.add_argument('--crop_scale', type=float, default=0, help='Scale bounding box')
32
- parser.add_argument('--min_track', type=int, default=10, help='Minimum facetrack duration')
33
- parser.add_argument('--min_frame_size', type=int, default=64, help='Minimum frame size in pixels')
34
- parser.add_argument('--num_failed_det', type=int, default=25, help='Number of missed detections allowed before tracking is stopped')
35
- parser.add_argument('--frame_rate', type=int, default=25, help='Frame rate')
36
- opt = parser.parse_args()
37
-
38
- # Set random seeds
39
- random.seed(42)
40
-
41
- # Load the YOLO model
42
- yolo_model = YOLO("yolov9c.pt")
43
-
44
- # Initialize the mediapipe holistic keypoint detection model
45
- mp_holistic = mp.solutions.holistic
46
-
47
- # Global variables
48
- save_count, err_count = 0, 0
49
-
50
- def bb_intersection_over_union(boxA, boxB):
51
-
52
- '''
53
- This function calculates the intersection over union of two bounding boxes
54
-
55
- Args:
56
- - boxA (list): Bounding box A.
57
- - boxB (list): Bounding box B.
58
- Returns:
59
- - iou (float): Intersection over union of the two bounding boxes
60
- '''
61
-
62
- xA = max(boxA[0], boxB[0])
63
- yA = max(boxA[1], boxB[1])
64
- xB = min(boxA[2], boxB[2])
65
- yB = min(boxB[3], boxB[3])
66
-
67
- interArea = max(0, xB - xA) * max(0, yB - yA)
68
-
69
- boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
70
- boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
71
-
72
- try:
73
- iou = interArea / float(boxAArea + boxBArea - interArea)
74
- except:
75
- return None
76
-
77
- return iou
78
-
79
- def track_speakers(opt, dets):
80
-
81
- '''
82
- This function tracks the speakers in the video using the detected bounding boxes
83
-
84
- Args:
85
- - opt (argparse): Argument parser.
86
- - dets (list): List of detections.
87
- Returns:
88
- - tracks (list): List of tracks.
89
- '''
90
-
91
- # Minimum IOU between consecutive face detections
92
- iouThres = 0.5
93
- tracks = []
94
-
95
- while True:
96
- track = []
97
- for frames in dets:
98
- for face in frames:
99
- if track == []:
100
- track.append(face)
101
- frames.remove(face)
102
- elif face['frame'] - track[-1]['frame'] <= opt.num_failed_det:
103
- iou = bb_intersection_over_union(face['bbox'], track[-1]['bbox'])
104
- if iou is None:
105
- track.append(face)
106
- frames.remove(face)
107
- continue
108
- elif iou > iouThres:
109
- track.append(face)
110
- frames.remove(face)
111
- continue
112
- else:
113
- break
114
-
115
- if track == []:
116
- break
117
- elif len(track) > opt.min_track:
118
- framenum = np.array([f['frame'] for f in track])
119
- bboxes = np.array([np.array(f['bbox']) for f in track])
120
-
121
- frame_i = np.arange(framenum[0], framenum[-1] + 1)
122
-
123
- bboxes_i = []
124
- for ij in range(0, 4):
125
- interpfn = interp1d(framenum, bboxes[:, ij])
126
- bboxes_i.append(interpfn(frame_i))
127
- bboxes_i = np.stack(bboxes_i, axis=1)
128
-
129
- if max(np.mean(bboxes_i[:, 2] - bboxes_i[:, 0]), np.mean(bboxes_i[:, 3] - bboxes_i[:, 1])) > opt.min_frame_size:
130
- tracks.append({'frame': frame_i, 'bbox': bboxes_i})
131
-
132
- return tracks
133
-
134
-
135
- def get_keypoints(frames):
136
-
137
- '''
138
- This function extracts the keypoints from the frames using MediaPipe Holistic pipeline
139
-
140
- Args:
141
- - frames (list) : List of frames extracted from the video
142
- Returns:
143
- - all_frame_kps (list) : List of keypoints for each frame
144
- '''
145
-
146
- resolution = frames[0].shape
147
- # print("Resolution:", resolution)
148
-
149
- all_frame_kps= []
150
- with mp_holistic.Holistic(
151
- min_detection_confidence=0.5,
152
- min_tracking_confidence=0.5
153
- ) as holistic:
154
- for frame in frames:
155
-
156
- results = holistic.process(frame)
157
-
158
- pose, left_hand, right_hand, face = None, None, None, None
159
- if results.pose_landmarks is not None:
160
- pose, pose_world, left_hand, right_hand, face = None, None, None, None, None
161
- if results.pose_landmarks is not None:
162
- pose = protobuf_to_dict(results.pose_landmarks)['landmark']
163
-
164
- pose_kps = []
165
- for kps in pose:
166
- if kps is not None:
167
- pose_kps.append([kps["x"]*resolution[1], kps["y"]*resolution[0], kps["visibility"]])
168
- pose_kps = np.array(pose_kps)
169
-
170
- all_frame_kps.append(pose_kps)
171
-
172
-
173
- all_frame_kps = np.array(all_frame_kps)
174
- if len(all_frame_kps) == 0:
175
- return None
176
- else:
177
- return all_frame_kps
178
-
179
- def adjust_bbox_kps(frames, all_frame_kps, padding_x=25, padding_y=-15):
180
-
181
- '''
182
- This function crops frames based on the detected keypoints
183
-
184
- Args:
185
- - frames (list of numpy arrays): List of cropped frames.
186
- - all_frame_kps (numpy array): T x num_keypoints x 3 (x, y, confidence).
187
- - padding_x (int): Extra padding for cropping.
188
- - padding_y (int): Extra padding for cropping.
189
-
190
- Returns:
191
- - cropped_frames (list of numpy arrays): Cropped frames according to adjusted bounding box from keypoints
192
- '''
193
-
194
- LEFT_KP_INDICES = [12, 14, 16, 18, 20, 22, 24]
195
- RIGHT_KP_INDICES = [11, 13, 15, 17, 19, 21, 23]
196
- LEFT_HIP_IDX = 23
197
- RIGHT_HIP_IDX = 24
198
-
199
- left_xs = []
200
- right_xs = []
201
- waist_ys = []
202
-
203
- for keypoints in all_frame_kps:
204
- # Extract left and right keypoints that have confidence > 0.7
205
- left_kps = [keypoints[i] for i in LEFT_KP_INDICES if keypoints[i][2] > 0.7]
206
- right_kps = [keypoints[i] for i in RIGHT_KP_INDICES if keypoints[i][2] > 0.7]
207
-
208
- # Compute spatial limits if keypoints exist
209
- if left_kps:
210
- left_xs.append(min(kp[0] for kp in left_kps)) # Leftmost x
211
- if right_kps:
212
- right_xs.append(max(kp[0] for kp in right_kps)) # Rightmost x
213
-
214
- # Compute waistline from hips if both are detected with confidence > 0.7
215
- left_hip, right_hip = keypoints[LEFT_HIP_IDX], keypoints[RIGHT_HIP_IDX]
216
- if left_hip[2] > 0.7 and right_hip[2] > 0.7:
217
- waist_ys.append((left_hip[1] + right_hip[1]) / 2)
218
-
219
- # Compute global cropping limits
220
- frame_height, frame_width = frames[0].shape[:2]
221
-
222
- if len(left_xs) > 0 and len(left_xs)/len(all_frame_kps) > 0.7:
223
- left_x = int(min(left_xs)) - padding_x
224
- else:
225
- left_x = 0
226
-
227
- if len(right_xs) > 0 and len(right_xs)/len(all_frame_kps) > 0.7:
228
- right_x = int(max(right_xs)) + padding_x
229
- else:
230
- right_x = frame_width
231
-
232
- if len(waist_ys) > 0 and len(waist_ys)/len(all_frame_kps) > 0.7:
233
- upper_body_estimate = int(np.mean(waist_ys)) # Use average waist position
234
- new_y2 = upper_body_estimate + padding_y
235
- else:
236
- new_y2 = frame_height
237
-
238
- # Ensure within frame bounds
239
- left_x = max(0, left_x)
240
- right_x = min(frame_width, right_x)
241
- new_y2 = min(new_y2, frame_height)
242
-
243
-
244
- # Crop all frames
245
- cropped_frames = [frame[:new_y2, left_x:right_x] for frame in frames]
246
-
247
- return cropped_frames
248
-
249
- def detect_speaker(opt, padding=5, video_fname="person", work_dir=None):
250
-
251
- '''
252
- This function detects the speaker in the video using YOLOv9 model
253
-
254
- Args:
255
- - opt (argparse): Argument parser.
256
- - padding (int): Extra padding for cropping.
257
- - video_fname (str): Name of the video file.
258
- - work_dir (str): Directory to save the person.pkl file.
259
- Returns:
260
- - alltracks (list): List of tracks.
261
- '''
262
-
263
- videofile = os.path.join(opt.avi_dir, 'video.avi')
264
- vidObj = cv2.VideoCapture(videofile)
265
-
266
- dets = []
267
- fidx = 0
268
- alltracks = []
269
-
270
- while True:
271
- success, image = vidObj.read()
272
- if not success:
273
- break
274
-
275
- image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
276
-
277
- # Perform person detection
278
- results = yolo_model(image_np, verbose=False)
279
- detections = results[0].boxes
280
-
281
- dets.append([])
282
- for i, det in enumerate(detections):
283
- x1, y1, x2, y2 = det.xyxy[0]
284
- cls = det.cls[0]
285
- conf = det.conf[0]
286
- if int(cls) == 0 and conf>0.6: # Class 0 is 'person' in COCO dataset
287
- x1 = max(0, int(x1) - padding)
288
- y1 = max(0, int(y1) - padding)
289
- x2 = min(image_np.shape[1], int(x2) + padding)
290
- y2 = min(image_np.shape[0], int(y2) + padding)
291
- dets[-1].append({'frame': fidx, 'bbox': [x1, y1, x2, y2], 'conf': conf})
292
-
293
- fidx += 1
294
-
295
-
296
- if len(dets) >= opt.min_track and np.abs(len(dets) - fidx) <= 5:
297
- alltracks.extend(track_speakers(opt, dets[0:len(dets)]))
298
-
299
- savepath = os.path.join(work_dir, 'person.pkl')
300
- with open(savepath, 'wb') as fil:
301
- pickle.dump(dets, fil)
302
-
303
- return alltracks
304
-
305
- else:
306
- # print("Num. of frames = {} | Num. of detections = {}".format(fidx, len(dets)))
307
- return None
308
-
309
-
310
- def crop_video(opt, track, cropfile, tight_scale=0.9, padding=-15):
311
-
312
- '''
313
- This function crops the video based on the detected bounding boxes
314
-
315
- Args:
316
- - opt (argparse): Argument parser.
317
- - track (dict): Person tracks obtained.
318
- - cropfile (str): Path to save the cropped video.
319
- - tight_scale (float): Tight scale for cropping.
320
- - padding (int): Extra padding for cropping.
321
- Returns:
322
- - dets (dict): Detections.
323
- '''
324
-
325
- dets = {'x': [], 'y': [], 's': []}
326
-
327
- for det in track['bbox']:
328
- # Scale the bounding box by a small factor to obtain a tight crop
329
- width = (det[2] - det[0]) * tight_scale
330
- height = (det[3] - det[1]) * tight_scale
331
- center_x = (det[0] + det[2]) / 2
332
- center_y = (det[1] + det[3]) / 2
333
-
334
- dets['s'].append(max(height, width) / 2)
335
- dets['y'].append(center_y) # crop center y
336
- dets['x'].append(center_x) # crop center x
337
-
338
- # Smooth detections
339
- dets['s'] = signal.medfilt(dets['s'], kernel_size=13)
340
- dets['x'] = signal.medfilt(dets['x'], kernel_size=13)
341
- dets['y'] = signal.medfilt(dets['y'], kernel_size=13)
342
-
343
- videofile = os.path.join(opt.avi_dir, 'video.avi')
344
- frame_no_to_start = track['frame'][0]
345
-
346
- video_stream = cv2.VideoCapture(videofile)
347
- video_stream.set(cv2.CAP_PROP_POS_FRAMES, frame_no_to_start)
348
- cropped_frames, all_heights, all_widths = [], [], []
349
-
350
- for fidx, _ in enumerate(track['frame']):
351
- cs = opt.crop_scale
352
- bs = dets['s'][fidx] # Detection box size
353
- bsi = int(bs * (1 + 2 * cs)) # Pad videos by this amount
354
-
355
- image = video_stream.read()[1]
356
- frame = np.pad(image, ((bsi, bsi), (bsi, bsi), (0, 0)), 'constant', constant_values=(110, 110))
357
-
358
- my = dets['y'][fidx] + bsi # BBox center Y
359
- mx = dets['x'][fidx] + bsi # BBox center X
360
-
361
- crop = frame[int(my - bs):int(my + bs * (1 + 2 * cs)), int(mx - bs * (1 + cs)):int(mx + bs * (1 + cs))]
362
-
363
- cropped_frames.append(crop)
364
- all_heights.append(crop.shape[0])
365
- all_widths.append(crop.shape[1])
366
-
367
- # Get the maximum height and width of the cropped frames
368
- shape = (max(all_heights), max(all_widths))
369
-
370
- # Resize the cropped frames to the maximum height and width
371
- cropped_frames_fixed_size = []
372
- for frame in cropped_frames:
373
- frame = cv2.resize(frame, (shape[0], shape[1]))
374
- cropped_frames_fixed_size.append(frame)
375
-
376
- # Get the keypoints for the cropped frames
377
- all_frame_kps = get_keypoints(cropped_frames_fixed_size.copy(), cropfile+"_kps.pkl")
378
- if all_frame_kps is None:
379
- upper_body_cropped_frames = cropped_frames_fixed_size
380
- else:
381
- upper_body_cropped_frames = adjust_bbox_kps(cropped_frames_fixed_size, all_frame_kps)
382
-
383
- # Write the cropped frames to a video file
384
- shape_video = (upper_body_cropped_frames[0].shape[1], upper_body_cropped_frames[0].shape[0])
385
- fourcc = cv2.VideoWriter_fourcc(*'XVID')
386
- vOut = cv2.VideoWriter(cropfile + '.avi', fourcc, opt.frame_rate, shape_video)
387
-
388
- for frame in upper_body_cropped_frames:
389
- frame = np.uint8(frame)
390
- vOut.write(frame)
391
-
392
- video_stream.release()
393
- audiotmp = os.path.join(opt.tmp_dir, 'audio.wav')
394
- audiostart = (track['frame'][0]) / opt.frame_rate
395
- audioend = (track['frame'][-1] + 1) / opt.frame_rate
396
-
397
- vOut.release()
398
-
399
- # ========== CROP AUDIO FILE ==========
400
-
401
- command = ("ffmpeg -hide_banner -loglevel panic -y -i %s -ss %.3f -to %.3f %s" % (os.path.join(opt.avi_dir, 'audio.wav'), audiostart, audioend, audiotmp))
402
- output = subprocess.call(command, shell=True, stdout=None)
403
-
404
- copy(audiotmp, cropfile + '.wav')
405
-
406
- # print('Mean pos: x %.2f y %.2f s %.2f' % (np.mean(dets['x']), np.mean(dets['y']), np.mean(dets['s'])))
407
-
408
- return {'track': track, 'proc_track': dets}
409
-
410
-
411
- def process_video(file, initial_data_path):
412
-
413
- '''
414
- This function processes the video
415
-
416
- Args:
417
- - file (str): Path to the video file.
418
- - initial_data_path (str): Path to save the initial data.
419
- '''
420
-
421
- global save_count, err_count
422
-
423
- video_name = file.split('/')[-1]
424
- sd_dest_folder = os.path.join(initial_data_path, video_name[:-4])
425
- work_dest_folder = os.path.join(opt.metadata_root, video_name[:-4])
426
-
427
- if os.path.exists(os.path.join(work_dest_folder, 'person.pkl')) and os.path.exists(sd_dest_folder):
428
- save_count += 1
429
- return
430
-
431
-
432
- print("Processing video: ", file)
433
- setattr(opt, 'videofile', file)
434
-
435
- if os.path.exists(opt.work_dir):
436
- rmtree(opt.work_dir)
437
-
438
- if os.path.exists(opt.crop_dir):
439
- rmtree(opt.crop_dir)
440
-
441
- if os.path.exists(opt.avi_dir):
442
- rmtree(opt.avi_dir)
443
-
444
- if os.path.exists(opt.frames_dir):
445
- rmtree(opt.frames_dir)
446
-
447
- if os.path.exists(opt.tmp_dir):
448
- rmtree(opt.tmp_dir)
449
-
450
- os.makedirs(opt.work_dir)
451
- os.makedirs(opt.crop_dir)
452
- os.makedirs(opt.avi_dir)
453
- os.makedirs(opt.frames_dir)
454
- os.makedirs(opt.tmp_dir)
455
- os.makedirs(sd_dest_folder, exist_ok=True)
456
- os.makedirs(work_dest_folder, exist_ok=True)
457
-
458
- # Extract the video and convert it to 25 FPS from the input video file
459
- command = ("ffmpeg -hide_banner -loglevel panic -y -i %s -qscale:v 2 -async 1 -r 25 %s" % (opt.videofile,
460
- os.path.join(opt.avi_dir,
461
- 'video.avi')))
462
- output = subprocess.call(command, shell=True, stdout=None)
463
- if output != 0:
464
- print("Failed to extract video from ", file)
465
- err_count += 1
466
- return
467
-
468
-
469
- command = ("ffmpeg -hide_banner -loglevel panic -y -i %s -ac 1 -vn -acodec pcm_s16le -ar 16000 %s" % (os.path.join(opt.avi_dir,
470
- 'video.avi'),
471
- os.path.join(opt.avi_dir,
472
- 'audio.wav')))
473
- output = subprocess.call(command, shell=True, stdout=None)
474
- if output != 0:
475
- print("Failed to extract audio from ", file)
476
- err_count += 1
477
- return
478
-
479
- # Detect the speaker in the video using YOLOv9 model
480
- spk_tracks = detect_speaker(opt, video_fname=video_name[:-4], work_dir=work_dest_folder)
481
- if spk_tracks is None:
482
- print("No tracks found for ", file)
483
- err_count += 1
484
- return
485
-
486
-
487
- # Crop the video based on the detected bounding boxes
488
- vidtracks = []
489
- for ii, track in enumerate(spk_tracks):
490
- vidtracks.append(crop_video(opt, track, os.path.join(sd_dest_folder, '%05d' % ii)))
491
-
492
- savepath = os.path.join(work_dest_folder, 'tracks.pkl')
493
- with open(savepath, 'wb') as fil:
494
- pickle.dump(vidtracks, fil)
495
-
496
- # Clean up the temporary directories
497
- rmtree(opt.tmp_dir)
498
- rmtree(opt.avi_dir)
499
- rmtree(opt.frames_dir)
500
-
501
- print("Saved processed video...")
502
- save_count += 1
503
-
504
-
505
- def filter_and_merge(csv_path, initial_data_path, final_data_path, merged_path, fps=25):
506
-
507
- '''
508
- This function filters and merges the audio and video
509
-
510
- Args:
511
- - csv_path (str): Path to the dataset csv file.
512
- - initial_data_path (str): Path to the initial data.
513
- - final_data_path (str): Path to save the final data (saves .avi and .wav files).
514
- - merged_path (str): Path to save the merged data (saves .mp4 files).
515
- - fps (int): Frames per second.
516
- '''
517
-
518
- # Load the dataset csv file with annotations
519
- dataset = load_dataset("sindhuhegde/avs-spot")
520
- df = dataset.to_pandas()
521
-
522
- print("Merging audio and video for visualization...")
523
-
524
- for idx in tqdm(range(len(df))):
525
- row = df.iloc[idx]
526
- video = os.path.join(initial_data_path, row["filename"] + ".avi")
527
- audio = video.replace(".avi", ".wav")
528
- kps = video.replace(".avi", "_kps.pkl")
529
-
530
- video_output = video.replace(initial_data_path, final_data_path)
531
- audio_output = audio.replace(initial_data_path, final_data_path)
532
- fname = video.split("/")[-2] + "_" + video.split("/")[-1].split(".")[0]
533
- merged_output = os.path.join(merged_path, str(idx)+"_"+fname+".mp4")
534
-
535
- # Merge the audio and video
536
- status = subprocess.call('ffmpeg -hide_banner -loglevel panic -threads 1 -y -i %s -i %s -strict -2 -q:v 1 %s' %
537
- (audio, video, merged_output), shell=True)
538
- if status != 0:
539
- print("Failed to merge audio and video for ", video)
540
- continue
541
-
542
- # Copy the target video to the final data path
543
- video_output_folder = os.path.join(final_data_path, video_output.split("/")[-2])
544
- if not os.path.exists(video_output_folder):
545
- os.makedirs(video_output_folder)
546
- status = subprocess.call('rsync -az %s %s' % (video, video_output), shell=True)
547
- if status != 0:
548
- print("Failed to copy video for ", video)
549
- continue
550
-
551
- # Copy the target audio to the final data path
552
- status = subprocess.call('rsync -az %s %s' % (audio, audio_output), shell=True)
553
- if status != 0:
554
- print("Failed to copy audio for ", audio)
555
- continue
556
-
557
-
558
- if __name__ == "__main__":
559
-
560
- # Get the list of videos to process
561
- filelist = pd.read_csv(opt.file)["filename"].tolist()
562
- files = [os.path.join(opt.data_root, f.split("/")[0] + ".mp4") for f in filelist]
563
- print(f"A total of {len(files)} files found.")
564
-
565
- # Create the necessary directories
566
- initial_data_path = opt.preprocessed_root+"_all"
567
- os.makedirs(initial_data_path, exist_ok=True)
568
- os.makedirs(opt.preprocessed_root, exist_ok=True)
569
- os.makedirs(opt.metadata_root, exist_ok=True)
570
-
571
- # Set the necessary attributes
572
- setattr(opt, 'avi_dir', os.path.join(opt.temp_dir, 'pyavi'))
573
- setattr(opt, 'tmp_dir', os.path.join(opt.temp_dir, 'pytmp'))
574
- setattr(opt, 'work_dir', os.path.join(opt.temp_dir, 'pywork'))
575
- setattr(opt, 'crop_dir', os.path.join(opt.temp_dir, 'pycrop'))
576
- setattr(opt, 'frames_dir', os.path.join(opt.temp_dir, 'pyframes'))
577
- setattr(opt, 'audio_dir', None)
578
-
579
-
580
- # Process the videos
581
- prog_bar = tqdm(files)
582
- for file in prog_bar:
583
- process_video(file, initial_data_path)
584
- prog_bar.set_description(f"Saved files: {save_count} | Failed files: {err_count}")
585
-
586
- # Create the directory and merge the audio-video files
587
- os.makedirs(opt.merge_dir, exist_ok=True)
588
- filter_and_merge(opt.file, initial_data_path, opt.preprocessed_root, opt.merge_dir)