useful_code / dataset_code /cp_high_motion.py
SuperCS's picture
Add files using upload-large-folder tool
e31e7b4 verified
import os
import shutil
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from tqdm import tqdm
import threading
def copy_single_file(pt_file, output_folder):
"""
复制单个文件的函数
Args:
pt_file: PT文件路径
output_folder: 输出文件夹路径
Returns:
tuple: (是否成功, 文件名)
"""
try:
pt_filename = pt_file.name
destination = Path(output_folder) / pt_filename
shutil.copy2(pt_file, destination)
return True, pt_filename
except Exception as e:
return False, f"复制 {pt_file.name} 失败: {str(e)}"
def copy_matching_pt_files(json_folder, pt_folder, matched_output_folder, unmatched_output_folder, max_workers=4):
"""
根据JSON文件的存在情况,多线程复制对应的PT文件到不同文件夹
Args:
json_folder: JSON文件所在的文件夹路径
pt_folder: PT文件所在的文件夹路径
matched_output_folder: 匹配文件的输出文件夹路径
unmatched_output_folder: 不匹配文件的输出文件夹路径
max_workers: 最大线程数,默认为4
"""
# 创建输出文件夹(如果不存在)
os.makedirs(matched_output_folder, exist_ok=True)
os.makedirs(unmatched_output_folder, exist_ok=True)
# 获取所有JSON文件的ID
print("正在扫描JSON文件...")
json_files = list(Path(json_folder).glob("*.json"))
json_ids = set()
for json_file in tqdm(json_files, desc="扫描JSON文件"):
# 提取文件名(不含扩展名)作为ID
file_id = json_file.stem
json_ids.add(file_id)
print(f"找到 {len(json_ids)} 个JSON文件")
# 查找匹配和不匹配的PT文件
print("正在分类PT文件...")
pt_files = list(Path(pt_folder).glob("*.pt"))
matching_files = []
unmatching_files = []
for pt_file in tqdm(pt_files, desc="分类PT文件"):
pt_filename = pt_file.name
# 检查PT文件名是否以任何JSON ID开头
is_matched = False
for json_id in json_ids:
if pt_filename.startswith(json_id):
matching_files.append(pt_file)
is_matched = True
break # 找到匹配后跳出内层循环
if not is_matched:
unmatching_files.append(pt_file)
print(f"找到 {len(matching_files)} 个匹配的PT文件")
print(f"找到 {len(unmatching_files)} 个不匹配的PT文件")
# 使用线程锁保护计数器
copy_lock = threading.Lock()
matched_copied = 0
matched_failed = 0
unmatched_copied = 0
unmatched_failed = 0
def process_files(files, output_folder, file_type):
nonlocal matched_copied, matched_failed, unmatched_copied, unmatched_failed
if not files:
print(f"没有{file_type}文件需要复制")
return
with ThreadPoolExecutor(max_workers=max_workers) as executor:
# 提交所有复制任务
future_to_file = {
executor.submit(copy_single_file, pt_file, output_folder): pt_file
for pt_file in files
}
# 使用tqdm显示进度
with tqdm(total=len(files), desc=f"复制{file_type}文件") as pbar:
for future in as_completed(future_to_file):
success, result = future.result()
with copy_lock:
if success:
if file_type == "匹配":
matched_copied += 1
pbar.set_postfix({
'已复制': matched_copied,
'失败': matched_failed,
'当前': result
})
else:
unmatched_copied += 1
pbar.set_postfix({
'已复制': unmatched_copied,
'失败': unmatched_failed,
'当前': result
})
else:
if file_type == "匹配":
matched_failed += 1
pbar.set_postfix({
'已复制': matched_copied,
'失败': matched_failed
})
else:
unmatched_failed += 1
pbar.set_postfix({
'已复制': unmatched_copied,
'失败': unmatched_failed
})
print(f"\n错误: {result}")
pbar.update(1)
# 复制匹配的文件
if matching_files:
print("\n开始复制匹配的文件...")
process_files(matching_files, matched_output_folder, "匹配")
# 复制不匹配的文件
if unmatching_files:
print("\n开始复制不匹配的文件...")
process_files(unmatching_files, unmatched_output_folder, "不匹配")
# 输出最终统计
print(f"\n复制完成!")
print(f"匹配文件 - 成功复制: {matched_copied} 个, 失败: {matched_failed} 个")
print(f"不匹配文件 - 成功复制: {unmatched_copied} 个, 失败: {unmatched_failed} 个")
print(f"匹配文件输出目录: {matched_output_folder}")
print(f"不匹配文件输出目录: {unmatched_output_folder}")
# 使用示例
if __name__ == "__main__":
# 设置文件夹路径
json_folder = "/mnt/bn/yufan-dev-my/ysh/Datasets/sft_sftnews_videos/new_metadata/high_motion"
pt_folder = "/mnt/bn/yufan-dev-my/ysh/Datasets/fp_offload_latents"
matched_output_folder = "/mnt/bn/yufan-dev-my/ysh/Datasets/fp_offload_latents/high_motion"
unmatched_output_folder = "/mnt/bn/yufan-dev-my/ysh/Datasets/fp_offload_latents/low_motion"
os.makedirs(matched_output_folder, exist_ok=True)
os.makedirs(unmatched_output_folder, exist_ok=True)
# 执行复制操作(可以调整max_workers参数控制线程数)
copy_matching_pt_files(
json_folder,
pt_folder,
matched_output_folder,
unmatched_output_folder,
max_workers=32
)