from tqdm import tqdm import pandas as pd import json import os from concurrent.futures import ThreadPoolExecutor, as_completed import threading def process_single_row(args): """ 处理单个行的函数 Args: args: 元组,包含 (index, row, video_folder) Returns: tuple: (index, prompt) """ index, row, video_folder = args try: # 构建caption.json文件路径 prompt_path = os.path.join(video_folder, row["annotation path"], "caption.json") # 读取JSON文件 with open(prompt_path, 'r', encoding='utf-8') as f: data = json.load(f) # 构建prompt prompt = data['SceneDescription'] + " " + data["CameraMotion"] return (index, prompt) except FileNotFoundError: print(f"Warning: File not found - {prompt_path}") return (index, "") except KeyError as e: print(f"Warning: Key {e} not found in {prompt_path}") return (index, "") except Exception as e: print(f"Error processing row {index}: {e}") return (index, "") def add_prompt_to_csv(csv_path, video_folder, output_path=None, max_workers=4): """ 为CSV文件添加prompt字段(多线程版本) Args: csv_path: 输入CSV文件路径 video_folder: 视频文件夹路径(self.video_folder的值) output_path: 输出CSV文件路径,如果为None则覆盖原文件 max_workers: 最大线程数,默认为4 """ # 读取CSV文件 df = pd.read_csv(csv_path) # 准备任务参数 tasks = [(index, row, video_folder) for index, row in df.iterrows()] # 初始化结果字典 results = {} # 使用ThreadPoolExecutor进行多线程处理 with ThreadPoolExecutor(max_workers=max_workers) as executor: # 提交所有任务 future_to_index = {executor.submit(process_single_row, task): task[0] for task in tasks} # 收集结果,使用tqdm显示进度 for future in tqdm(as_completed(future_to_index), desc="Processing videos", total=len(tasks)): try: index, prompt = future.result() results[index] = prompt except Exception as e: index = future_to_index[future] print(f"Error in thread processing row {index}: {e}") results[index] = "" # 按索引顺序构建prompt列表 prompts = [results[i] for i in range(len(df))] # 添加prompt列到DataFrame df['prompt'] = prompts # 保存结果 if output_path is None: output_path = csv_path df.to_csv(output_path, index=False) print(f"Updated CSV saved to: {output_path}") return df # 如果需要更高的性能,也可以考虑使用进程池版本 def add_prompt_to_csv_multiprocess(csv_path, video_folder, output_path=None, max_workers=4): """ 为CSV文件添加prompt字段(多进程版本) 适用于CPU密集型任务 Args: csv_path: 输入CSV文件路径 video_folder: 视频文件夹路径 output_path: 输出CSV文件路径,如果为None则覆盖原文件 max_workers: 最大进程数,默认为4 """ from concurrent.futures import ProcessPoolExecutor # 读取CSV文件 df = pd.read_csv(csv_path) # 准备任务参数 tasks = [(index, row, video_folder) for index, row in df.iterrows()] # 初始化结果字典 results = {} # 使用ProcessPoolExecutor进行多进程处理 with ProcessPoolExecutor(max_workers=max_workers) as executor: # 提交所有任务 future_to_index = {executor.submit(process_single_row, task): task[0] for task in tasks} # 收集结果,使用tqdm显示进度 for future in tqdm(as_completed(future_to_index), desc="Processing videos", total=len(tasks)): try: index, prompt = future.result() results[index] = prompt except Exception as e: index = future_to_index[future] print(f"Error in process processing row {index}: {e}") results[index] = "" # 按索引顺序构建prompt列表 prompts = [results[i] for i in range(len(df))] # 添加prompt列到DataFrame df['prompt'] = prompts # 保存结果 if output_path is None: output_path = csv_path df.to_csv(output_path, index=False) print(f"Updated CSV saved to: {output_path}") return df # 使用示例 if __name__ == "__main__": # 替换为您的实际路径 csv_file_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step1.csv" output_csv_file_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final/data/SpatialVID_HQ_step2.csv" video_folder_path = "/mnt/bn/yufan-dev-my/ysh/Ckpts/SpatialVID/SpatialVID-HQ-Final" # 使用多线程版本(推荐用于I/O密集型任务) updated_df = add_prompt_to_csv(csv_file_path, video_folder_path, output_csv_file_path, max_workers=128) # 如果是CPU密集型任务,可以使用多进程版本 # updated_df = add_prompt_to_csv_multiprocess(csv_file_path, video_folder_path, output_csv_file_path, max_workers=4)