Caesarrr commited on
Commit
565bf0c
·
verified ·
1 Parent(s): 1fb80ce

Upload ./scripts/rewrite.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/rewrite.py +422 -0
scripts/rewrite.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 脚本名称: rewrite.py
3
+ 功能: 批量重写 Task 1, 2, 3 数据集中的 CoT (Chain of Thought) 推理文本。
4
+
5
+ 【功能描述】
6
+ 该脚本读取原始 JSONL 文件,保持图像路径、几何参数、正确答案不变,
7
+ 仅根据 metadata 中的几何信息(角度、步骤)重新生成 'cot_trace' 字段。
8
+ 支持通过修改脚本顶部的模板列表来丰富语言的多样性。
9
+
10
+ 【环境依赖】
11
+ python >= 3.6
12
+ tqdm
13
+
14
+ 【如何运行】
15
+ 在终端中使用以下命令运行。请确保 --input_dir 指向包含 jsonl 文件的根目录。
16
+
17
+ 1. 针对 Task 1 (单步预测):
18
+ python scripts/rewrite.py --task_type task1 --input_dir ./data/task1 --output_dir ./data/task1_new
19
+
20
+ 2. 针对 Task 2 (多步指令跟随):
21
+ python scripts/rewrite.py --task_type task2 --input_dir ./data/task2 --output_dir ./data/task2_new
22
+
23
+ 3. 针对 Task 3 (序列排序):
24
+ python scripts/rewrite.py --task_type task3 --input_dir ./data/task3 --output_dir ./data/task3_new
25
+
26
+ 【参数说明】
27
+ --input_dir : 输入文件夹路径(脚本会递归查找该目录下的所有 .jsonl 文件)
28
+ --output_dir: 输出文件夹路径(保持原有的目录结构)
29
+ --task_type : 任务类型,必须是 [task1, task2, task3] 之一
30
+ --seed : 随机种子,用于控制模板选择的随机性 (默认 42)
31
+ --debug : 开启调试模式,打印错误信息
32
+ """
33
+
34
+ import os
35
+ import json
36
+ import re
37
+ import argparse
38
+ from glob import glob
39
+ from tqdm import tqdm
40
+ import random
41
+
42
+ # ==========================================
43
+ # 1. 语言模板库 (Language Templates)
44
+ # ==========================================
45
+ #
46
+ # 【如何增加/修改模板】
47
+ # 1. 每个列表包含多个字符串,脚本会随机选择其中一条。
48
+ # 2. 必须保留大括号 {} 包裹的占位符,例如 {angle}, {direction}。
49
+ # 3. 如果你想增加新的表达方式,直接在对应的列表中添加字符串即可。
50
+ #
51
+ # 【通用变量说明】
52
+ # {angle} : 旋转的角度数值 (绝对值)
53
+ # {direction}: 旋转方向 (如 clockwise, to the left)
54
+ # {img_tag} : 图片标签,格式为 <image_start>[reasoning_image_x]<image_end>
55
+ # {label} : 正确选项 (A, B, C, D)
56
+ # ==========================================
57
+
58
+ # --- 通用方向词汇映射 ---
59
+ # 用于将 metadata 中的 "clockwise" 替换为更多样的表达
60
+ DIRECTION_MAP = {
61
+ "clockwise": ["clockwise", "to the right", "in a clockwise direction"],
62
+ "anticlockwise": ["anticlockwise", "counter-clockwise", "to the left"],
63
+ "counter-clockwise": ["anticlockwise", "counter-clockwise", "to the left"]
64
+ }
65
+
66
+ # ---------------------------------------------------------
67
+ # Task 1 模板: 单步预测 (Single-step View Prediction)
68
+ # 逻辑:
69
+ # 1. Start: 描述初始旋转。
70
+ # 2. Middle: 描述中间的连续旋转步骤。
71
+ # 3. Final: 总结最终视图并匹配选项。
72
+ # ---------------------------------------------------------
73
+ T1_START = [
74
+ "Starting from the initial view, I rotate the camera {angle} degrees {direction} and see {img_tag}",
75
+ "First, let's move the camera {angle} degrees {direction}. The object now looks like this: {img_tag}",
76
+ "Initiating a {direction} rotation of {angle} degrees reveals this perspective: {img_tag}",
77
+ ]
78
+
79
+ T1_MIDDLE = [
80
+ "Continuing the rotation by {angle} degrees {direction}, the view becomes {img_tag}",
81
+ "Another {angle} degrees {direction} turn brings us to this angle: {img_tag}",
82
+ "Rotating further by {angle} degrees {direction}, I observe {img_tag}",
83
+ ]
84
+
85
+ T1_FINAL = [
86
+ ", which represents the final target view. Comparing this with the options, image {label} is the best match, so the answer is {label}.",
87
+ ". This matches the final position. Upon checking the candidates, option {label} aligns perfectly with this view. Therefore, the correct answer is {label}.",
88
+ ", arriving at the destination angle. Among the choices, option {label} is identical to my current view. Thus, {label} is correct."
89
+ ]
90
+
91
+ # ---------------------------------------------------------
92
+ # Task 2 模板: 多步指令 (Multi-step Instruction Following)
93
+ # 逻辑:
94
+ # 1. Step (Intermediate): 执行指令 -> 展示 reasoning_image。
95
+ # 2. Final Step: 执行最后一步指令 -> 到达目标位置 (注意:最后一步通常没有 reasoning_image,直接对应选项)。
96
+ # 3. Conclusion: 匹配选项。
97
+ # ---------------------------------------------------------
98
+ T2_STEP = [
99
+ "Step {i}: Rotating {angle} degrees {direction}, the view transitions to <image_start>[{img_key}]<image_end>",
100
+ "Following the instruction to rotate {angle} degrees {direction}, I observe this intermediate view: <image_start>[{img_key}]<image_end>",
101
+ "Next, a {angle}-degree {direction} rotation reveals: <image_start>[{img_key}]<image_end>",
102
+ ]
103
+
104
+ T2_FINAL_STEP = [
105
+ "Finally, rotating {angle} degrees {direction} brings us to the target position.",
106
+ "The last step is a {angle}-degree {direction} rotation to reach the destination.",
107
+ "Completing the sequence with a {angle} degrees {direction} turn.",
108
+ ]
109
+
110
+ T2_CONCLUSION = [
111
+ " Comparing the final view with the options, it matches option {label}. So the answer is {label}.",
112
+ " This final perspective corresponds to option {label}. Therefore, {label} is correct.",
113
+ ]
114
+
115
+ # ---------------------------------------------------------
116
+ # Task 3 模板: 序列排序 (View Ordering)
117
+ # 逻辑:
118
+ # 1. Start: 确定方向,开始旋转。
119
+ # 2. Middle (No Match): 旋转后展示图片,但该图片不对应任何选项图片 (只是中间过程)。
120
+ # 3. Middle (Match): 旋转后展示图片,并且该图片与选项中的某张图 (1/2/3/4) 匹配。
121
+ # 4. Conclusion: 总结正确的顺序 (如 4-2-1-3) 并选择选项。
122
+ # ---------------------------------------------------------
123
+ T3_START = [
124
+ "Based on the images, the rotation appears to be {direction}. Starting the rotation by {angle} degrees, I see <image_start>[{img_key}]<image_end>",
125
+ "I deduce the rotation is {direction}. First, moving {angle} degrees reveals <image_start>[{img_key}]<image_end>",
126
+ ]
127
+
128
+ # 当这一步的 reasoning_image 不匹配任何选项图片时使用:
129
+ T3_MIDDLE_NO_MATCH = [
130
+ "Continuing {angle} degrees {direction}, the view is <image_start>[{img_key}]<image_end>",
131
+ "Rotating another {angle} degrees {direction} shows <image_start>[{img_key}]<image_end>",
132
+ "Next, moving {angle} degrees {direction} gives us <image_start>[{img_key}]<image_end>",
133
+ ]
134
+
135
+ # 当这一步的 reasoning_image 匹配了选项图片 (img_idx) 时使用:
136
+ # {img_idx} 是匹配到的图片编号 (1, 2, 3, 4)
137
+ T3_MIDDLE_MATCH = [
138
+ "After rotating {angle} degrees {direction}, I see <image_start>[{img_key}]<image_end>. This view closely resembles image {img_idx}, so the next item in the sequence is {img_idx}.",
139
+ "Moving {angle} degrees {direction} leads to <image_start>[{img_key}]<image_end>, which matches image {img_idx}. Thus, {img_idx} is the next step.",
140
+ "A further {angle} degrees {direction} rotation shows <image_start>[{img_key}]<image_end>. This looks identical to image {img_idx}.",
141
+ ]
142
+
143
+ T3_CONCLUSION = [
144
+ "Combining these observations, the correct chronological order is {seq_str}. This corresponds to option {label}.",
145
+ "Therefore, the sequence is {seq_str}, making {label} the correct choice.",
146
+ "So, the sequence should be {seq_str}, which indicates that option {label} should be the right answer."
147
+ ]
148
+
149
+
150
+ # ==========================================
151
+ # 2. 核心处理逻辑
152
+ # ==========================================
153
+
154
+ def get_direction_variations(direction_str):
155
+ """根据方向关键词返回同义词列表"""
156
+ key = direction_str.lower()
157
+ if "counter" in key or "anti" in key:
158
+ return DIRECTION_MAP["anticlockwise"]
159
+ return DIRECTION_MAP["clockwise"]
160
+
161
+ def process_task1(line_data):
162
+ """处理 Task 1: 单步预测"""
163
+ metadata = line_data.get("metadata", {})
164
+ old_cot = metadata.get("cot_trace", "")
165
+ direction = metadata.get("direction", "clockwise")
166
+
167
+ gt_answer = line_data.get("gt_answer", "")
168
+ label_match = re.search(r'<answer>([A-D])</answer>', gt_answer)
169
+ correct_label = label_match.group(1) if label_match else "A"
170
+
171
+ # 从旧文本中提取所有数字作为角度步骤
172
+ steps = [int(m) for m in re.findall(r'(\d+)\s+degrees', old_cot)]
173
+
174
+ images = line_data.get("images", {})
175
+ # 按索引排序 reasoning images
176
+ reasoning_keys = sorted([k for k in images.keys() if k.startswith("reasoning_image_")],
177
+ key=lambda x: int(x.split('_')[-1]))
178
+
179
+ # 简单校验:步骤数应等于中间图数量
180
+ if len(steps) != len(reasoning_keys):
181
+ return line_data, False
182
+
183
+ cot_parts = []
184
+ dir_vars = get_direction_variations(direction)
185
+
186
+ for i, (step, img_key) in enumerate(zip(steps, reasoning_keys)):
187
+ img_tag = f"<image_start>[{img_key}]<image_end>"
188
+ cur_dir = random.choice(dir_vars)
189
+
190
+ if i == 0:
191
+ tmpl = random.choice(T1_START)
192
+ else:
193
+ tmpl = random.choice(T1_MIDDLE)
194
+
195
+ cot_parts.append(tmpl.format(angle=step, direction=cur_dir, img_tag=img_tag))
196
+
197
+ new_cot = "; ".join(cot_parts)
198
+ new_cot += random.choice(T1_FINAL).format(label=correct_label)
199
+
200
+ line_data['metadata']['cot_trace'] = new_cot
201
+ return line_data, True
202
+
203
+ def process_task2(line_data):
204
+ """处理 Task 2: 多步指令"""
205
+ metadata = line_data.get("metadata", {})
206
+
207
+ # 优先从 metadata 获取准确的角度列表
208
+ steps_degrees = metadata.get("steps_degrees", [])
209
+ if not steps_degrees:
210
+ instr = metadata.get("instruction_sequence", "")
211
+ steps_degrees = [int(m) for m in re.findall(r'(\d+)\s+degrees', instr)]
212
+
213
+ instruction_seq = metadata.get("instruction_sequence", "")
214
+ # 提取指令中的方向序列
215
+ directions = re.findall(r'(clockwise|anticlockwise|counter-clockwise)', instruction_seq)
216
+
217
+ gt_answer = line_data.get("gt_answer", "")
218
+ label_match = re.search(r'<answer>([A-D])</answer>', gt_answer)
219
+ correct_label = label_match.group(1) if label_match else "D"
220
+
221
+ images = line_data.get("images", {})
222
+ reasoning_keys = sorted([k for k in images.keys() if k.startswith("reasoning_image_")],
223
+ key=lambda x: int(x.split('_')[-1]))
224
+
225
+ # Task 2 逻辑:N 个步骤,通常有 N-1 张中间图 (最后一步直接到结果)
226
+ if len(steps_degrees) != len(reasoning_keys) + 1:
227
+ # 容错:如果步骤数不匹配,不修改
228
+ return line_data, False
229
+
230
+ cot_parts = []
231
+
232
+ for i, angle in enumerate(steps_degrees):
233
+ abs_angle = abs(angle)
234
+ # 获取当前步骤对应的方向
235
+ cur_dir_raw = directions[i] if i < len(directions) else "clockwise"
236
+ cur_dir = random.choice(get_direction_variations(cur_dir_raw))
237
+
238
+ if i < len(reasoning_keys):
239
+ # 中间步骤:有 reasoning_image
240
+ img_key = reasoning_keys[i]
241
+ tmpl = random.choice(T2_STEP)
242
+ cot_parts.append(tmpl.format(i=i+1, angle=abs_angle, direction=cur_dir, img_key=img_key))
243
+ else:
244
+ # 最后一步:没有 reasoning_image,直接得出结论
245
+ tmpl = random.choice(T2_FINAL_STEP)
246
+ cot_parts.append(tmpl.format(angle=abs_angle, direction=cur_dir))
247
+
248
+ new_cot = " ".join(cot_parts)
249
+ new_cot += random.choice(T2_CONCLUSION).format(label=correct_label)
250
+
251
+ line_data['metadata']['cot_trace'] = new_cot
252
+ return line_data, True
253
+
254
+ def process_task3(line_data):
255
+ """处理 Task 3: 序列排序"""
256
+ metadata = line_data.get("metadata", {})
257
+ old_cot = metadata.get("cot_trace", "")
258
+
259
+ # 1. 确定总体旋转方向
260
+ if "counter-clockwise" in old_cot or "anticlockwise" in old_cot:
261
+ direction_raw = "anticlockwise"
262
+ else:
263
+ direction_raw = "clockwise"
264
+
265
+ gt_answer = line_data.get("gt_answer", "")
266
+ label_match = re.search(r'<answer>([A-D])</answer>', gt_answer)
267
+ correct_label = label_match.group(1) if label_match else "A"
268
+
269
+ # 2. 提取最终的排序结果 (如 "4-2-1-3")
270
+ seq_match = re.search(r'sequence should be ([\d-]+)', old_cot)
271
+ final_seq_str = seq_match.group(1) if seq_match else "UNKNOWN"
272
+
273
+ # 3. 解析旧 CoT,提取 (角度, 图片key, 是否匹配) 的三元组
274
+ # 策略:按 "Then," 或 "After" 分割句子,逐句分析
275
+ segments = re.split(r'(?:Then,|After)', old_cot)
276
+ parsed_steps = []
277
+
278
+ for seg in segments:
279
+ # 提取角度
280
+ angle_m = re.search(r'rotat\w+\s+(\d+)\s+degrees', seg)
281
+ if not angle_m: continue
282
+ angle = int(angle_m.group(1))
283
+
284
+ # 提取 reasoning_image 编号
285
+ img_m = re.search(r'reasoning_image_(\d+)', seg)
286
+ if not img_m: continue
287
+ r_img_idx = img_m.group(1)
288
+ r_img_key = f"reasoning_image_{r_img_idx}"
289
+
290
+ # 提取匹配信息 (matches image X)
291
+ match_m = re.search(r'(?:matches|resembles)\s+image\s+(\d+)', seg)
292
+ matched_idx = match_m.group(1) if match_m else None
293
+
294
+ parsed_steps.append({
295
+ "angle": angle,
296
+ "img_key": r_img_key,
297
+ "matched_idx": matched_idx
298
+ })
299
+
300
+ images = line_data.get("images", {})
301
+ reasoning_keys = [k for k in images.keys() if k.startswith("reasoning_image_")]
302
+
303
+ # 校验解析出的步骤数是否与图片数一致
304
+ if len(parsed_steps) != len(reasoning_keys):
305
+ return line_data, False
306
+
307
+ # 4. 生成新文本
308
+ cot_parts = []
309
+ dir_vars = get_direction_variations(direction_raw)
310
+
311
+ for i, step in enumerate(parsed_steps):
312
+ cur_dir = random.choice(dir_vars)
313
+ angle = step['angle']
314
+ img_key = step['img_key']
315
+ matched_idx = step['matched_idx']
316
+
317
+ if i == 0:
318
+ # 第一步通常只是展示,不匹配
319
+ tmpl = random.choice(T3_START)
320
+ text = tmpl.format(angle=angle, direction=cur_dir, img_key=img_key)
321
+ else:
322
+ if matched_idx:
323
+ # 如果这一步有匹配
324
+ tmpl = random.choice(T3_MIDDLE_MATCH)
325
+ text = tmpl.format(angle=angle, direction=cur_dir, img_key=img_key, img_idx=matched_idx)
326
+ else:
327
+ # 如果这一步只是中间过渡
328
+ tmpl = random.choice(T3_MIDDLE_NO_MATCH)
329
+ text = tmpl.format(angle=angle, direction=cur_dir, img_key=img_key)
330
+
331
+ cot_parts.append(text)
332
+
333
+ new_cot = " ".join(cot_parts)
334
+ new_cot += random.choice(T3_CONCLUSION).format(seq_str=final_seq_str, label=correct_label)
335
+
336
+ line_data['metadata']['cot_trace'] = new_cot
337
+ return line_data, True
338
+
339
+
340
+ # ==========================================
341
+ # 3. 主程序入口
342
+ # ==========================================
343
+
344
+ def process_file(file_path, out_path, task_type, debug=False):
345
+ new_lines = []
346
+ modified_count = 0
347
+ total_count = 0
348
+
349
+ with open(file_path, 'r', encoding='utf-8') as f:
350
+ for line in f:
351
+ if not line.strip(): continue
352
+ total_count += 1
353
+ data = json.loads(line)
354
+
355
+ is_modified = False
356
+ try:
357
+ if task_type == "task1":
358
+ data, is_modified = process_task1(data)
359
+ elif task_type == "task2":
360
+ data, is_modified = process_task2(data)
361
+ elif task_type == "task3":
362
+ data, is_modified = process_task3(data)
363
+ except Exception as e:
364
+ if debug: print(f"[Error] Line {total_count} in {os.path.basename(file_path)}: {e}")
365
+ is_modified = False
366
+
367
+ if is_modified:
368
+ modified_count += 1
369
+ new_lines.append(data)
370
+
371
+ with open(out_path, 'w', encoding='utf-8') as f_out:
372
+ for item in new_lines:
373
+ f_out.write(json.dumps(item) + "\n")
374
+
375
+ return total_count, modified_count
376
+
377
+ def main():
378
+ parser = argparse.ArgumentParser(description="Rewrite CoT trace for Task 1, 2, 3")
379
+ parser.add_argument("--input_dir", type=str, required=True, help="Input directory root (recursive search)")
380
+ parser.add_argument("--output_dir", type=str, required=True, help="Output directory root")
381
+ parser.add_argument("--task_type", type=str, required=True, choices=["task1", "task2", "task3"],
382
+ help="Which task logic to apply")
383
+ parser.add_argument("--seed", type=int, default=42, help="Random seed for template selection")
384
+ parser.add_argument("--debug", action="store_true", help="Print detailed error messages")
385
+
386
+ args = parser.parse_args()
387
+ random.seed(args.seed)
388
+
389
+ # 递归查找所有 jsonl 文件
390
+ search_pattern = os.path.join(args.input_dir, "**", "*.jsonl")
391
+ files = glob(search_pattern, recursive=True)
392
+
393
+ if not files:
394
+ print(f"No JSONL files found in {args.input_dir}")
395
+ return
396
+
397
+ print(f"Found {len(files)} files for {args.task_type}")
398
+ print(f"Input: {args.input_dir}")
399
+ print(f"Output: {args.output_dir}")
400
+
401
+ total_processed = 0
402
+ total_modified = 0
403
+
404
+ for file_path in tqdm(files, desc=f"Processing {args.task_type}"):
405
+ # 计算相对路径,保持输出目录结构一致
406
+ rel_path = os.path.relpath(file_path, args.input_dir)
407
+ out_path = os.path.join(args.output_dir, rel_path)
408
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
409
+
410
+ t, m = process_file(file_path, out_path, args.task_type, args.debug)
411
+ total_processed += t
412
+ total_modified += m
413
+
414
+ print("-" * 30)
415
+ print(f"Done!")
416
+ print(f"Total Lines Processed: {total_processed}")
417
+ print(f"Total Lines Modified : {total_modified}")
418
+ print(f"Success Rate: {total_modified/total_processed:.1%}" if total_processed > 0 else "N/A")
419
+ print(f"Output saved to {args.output_dir}")
420
+
421
+ if __name__ == "__main__":
422
+ main()