|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| import argparse
|
| import ast
|
| import csv
|
| import json
|
| import os
|
| import shutil
|
| import subprocess
|
| from tqdm import tqdm
|
|
|
|
|
| def get_vid_mapping(input_video_dir):
|
| """
|
| Create mapping from video ID to local file path.
|
|
|
| Args:
|
| input_video_dir: Directory containing downloaded videos organized in folders
|
|
|
| Returns:
|
| vid_mapping: Dictionary mapping video IDs to local file paths
|
| """
|
| print("mapping video id to local path")
|
| vid_mapping = {}
|
| folders = [x for x in os.listdir(input_video_dir) if os.path.isdir(f"{input_video_dir}/{x}")]
|
| for folder in sorted(folders):
|
| vids = [x for x in os.listdir(f"{input_video_dir}/{folder}") if x[-4:] == ".mp4"]
|
| for vid in tqdm(sorted(vids)):
|
| vid_path = f"{input_video_dir}/{folder}/{vid}"
|
| vid_json = f"{input_video_dir}/{folder}/{vid[:-4]}.json"
|
|
|
| vid_name = json.load(open(vid_json))["url"].split("?v=")[-1]
|
| vid_mapping[vid_name] = vid_path
|
| return vid_mapping
|
|
|
|
|
| def extract(url_list, input_video_dir, output_frame_parent, uid_mapping):
|
| """
|
| Extract frames from videos at 12 fps.
|
|
|
| Args:
|
| url_list: CSV file containing video URLs and timestamps
|
| input_video_dir: Directory containing downloaded videos
|
| output_frame_parent: Output directory for extracted frames
|
| uid_mapping: CSV file mapping timestamps to unique IDs
|
| """
|
| vid_mapping = get_vid_mapping(input_video_dir)
|
|
|
| with open(uid_mapping, "r") as file2:
|
| with open(url_list, "r") as file:
|
| csv_reader = csv.reader(file)
|
| csv_reader2 = csv.reader(file2)
|
| for i, (row, row2) in enumerate(tqdm(zip(csv_reader, csv_reader2))):
|
|
|
| if i == 0 or len(row) == 0:
|
| continue
|
|
|
| try:
|
| full_vid_path = vid_mapping[row[0]]
|
| except KeyError:
|
| if i % 10 == 0:
|
| print("video not found, skipping", row[0])
|
| continue
|
|
|
| print("extracting", row[0])
|
| for j, timestamps in enumerate(ast.literal_eval(row[2])):
|
| uid = row2[j]
|
|
|
| vid_parent = os.path.dirname(os.path.dirname(full_vid_path))
|
| vid_uid_path = shutil.copyfile(full_vid_path, f"{vid_parent}/{uid}.mp4")
|
| os.makedirs(f"{output_frame_parent}/{uid}", exist_ok=True)
|
|
|
| cmd = f"nice -n 19 ffmpeg -i {vid_uid_path} -q:v 2 -vf fps=12 {output_frame_parent}/{uid}/%05d.jpg"
|
|
|
| subprocess.run(cmd, shell=True, capture_output=True)
|
|
|
|
|
| if __name__ == "__main__":
|
| parser = argparse.ArgumentParser()
|
| parser.add_argument("--url_list", type=str, help="path for url list")
|
| parser.add_argument("--input_video_dir", type=str, help="video directory")
|
| parser.add_argument("--output_frame_parent", type=str, help="parent for output frames")
|
| parser.add_argument("--uid_mapping", type=str, help="path for uid mapping")
|
| args = parser.parse_args()
|
| print("args", args)
|
| extract(args.url_list, args.input_video_dir, args.output_frame_parent, args.uid_mapping)
|
|
|