Download dataset_code/sekai/preprocess/cut_video.py from SuperCS/useful_code: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/datasets/SuperCS/useful_code/resolve/aaf853dfec71df594de1823e958ef7533fdc28fa/dataset_code/sekai/preprocess/cut_video.py
- Command line
-
hf download hf://datasets/SuperCS/useful_code@aaf853dfec71df594de1823e958ef7533fdc28fa/dataset_code/sekai/preprocess/cut_video.py
-
curl -L -o cut_video.py https://huggingface.co/datasets/SuperCS/useful_code/resolve/aaf853dfec71df594de1823e958ef7533fdc28fa/dataset_code/sekai/preprocess/cut_video.py
12.7 kB
| import argparse | |
| import subprocess | |
| import os | |
| import glob | |
| from tqdm import tqdm | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| import threading | |
| def extract_video_info_split(input_file): | |
| filename = os.path.splitext(os.path.basename(input_file))[0] | |
| parts = filename.split('_') | |
| start_frame = int(parts[-2]) | |
| end_frame = int(parts[-1]) | |
| # video_id = filename.replace(f"_{parts[-1]}", "").replace(f"_{parts[-2]}", "") | |
| video_id = filename | |
| return video_id, start_frame, end_frame | |
| # if len(parts) == 3: | |
| # video_id = parts[0] | |
| # start_frame = int(parts[1]) | |
| # end_frame = int(parts[2]) | |
| # return video_id, start_frame, end_frame | |
| # else: | |
| # raise ValueError(f"文件名格式不匹配,期望3个部分,实际得到{len(parts)}个: {filename}") | |
| def check_segments_exist(video_id, start_frame, total_frames, output_dir, frames_per_segment): | |
| """ | |
| 检查该视频的所有片段是否已存在 | |
| Returns: | |
| bool: True表示所有片段都存在,False表示有片段缺失 | |
| list: 缺失的片段文件名列表 | |
| """ | |
| missing_segments = [] | |
| current_frame = start_frame | |
| while current_frame < start_frame + total_frames: | |
| segment_end_frame = min(current_frame + frames_per_segment - 1, start_frame + total_frames - 1) | |
| output_filename = f"{video_id}_{current_frame:07d}_{(segment_end_frame+1):07d}.mp4" | |
| output_file = os.path.join(output_dir, output_filename) | |
| if not os.path.exists(output_file): | |
| missing_segments.append(output_filename) | |
| current_frame = segment_end_frame + 1 | |
| return len(missing_segments) == 0, missing_segments | |
| def process_single_video(input_file, output_dir, frames_per_segment=386, skip_existing=True): | |
| try: | |
| video_id, start_frame, original_end_frame = extract_video_info_split(input_file) | |
| # 获取帧率 | |
| result = subprocess.run([ | |
| 'ffprobe', '-v', 'quiet', '-select_streams', 'v:0', | |
| '-show_entries', 'stream=r_frame_rate', '-of', 'csv=p=0', input_file | |
| ], capture_output=True, text=True) | |
| frame_rate_str = result.stdout.strip() | |
| if frame_rate_str and '/' in frame_rate_str: | |
| frame_rate = eval(frame_rate_str) | |
| else: | |
| frame_rate = 30.0 | |
| # 获取总帧数 | |
| result = subprocess.run([ | |
| 'ffprobe', '-v', 'quiet', '-select_streams', 'v:0', | |
| '-show_entries', 'stream=nb_frames', '-of', 'csv=p=0', input_file | |
| ], capture_output=True, text=True) | |
| total_frames = int(result.stdout.strip()) | |
| # 检查文件是否已存在 | |
| if skip_existing: | |
| all_exist, missing_segments = check_segments_exist( | |
| video_id, start_frame, total_frames, output_dir, frames_per_segment | |
| ) | |
| thread_id = threading.current_thread().name | |
| if all_exist: | |
| # 计算应该有多少个片段 | |
| expected_segments = 0 | |
| current_frame = start_frame | |
| while current_frame < start_frame + total_frames: | |
| expected_segments += 1 | |
| segment_end_frame = min(current_frame + frames_per_segment - 1, start_frame + total_frames - 1) | |
| current_frame = segment_end_frame + 1 | |
| print(f"[{thread_id}] 跳过文件: {os.path.basename(input_file)} - 所有{expected_segments}个片段已存在") | |
| return True, expected_segments, os.path.basename(input_file), True # 最后一个参数表示是否跳过 | |
| else: | |
| print(f"[{thread_id}] 处理文件: {os.path.basename(input_file)} - 缺失{len(missing_segments)}个片段") | |
| current_frame = start_frame | |
| # 使用线程安全的打印 | |
| thread_id = threading.current_thread().name | |
| if not skip_existing or not all_exist: | |
| print(f"[{thread_id}] 原视频片段: 第{start_frame}帧 到 第{original_end_frame}帧") | |
| print(f"[{thread_id}] 文件总帧数: {total_frames}") | |
| segment_index = 0 | |
| processed_segments = 0 | |
| while current_frame < start_frame + total_frames: | |
| segment_end_frame = min(current_frame + frames_per_segment - 1, start_frame + total_frames - 1) | |
| output_filename = f"{video_id}_{current_frame:07d}_{(segment_end_frame + 1):07d}.mp4" | |
| output_file = os.path.join(output_dir, output_filename) | |
| if skip_existing and os.path.exists(output_file): | |
| print(f"[{thread_id}] 跳过片段: {output_filename} (已存在)") | |
| pass | |
| else: | |
| start_time = (current_frame - start_frame) / frame_rate | |
| # 修改这里:直接使用帧数计算,确保精确 | |
| actual_frames = segment_end_frame - current_frame + 1 | |
| duration = actual_frames / frame_rate | |
| # 使用更精确的FFmpeg命令 | |
| # subprocess.run([ | |
| # 'ffmpeg', '-ss', str(start_time), '-i', input_file, | |
| # '-frames:v', str(actual_frames), | |
| # '-c:v', 'libx264', '-crf', '0', # 无损编码 | |
| # '-preset', 'ultrafast', # 快速编码 | |
| # '-c:a', 'copy', | |
| # output_file, '-y' | |
| # ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
| subprocess.run([ | |
| 'ffmpeg', '-ss', str(start_time), '-i', input_file, | |
| '-t', str(duration), | |
| '-c', 'copy', # 直接拷贝,不重编码 | |
| output_file, '-y' | |
| ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
| print(f"[{thread_id}] 生成片段: {output_filename} ({actual_frames}帧)") | |
| processed_segments += 1 | |
| current_frame = segment_end_frame + 1 | |
| segment_index += 1 | |
| if not skip_existing or not all_exist: | |
| if processed_segments > 0: | |
| print(f"[{thread_id}] 完成: {os.path.basename(input_file)} - 新生成{processed_segments}个片段") | |
| else: | |
| print(f"[{thread_id}] 完成: {os.path.basename(input_file)} - 所有片段都已存在") | |
| return True, segment_index, os.path.basename(input_file), False | |
| except Exception as e: | |
| thread_id = threading.current_thread().name | |
| print(f"[{thread_id}] 处理文件 {input_file} 时出错: {str(e)}") | |
| return False, 0, os.path.basename(input_file), False | |
| def batch_process_videos(input_folder, output_dir, frames_per_segment=386, max_workers=4, | |
| skip_existing=True, cur_part=None, total_part=None): | |
| """ | |
| 多线程批量处理视频 | |
| Args: | |
| input_folder: 输入文件夹路径 | |
| output_dir: 输出目录 | |
| frames_per_segment: 每个片段的帧数 | |
| max_workers: 最大线程数,建议设置为CPU核心数的1-2倍 | |
| skip_existing: 是否跳过已存在的文件 | |
| cur_part: 当前处理的部分 (1-based, 从1开始) | |
| total_part: 总共分割的部分数 | |
| """ | |
| # 创建输出目录 | |
| os.makedirs(output_dir, exist_ok=True) | |
| # 查找所有mp4文件 | |
| video_files = glob.glob(os.path.join(input_folder, "*.mp4")) | |
| if not video_files: | |
| print(f"在目录 {input_folder} 中未找到mp4文件") | |
| return | |
| # 对视频文件进行排序,确保分割结果的一致性 | |
| video_files.sort() | |
| # 如果指定了分割参数,则对视频文件列表进行分割 | |
| if cur_part is not None and total_part is not None: | |
| if not (1 <= cur_part <= total_part): | |
| raise ValueError(f"cur_part ({cur_part}) 必须在 1 到 {total_part} 之间") | |
| total_videos = len(video_files) | |
| videos_per_part = total_videos // total_part | |
| remainder = total_videos % total_part | |
| # 计算当前部分的起始和结束索引 | |
| if cur_part <= remainder: | |
| # 前remainder个部分每个多分配1个文件 | |
| start_idx = (cur_part - 1) * (videos_per_part + 1) | |
| end_idx = start_idx + videos_per_part + 1 | |
| else: | |
| # 后面的部分按标准数量分配 | |
| start_idx = remainder * (videos_per_part + 1) + (cur_part - remainder - 1) * videos_per_part | |
| end_idx = start_idx + videos_per_part | |
| video_files = video_files[start_idx:end_idx] | |
| print(f"分割处理模式: 第 {cur_part} 部分 / 共 {total_part} 部分") | |
| print(f"原始视频总数: {total_videos}") | |
| print(f"当前部分处理: {len(video_files)} 个视频 (索引 {start_idx} 到 {end_idx-1})") | |
| if not video_files: | |
| print("当前部分没有需要处理的视频文件") | |
| return | |
| print(f"找到 {len(video_files)} 个视频文件") | |
| print(f"输出目录: {output_dir}") | |
| print(f"使用 {max_workers} 个线程进行处理") | |
| print(f"跳过已存在文件: {'是' if skip_existing else '否'}") | |
| total_segments = 0 | |
| success_count = 0 | |
| skipped_count = 0 | |
| failed_files = [] | |
| # 使用ThreadPoolExecutor进行多线程处理 | |
| with ThreadPoolExecutor(max_workers=max_workers) as executor: | |
| # 提交所有任务 | |
| future_to_file = { | |
| executor.submit(process_single_video, video_file, output_dir, frames_per_segment, skip_existing): video_file | |
| for video_file in video_files | |
| } | |
| # 使用tqdm显示进度条 | |
| progress_desc = "处理进度" | |
| if cur_part is not None and total_part is not None: | |
| progress_desc = f"处理进度 ({cur_part}/{total_part})" | |
| with tqdm(total=len(video_files), desc=progress_desc) as pbar: | |
| for future in as_completed(future_to_file): | |
| video_file = future_to_file[future] | |
| try: | |
| success, segments, filename, was_skipped = future.result() | |
| if success: | |
| success_count += 1 | |
| total_segments += segments | |
| if was_skipped: | |
| skipped_count += 1 | |
| else: | |
| failed_files.append(filename) | |
| except Exception as exc: | |
| print(f'视频文件 {video_file} 处理时发生异常: {exc}') | |
| failed_files.append(os.path.basename(video_file)) | |
| finally: | |
| pbar.update(1) | |
| print(f"\n批量处理完成!") | |
| if cur_part is not None and total_part is not None: | |
| print(f"当前部分 ({cur_part}/{total_part}) 处理结果:") | |
| print(f"成功处理: {success_count}/{len(video_files)} 个视频") | |
| print(f"跳过文件: {skipped_count} 个视频 (所有片段已存在)") | |
| print(f"实际处理: {success_count - skipped_count} 个视频") | |
| print(f"总共生成: {total_segments} 个片段") | |
| if failed_files: | |
| print(f"处理失败的文件: {failed_files}") | |
| def main(): | |
| parser = argparse.ArgumentParser(description='批量处理视频文件,提取帧并分段保存') | |
| parser.add_argument('--input_folder', type=str, default="./", help='输入文件夹路径') | |
| parser.add_argument('--output_dir', type=str, default="./dummy_segments_33", help='输出目录路径') | |
| parser.add_argument('--frames-per-segment', type=int, default=193, help='每段的帧数') | |
| parser.add_argument('--max-workers', type=int, default=8, help='线程数') | |
| parser.add_argument('--skip-existing', action='store_true', default=True, help='跳过已存在的文件') | |
| parser.add_argument('--no-skip-existing', dest='skip_existing', action='store_false', help='强制重新处理') | |
| parser.add_argument('--cur-part', type=int, default=1, help='当前处理的部分') | |
| parser.add_argument('--total-part', type=int, default=1, help='总共分成几部分') | |
| args = parser.parse_args() | |
| batch_process_videos( | |
| input_folder=args.input_folder, | |
| output_dir=args.output_dir, | |
| frames_per_segment=args.frames_per_segment, | |
| max_workers=args.max_workers, | |
| skip_existing=args.skip_existing, | |
| cur_part=args.cur_part, | |
| total_part=args.total_part | |
| ) | |
| if __name__ == "__main__": | |
| main() |