TainU commited on
Commit
4e3f5cf
·
verified ·
1 Parent(s): 76e41e4

Delete preprocess_videos.py

Browse files
Files changed (1) hide show
  1. preprocess_videos.py +0 -137
preprocess_videos.py DELETED
@@ -1,137 +0,0 @@
1
- import os
2
- import sys
3
- import subprocess
4
- import cv2
5
- import numpy as np
6
- from decord import VideoReader, cpu
7
- from tqdm import tqdm
8
- from PIL import Image
9
- import argparse
10
- import re
11
-
12
- def get_new_height_width(height, width, longest_side_size=512):
13
- if height > width:
14
- new_height = longest_side_size
15
- new_width = int(new_height * width / height) # floor value
16
- else:
17
- new_width = longest_side_size
18
- new_height = int(new_width * height / width) # floor value
19
- return new_height, new_width
20
-
21
- def downsample_video(input_video_path, output_video_path):
22
- print(f"Downsampling video: {input_video_path} to {output_video_path}")
23
- if os.path.exists(output_video_path):
24
- print('Downsampled video exists. Exiting now...')
25
- return
26
-
27
- try:
28
- print("Attempting to use FFmpeg for fast downsampling...")
29
- probe_cmd = ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
30
- "stream=width,height,r_frame_rate,duration", "-of", "csv=p=0", input_video_path]
31
-
32
- try:
33
- probe_output = subprocess.check_output(probe_cmd, universal_newlines=True).strip().split(',')
34
- width, height, fps_fraction, duration = probe_output
35
- original_fps = eval(fps_fraction)
36
- width, height = int(width), int(height)
37
- new_height, new_width = get_new_height_width(height, width, longest_side_size=512)
38
- total_duration = float(duration)
39
- except:
40
- video_reader = VideoReader(input_video_path, ctx=cpu(0), num_threads=0)
41
- original_fps = video_reader.get_avg_fps()
42
- first_frame = video_reader[0].asnumpy()
43
- height, width, _ = first_frame.shape
44
- new_height, new_width = get_new_height_width(height, width, longest_side_size=512)
45
- total_duration = len(video_reader) / original_fps
46
- del video_reader
47
-
48
- temp_output_path = output_video_path.split('.')[0] + '.temp.mp4'
49
- if os.path.exists(temp_output_path):
50
- os.remove(temp_output_path)
51
-
52
- ffmpeg_cmd = [
53
- "ffmpeg", "-y",
54
- "-i", input_video_path,
55
- "-vf", f"fps={original_fps},scale={new_width}:{new_height}",
56
- "-c:v", "libx264",
57
- "-preset", "medium",
58
- "-crf", "23",
59
- "-g", "60",
60
- "-bf", "2",
61
- "-an",
62
- "-pix_fmt", "yuv420p",
63
- temp_output_path
64
- ]
65
-
66
- # 使用tqdm显示ffmpeg的进度
67
- with tqdm(total=total_duration, desc=f"Processing {os.path.basename(input_video_path)}", leave=False) as pbar:
68
- process = subprocess.Popen(ffmpeg_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
69
- for line in process.stderr:
70
- # 匹配ffmpeg输出中的时间信息
71
- match = re.search(r'time=(\d+:\d+:\d+\.\d+)', line)
72
- if match:
73
- time_str = match.group(1)
74
- h, m, s = map(float, time_str.split(':'))
75
- current_time = h * 3600 + m * 60 + s
76
- pbar.update(current_time - pbar.n)
77
- process.wait()
78
-
79
- if process.returncode == 0:
80
- os.replace(temp_output_path, output_video_path)
81
- print(f"Successfully downsampled video using FFmpeg")
82
- return
83
-
84
- except (subprocess.SubprocessError, FileNotFoundError) as e:
85
- print(f"FFmpeg method failed: {str(e)}. Falling back to Python implementation.")
86
- if os.path.exists(temp_output_path):
87
- os.remove(temp_output_path)
88
- raise
89
-
90
-
91
- def process_video(filename, source_dir, target_dir):
92
- if '_' not in filename and filename.endswith(('.mp4', '.avi', '.mov', '.mkv')):
93
- input_video_path = os.path.join(source_dir, filename)
94
- output_video_path = os.path.join(target_dir, filename)
95
- print(f"Processing {filename}...")
96
-
97
- downsample_video(input_video_path, output_video_path)
98
-
99
- def main():
100
- parser = argparse.ArgumentParser(description="Downsample videos from a source directory to a target directory.")
101
- parser.add_argument('source_dir', type=str, help='The directory containing the source videos.')
102
- parser.add_argument('target_dir', type=str, help='The directory to save the downsampled videos.')
103
- parser.add_argument('video_ids_file', type=str, help='The file containing video IDs to process.')
104
-
105
- args = parser.parse_args()
106
-
107
- source_dir = args.source_dir
108
- target_dir = args.target_dir
109
- video_ids_file = args.video_ids_file
110
-
111
- if not os.path.exists(target_dir):
112
- os.makedirs(target_dir)
113
-
114
- with open(video_ids_file, 'r') as f:
115
- video_ids = {line.strip() for line in f if line.strip()}
116
-
117
- filenames = [f for f in os.listdir(source_dir) if f.split('.')[0] in video_ids and f.endswith(('.mp4', '.avi', '.mov', '.mkv'))]
118
-
119
- print(f"Found {len(filenames)} videos to process.")
120
-
121
- if not filenames:
122
- print("No videos found to process. Exiting.")
123
- return
124
-
125
- print(f"Processing {len(filenames)} videos sequentially...")
126
- with tqdm(total=len(filenames), desc="Overall Progress") as pbar:
127
- for filename in filenames:
128
- try:
129
- process_video(filename, source_dir, target_dir)
130
- except Exception as e:
131
- print(f"An error occurred during processing {filename}: {e}")
132
- pbar.update(1)
133
-
134
- print("Processing completed successfully.")
135
-
136
- if __name__ == "__main__":
137
- main()