File size: 6,665 Bytes
e31e7b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
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
    )