Caesarrr commited on
Commit
18309e8
·
verified ·
1 Parent(s): e012859

Add files using upload-large-folder tool

Browse files
Files changed (2) hide show
  1. scripts/analyze_errors.py +126 -0
  2. scripts/remove.py +183 -0
scripts/analyze_errors.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ from collections import Counter
4
+
5
+ # ================= 配置区域 =================
6
+ # 1. 你的错误日志文件路径
7
+ LOG_FILE = 'copy_errors.log'
8
+
9
+ # 2. 图片路径中 category 和 sequence 的位置模式
10
+ # 假设路径是: data/raw_images/{category}/{sequence}/images/filename.jpg
11
+ # 我们使用正则来提取。
12
+ # 解释:
13
+ # data/raw_images/ -> 匹配前缀 (根据你的实际路径调整,或者用通用的)
14
+ # ([^/]+) -> 第一个捕获组: category (不包含/的任意字符)
15
+ # / -> 分隔符
16
+ # ([^/]+) -> 第二个捕获组: sequence
17
+ # /images/ -> 后面紧跟着 images 目录
18
+ PATH_PATTERN = re.compile(r'data/raw_images/([^/]+)/([^/]+)/images/')
19
+ # ===========================================
20
+
21
+ def analyze_log(log_file):
22
+ if not os.path.exists(log_file):
23
+ print(f"[Error] 找不到日志文件: {log_file}")
24
+ return
25
+
26
+ print(f"[*] 正在分析日志文件: {log_file} ...")
27
+
28
+ failed_categories = set()
29
+ failed_sequences = set()
30
+
31
+ # 用于统计每个 category 和 sequence 缺失了多少张图
32
+ category_counter = Counter()
33
+ sequence_counter = Counter()
34
+
35
+ # 用于存储 {category: [sequence1, sequence2, ...]} 的层级关系
36
+ cat_seq_map = {}
37
+
38
+ with open(log_file, 'r', encoding='utf-8') as f:
39
+ current_path = ""
40
+
41
+ for line in f:
42
+ line = line.strip()
43
+
44
+ # 提取日志中的图片路径行
45
+ # 日志格式: [FAIL] 图片路径: data/raw_images/bowl/...
46
+ if line.startswith("[FAIL] 图片路径:"):
47
+ # 提取路径部分
48
+ path_str = line.split(": ", 1)[1]
49
+
50
+ # 使用正则提取 category 和 sequence
51
+ match = PATH_PATTERN.search(path_str)
52
+ if match:
53
+ category = match.group(1)
54
+ sequence = match.group(2)
55
+
56
+ # 存入集合 (去重)
57
+ failed_categories.add(category)
58
+ failed_sequences.add(sequence)
59
+
60
+ # 计数
61
+ category_counter[category] += 1
62
+ sequence_counter[sequence] += 1
63
+
64
+ # 构建层级关系
65
+ if category not in cat_seq_map:
66
+ cat_seq_map[category] = set()
67
+ cat_seq_map[category].add(sequence)
68
+ else:
69
+ # 如果正则匹配失败,可能路径格式不一样,打印出来看看
70
+ # print(f"[Warning] 无法解析路径结构: {path_str}")
71
+ pass
72
+
73
+ # ================= 输出结果 =================
74
+ print("\n" + "="*50)
75
+ print("分析报告 (Analysis Report)")
76
+ print("="*50)
77
+
78
+ print(f"\n1. 缺失图片涉及的 Category 总数: {len(failed_categories)}")
79
+ print("-" * 30)
80
+ # 按缺失数量从多到少排序
81
+ for cat, count in category_counter.most_common():
82
+ print(f" - {cat}: 缺失 {count} 张图")
83
+
84
+ print(f"\n2. 缺失图片涉及的 Sequence 总数: {len(failed_sequences)}")
85
+ print("-" * 30)
86
+ # 如果 sequence 太多,只打印前 20 个
87
+ top_n = 20
88
+ for seq, count in sequence_counter.most_common(top_n):
89
+ print(f" - {seq}: 缺失 {count} 张图")
90
+ if len(sequence_counter) > top_n:
91
+ print(f" ... (还有 {len(sequence_counter) - top_n} 个 sequence)")
92
+
93
+ print(f"\n3. 详细层级结构 (Category -> Sequence)")
94
+ print("-" * 30)
95
+ for cat in sorted(cat_seq_map.keys()):
96
+ seqs = cat_seq_map[cat]
97
+ print(f"[{cat}] 下有 {len(seqs)} 个有问题的 sequence:")
98
+ # 将 set 转为 list 并排序,方便查看
99
+ sorted_seqs = sorted(list(seqs))
100
+
101
+ # 打印方式:如果很多,就一行打印多个
102
+ # 这里简单处理,每行打印一个,或者你可以改成逗号分隔
103
+ print(f" {', '.join(sorted_seqs)}")
104
+ print("")
105
+
106
+ # 保存结果到文件
107
+ output_file = "missing_stats.txt"
108
+ with open(output_file, 'w', encoding='utf-8') as f_out:
109
+ f_out.write("=== 缺失数据统计 ===\n")
110
+ f_out.write(f"Category 总数: {len(failed_categories)}\n")
111
+ f_out.write(f"Sequence 总数: {len(failed_sequences)}\n\n")
112
+
113
+ f_out.write("=== Category 列表 (格式: 名称 [缺失数量]) ===\n")
114
+ for cat, count in category_counter.most_common():
115
+ f_out.write(f"{cat} [{count}]\n")
116
+
117
+ f_out.write("\n=== Sequence 列表 (按 Category 分组) ===\n")
118
+ for cat in sorted(cat_seq_map.keys()):
119
+ f_out.write(f"\n[{cat}]\n")
120
+ for seq in sorted(list(cat_seq_map[cat])):
121
+ f_out.write(f" - {seq} (缺失 {sequence_counter[seq]} 张)\n")
122
+
123
+ print(f"\n[*] 详细统计已保存至: {output_file}")
124
+
125
+ if __name__ == "__main__":
126
+ analyze_log(LOG_FILE)
scripts/remove.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import re
4
+ import shutil
5
+ from collections import defaultdict
6
+
7
+ # ===================== 配置区域 =====================
8
+
9
+ # 1. 错误日志文件路径
10
+ LOG_FILE = 'copy_errors.log'
11
+
12
+ # 2. JSONL 文件的根目录 (脚本会去这里找对应的 jsonl 文件进行修改)
13
+ QUESTION_ROOT = 'data/questions'
14
+
15
+ # 3. 过滤条件 (可选)
16
+ # 如果只想删除特定 category 或 sequence 的问题,请在此填入字符串。
17
+ # 如果想处理日志中所有记录的错误,请设置为 None
18
+ TARGET_CATEGORY = None # 例如: 'bowl' 或 None
19
+ TARGET_SEQUENCE = None # 例如: '70_6141_14002' 或 None
20
+
21
+ # ===================================================
22
+
23
+ def parse_log_and_get_ids(log_file, target_cat=None, target_seq=None):
24
+ """
25
+ 解析日志文件,获取需要删除的 {文件名: {ID集合}}
26
+ 支持按 category 和 sequence 过滤
27
+ """
28
+ if not os.path.exists(log_file):
29
+ print(f"[Error] 找不到日志文件: {log_file}")
30
+ return {}
31
+
32
+ print(f"[*] 正在解析日志: {log_file} ...")
33
+ if target_cat:
34
+ print(f" -> 过滤条件 Category: {target_cat}")
35
+ if target_seq:
36
+ print(f" -> 过滤条件 Sequence: {target_seq}")
37
+
38
+ # 存储结构: { 'train_2.jsonl': {'task3_id_1', 'task3_id_2'}, ... }
39
+ files_to_clean = defaultdict(set)
40
+
41
+ # 正则用于提取路径中的 category 和 sequence
42
+ # 假设路径结构: .../raw_images/{category}/{sequence}/images/...
43
+ path_pattern = re.compile(r'data/raw_images/([^/]+)/([^/]+)/images/')
44
+
45
+ current_category = None
46
+ current_sequence = None
47
+ is_target_block = False # 标记当前错误块是否符合过滤条件
48
+
49
+ with open(log_file, 'r', encoding='utf-8') as f:
50
+ for line in f:
51
+ line = line.strip()
52
+
53
+ # 1. 识别错误块的开始 (提取图片路径信息)
54
+ if line.startswith("[FAIL] 图片路径:"):
55
+ path_str = line.split(": ", 1)[1]
56
+ match = path_pattern.search(path_str)
57
+
58
+ if match:
59
+ current_category = match.group(1)
60
+ current_sequence = match.group(2)
61
+
62
+ # 判断是否符合用户过滤条件
63
+ cat_match = (target_cat is None) or (current_category == target_cat)
64
+ seq_match = (target_seq is None) or (current_sequence == target_sequence)
65
+
66
+ is_target_block = cat_match and seq_match
67
+ else:
68
+ # 如果路径解析失败,为了安全起见,默认不处理,或者你可以选择处理
69
+ is_target_block = False
70
+
71
+ # 2. 提取受影响的问题 ID
72
+ # 格式: train_2.jsonl -> ID:task3_209_22099_44906_71
73
+ elif "-> ID:" in line:
74
+ if is_target_block:
75
+ try:
76
+ # 分割文件名和ID
77
+ parts = line.split("-> ID:")
78
+ filename = parts[0].strip()
79
+ q_id = parts[1].strip()
80
+
81
+ files_to_clean[filename].add(q_id)
82
+ except IndexError:
83
+ pass
84
+
85
+ total_ids = sum(len(ids) for ids in files_to_clean.values())
86
+ print(f"[*] 解析完成。共发现 {len(files_to_clean)} 个文件中的 {total_ids} 个问题需要删除。")
87
+ return files_to_clean
88
+
89
+ def clean_jsonl_files(question_root, files_to_clean):
90
+ """
91
+ 遍历目录,找到对应的 jsonl 文件并删除指定 ID 的行
92
+ """
93
+ if not files_to_clean:
94
+ print("[*] 没有需要删除的内容。")
95
+ return
96
+
97
+ print(f"[*] 开始扫描目录 {question_root} 并执行删除操作...")
98
+
99
+ modified_count = 0
100
+ deleted_lines_count = 0
101
+
102
+ # 遍历所有文件
103
+ for root, dirs, files in os.walk(question_root):
104
+ for file in files:
105
+ # 如果这个文件在我们的清理列表中
106
+ if file in files_to_clean:
107
+ file_path = os.path.join(root, file)
108
+ ids_to_remove = files_to_clean[file]
109
+
110
+ # 执行清理
111
+ removed = process_single_file(file_path, ids_to_remove)
112
+
113
+ if removed > 0:
114
+ modified_count += 1
115
+ deleted_lines_count += removed
116
+ # 从列表中移除已处理的文件(优化后续查找,虽然文件名可能重复,但这里假设文件名唯一对应任务)
117
+ # 注意:如果不同目录下有同名文件 (如 task1/train.jsonl, task2/train.jsonl),
118
+ # 且日志里只记了 "train.jsonl",我们需要对所有叫 train.jsonl 的都检查一遍 ID。
119
+ # 所以这里不从 files_to_clean 中 pop,而是让它继续检查。
120
+
121
+ print("\n" + "="*30)
122
+ print("清理任务完成 Summary:")
123
+ print(f"��改文件数: {modified_count}")
124
+ print(f"删除问题数: {deleted_lines_count}")
125
+ print("="*30)
126
+
127
+ def process_single_file(file_path, ids_to_remove):
128
+ """
129
+ 读取文件,过滤掉在 ids_to_remove 中的行,重写文件
130
+ """
131
+ temp_file = file_path + '.tmp'
132
+ removed_count = 0
133
+
134
+ try:
135
+ with open(file_path, 'r', encoding='utf-8') as f_in, \
136
+ open(temp_file, 'w', encoding='utf-8') as f_out:
137
+
138
+ for line in f_in:
139
+ line = line.strip()
140
+ if not line:
141
+ continue
142
+
143
+ should_delete = False
144
+ try:
145
+ data = json.loads(line)
146
+ if data.get('id') in ids_to_remove:
147
+ should_delete = True
148
+ except json.JSONDecodeError:
149
+ pass
150
+
151
+ if should_delete:
152
+ removed_count += 1
153
+ else:
154
+ f_out.write(line + '\n')
155
+
156
+ # 如果有删除操作,则用新文件替换旧文件
157
+ if removed_count > 0:
158
+ shutil.move(temp_file, file_path)
159
+ print(f" [Cleaned] {os.path.basename(file_path)}: 删除了 {removed_count} 行")
160
+ else:
161
+ # 如果没变化,删除临时文件
162
+ os.remove(temp_file)
163
+
164
+ except Exception as e:
165
+ print(f"[!] 处理文件 {file_path} 时出错: {e}")
166
+ if os.path.exists(temp_file):
167
+ os.remove(temp_file)
168
+ return 0
169
+
170
+ return removed_count
171
+
172
+ if __name__ == "__main__":
173
+ # 1. 获取删除列表
174
+ clean_map = parse_log_and_get_ids(LOG_FILE, TARGET_CATEGORY, TARGET_SEQUENCE)
175
+
176
+ # 2. 执行删除
177
+ if clean_map:
178
+ # 二次确认防止误删
179
+ confirm = input(f"警告: 即将从原始 jsonl 文件中永久删除数据。\n输入 'yes' 确认执行: ")
180
+ if confirm.lower() == 'yes':
181
+ clean_jsonl_files(QUESTION_ROOT, clean_map)
182
+ else:
183
+ print("[*] 操作已取消。")