|
| 1 | +import argparse |
| 2 | +import json |
| 3 | +import os |
| 4 | +import time |
| 5 | +from multiprocessing import Pool, cpu_count |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import torchvision |
| 9 | +from tqdm import tqdm |
| 10 | + |
| 11 | + |
| 12 | +def get_video_info(video_path): |
| 13 | + """Get video information using torchvision.""" |
| 14 | + # Read video tensor (T, C, H, W) |
| 15 | + video_tensor, _, info = torchvision.io.read_video(str(video_path), |
| 16 | + output_format="TCHW", |
| 17 | + pts_unit="sec") |
| 18 | + |
| 19 | + num_frames = video_tensor.shape[0] |
| 20 | + height = video_tensor.shape[2] |
| 21 | + width = video_tensor.shape[3] |
| 22 | + fps = info.get("video_fps", 0) |
| 23 | + duration = num_frames / fps if fps > 0 else 0 |
| 24 | + |
| 25 | + # Extract name |
| 26 | + _, _, videos_dir, video_name = str(video_path).split("/") |
| 27 | + |
| 28 | + return { |
| 29 | + "path": str(video_name), |
| 30 | + "resolution": { |
| 31 | + "width": width, |
| 32 | + "height": height |
| 33 | + }, |
| 34 | + "size": os.path.getsize(video_path), |
| 35 | + "fps": fps, |
| 36 | + "duration": duration, |
| 37 | + "num_frames": num_frames |
| 38 | + } |
| 39 | + |
| 40 | + |
| 41 | +def prepare_dataset_json(folder_path, |
| 42 | + output_name="videos2caption.json", |
| 43 | + num_workers=None) -> None: |
| 44 | + """Prepare dataset information from a folder containing videos and prompt.txt.""" |
| 45 | + folder_path = Path(folder_path) |
| 46 | + |
| 47 | + # Read prompt file |
| 48 | + prompt_file = folder_path / "prompt.txt" |
| 49 | + if not prompt_file.exists(): |
| 50 | + raise FileNotFoundError(f"prompt.txt not found in {folder_path}") |
| 51 | + |
| 52 | + with open(prompt_file) as f: |
| 53 | + prompts = [line.strip() for line in f.readlines() if line.strip()] |
| 54 | + |
| 55 | + # Read videos file |
| 56 | + videos_file = folder_path / "videos.txt" |
| 57 | + if not videos_file.exists(): |
| 58 | + raise FileNotFoundError(f"videos.txt not found in {folder_path}") |
| 59 | + |
| 60 | + with open(videos_file) as f: |
| 61 | + video_paths = [line.strip() for line in f.readlines() if line.strip()] |
| 62 | + |
| 63 | + if len(prompts) != len(video_paths): |
| 64 | + raise ValueError( |
| 65 | + f"Number of prompts ({len(prompts)}) does not match number of videos ({len(video_paths)})" |
| 66 | + ) |
| 67 | + |
| 68 | + # Prepare arguments for multiprocessing |
| 69 | + process_args = [folder_path / video_path for video_path in video_paths] |
| 70 | + |
| 71 | + # Determine number of workers |
| 72 | + if num_workers is None: |
| 73 | + num_workers = max(1, cpu_count() - 1) # Leave one CPU free |
| 74 | + |
| 75 | + # Process videos in parallel |
| 76 | + start_time = time.time() |
| 77 | + with Pool(num_workers) as pool: |
| 78 | + results = list( |
| 79 | + tqdm(pool.imap(get_video_info, process_args), |
| 80 | + total=len(process_args), |
| 81 | + desc="Processing videos", |
| 82 | + unit="video")) |
| 83 | + |
| 84 | + # Combine results with prompts |
| 85 | + dataset_info = [] |
| 86 | + for result, prompt in zip(results, prompts): |
| 87 | + result["cap"] = [prompt] |
| 88 | + dataset_info.append(result) |
| 89 | + |
| 90 | + # Calculate total processing time |
| 91 | + total_time = time.time() - start_time |
| 92 | + total_videos = len(dataset_info) |
| 93 | + avg_time_per_video = total_time / total_videos if total_videos > 0 else 0 |
| 94 | + |
| 95 | + print("\nProcessing completed:") |
| 96 | + print(f"Total videos processed: {total_videos}") |
| 97 | + print(f"Total time: {total_time:.2f} seconds") |
| 98 | + print(f"Average time per video: {avg_time_per_video:.2f} seconds") |
| 99 | + |
| 100 | + # Save to JSON file |
| 101 | + output_file = folder_path / output_name |
| 102 | + with open(output_file, 'w') as f: |
| 103 | + json.dump(dataset_info, f, indent=2) |
| 104 | + |
| 105 | + # Create merge.txt |
| 106 | + merge_file = folder_path / "merge.txt" |
| 107 | + with open(merge_file, 'w') as f: |
| 108 | + f.write(f"{folder_path}/videos,{output_file}\n") |
| 109 | + |
| 110 | + print(f"Dataset information saved to {output_file}") |
| 111 | + print(f"Merge file created at {merge_file}") |
| 112 | + |
| 113 | + |
| 114 | +def parse_args() -> argparse.Namespace: |
| 115 | + parser = argparse.ArgumentParser( |
| 116 | + description='Prepare video dataset information in JSON format') |
| 117 | + parser.add_argument( |
| 118 | + '--folder', |
| 119 | + type=str, |
| 120 | + required=True, |
| 121 | + help='Path to the folder containing videos and prompt.txt') |
| 122 | + parser.add_argument( |
| 123 | + '--output', |
| 124 | + type=str, |
| 125 | + default='videos2caption.json', |
| 126 | + help='Name of the output JSON file (default: videos2caption.json)') |
| 127 | + parser.add_argument('--workers', |
| 128 | + type=int, |
| 129 | + default=32, |
| 130 | + help='Number of worker processes (default: 16)') |
| 131 | + return parser.parse_args() |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + args = parse_args() |
| 136 | + prepare_dataset_json(args.folder, args.output, args.workers) |
0 commit comments