File size: 5,502 Bytes
e051419 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
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)
|