| """ |
| 脚本名称: rewrite.py |
| 功能: 批量重写 Task 1, 2, 3 数据集中的 CoT (Chain of Thought) 推理文本。 |
| |
| 【功能描述】 |
| 该脚本读取原始 JSONL 文件,保持图像路径、几何参数、正确答案不变, |
| 仅根据 metadata 中的几何信息(角度、步骤)重新生成 'cot_trace' 字段。 |
| 支持通过修改脚本顶部的模板列表来丰富语言的多样性。 |
| |
| 【环境依赖】 |
| python >= 3.6 |
| tqdm |
| |
| 【如何运行】 |
| 在终端中使用以下命令运行。请确保 --input_dir 指向包含 jsonl 文件的根目录。 |
| |
| 1. 针对 Task 1 (单步预测): |
| python scripts/rewrite.py --task_type task1 --input_dir ./data/task1 --output_dir ./data/task1_new |
| |
| 2. 针对 Task 2 (多步指令跟随): |
| python scripts/rewrite.py --task_type task2 --input_dir ./data/task2 --output_dir ./data/task2_new |
| |
| 3. 针对 Task 3 (序列排序): |
| python scripts/rewrite.py --task_type task3 --input_dir ./data/task3 --output_dir ./data/task3_new |
| |
| 【参数说明】 |
| --input_dir : 输入文件夹路径(脚本会递归查找该目录下的所有 .jsonl 文件) |
| --output_dir: 输出文件夹路径(保持原有的目录结构) |
| --task_type : 任务类型,必须是 [task1, task2, task3] 之一 |
| --seed : 随机种子,用于控制模板选择的随机性 (默认 42) |
| --debug : 开启调试模式,打印错误信息 |
| """ |
|
|
| import os |
| import json |
| import re |
| import argparse |
| from glob import glob |
| from tqdm import tqdm |
| import random |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| DIRECTION_MAP = { |
| "clockwise": ["clockwise", "to the right", "in a clockwise direction"], |
| "anticlockwise": ["anticlockwise", "counter-clockwise", "to the left"], |
| "counter-clockwise": ["anticlockwise", "counter-clockwise", "to the left"] |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| T1_START = [ |
| "Starting from the initial view, I rotate the camera {angle} degrees {direction} and see {img_tag}", |
| "First, let's move the camera {angle} degrees {direction}. The object now looks like this: {img_tag}", |
| "Initiating a {direction} rotation of {angle} degrees reveals this perspective: {img_tag}", |
| ] |
|
|
| T1_MIDDLE = [ |
| "Continuing the rotation by {angle} degrees {direction}, the view becomes {img_tag}", |
| "Another {angle} degrees {direction} turn brings us to this angle: {img_tag}", |
| "Rotating further by {angle} degrees {direction}, I observe {img_tag}", |
| ] |
|
|
| T1_FINAL = [ |
| ", which represents the final target view. Comparing this with the options, image {label} is the best match, so the answer is {label}.", |
| ". This matches the final position. Upon checking the candidates, option {label} aligns perfectly with this view. Therefore, the correct answer is {label}.", |
| ", arriving at the destination angle. Among the choices, option {label} is identical to my current view. Thus, {label} is correct." |
| ] |
|
|
| |
| |
| |
| |
| |
| |
| |
| T2_STEP = [ |
| "Step {i}: Rotating {angle} degrees {direction}, the view transitions to <image_start>[{img_key}]<image_end>", |
| "Following the instruction to rotate {angle} degrees {direction}, I observe this intermediate view: <image_start>[{img_key}]<image_end>", |
| "Next, a {angle}-degree {direction} rotation reveals: <image_start>[{img_key}]<image_end>", |
| ] |
|
|
| T2_FINAL_STEP = [ |
| "Finally, rotating {angle} degrees {direction} brings us to the target position.", |
| "The last step is a {angle}-degree {direction} rotation to reach the destination.", |
| "Completing the sequence with a {angle} degrees {direction} turn.", |
| ] |
|
|
| T2_CONCLUSION = [ |
| " Comparing the final view with the options, it matches option {label}. So the answer is {label}.", |
| " This final perspective corresponds to option {label}. Therefore, {label} is correct.", |
| ] |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| T3_START = [ |
| "Based on the images, the rotation appears to be {direction}. Starting the rotation by {angle} degrees, I see <image_start>[{img_key}]<image_end>", |
| "I deduce the rotation is {direction}. First, moving {angle} degrees reveals <image_start>[{img_key}]<image_end>", |
| ] |
|
|
| |
| T3_MIDDLE_NO_MATCH = [ |
| "Continuing {angle} degrees {direction}, the view is <image_start>[{img_key}]<image_end>", |
| "Rotating another {angle} degrees {direction} shows <image_start>[{img_key}]<image_end>", |
| "Next, moving {angle} degrees {direction} gives us <image_start>[{img_key}]<image_end>", |
| ] |
|
|
| |
| |
| T3_MIDDLE_MATCH = [ |
| "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}.", |
| "Moving {angle} degrees {direction} leads to <image_start>[{img_key}]<image_end>, which matches image {img_idx}. Thus, {img_idx} is the next step.", |
| "A further {angle} degrees {direction} rotation shows <image_start>[{img_key}]<image_end>. This looks identical to image {img_idx}.", |
| ] |
|
|
| T3_CONCLUSION = [ |
| "Combining these observations, the correct chronological order is {seq_str}. This corresponds to option {label}.", |
| "Therefore, the sequence is {seq_str}, making {label} the correct choice.", |
| "So, the sequence should be {seq_str}, which indicates that option {label} should be the right answer." |
| ] |
|
|
|
|
| |
| |
| |
|
|
| def get_direction_variations(direction_str): |
| """根据方向关键词返回同义词列表""" |
| key = direction_str.lower() |
| if "counter" in key or "anti" in key: |
| return DIRECTION_MAP["anticlockwise"] |
| return DIRECTION_MAP["clockwise"] |
|
|
| def process_task1(line_data): |
| """处理 Task 1: 单步预测""" |
| metadata = line_data.get("metadata", {}) |
| old_cot = metadata.get("cot_trace", "") |
| direction = metadata.get("direction", "clockwise") |
| |
| gt_answer = line_data.get("gt_answer", "") |
| label_match = re.search(r'<answer>([A-D])</answer>', gt_answer) |
| correct_label = label_match.group(1) if label_match else "A" |
|
|
| |
| steps = [int(m) for m in re.findall(r'(\d+)\s+degrees', old_cot)] |
| |
| images = line_data.get("images", {}) |
| |
| reasoning_keys = sorted([k for k in images.keys() if k.startswith("reasoning_image_")], |
| key=lambda x: int(x.split('_')[-1])) |
| |
| |
| if len(steps) != len(reasoning_keys): |
| return line_data, False |
|
|
| cot_parts = [] |
| dir_vars = get_direction_variations(direction) |
| |
| for i, (step, img_key) in enumerate(zip(steps, reasoning_keys)): |
| img_tag = f"<image_start>[{img_key}]<image_end>" |
| cur_dir = random.choice(dir_vars) |
| |
| if i == 0: |
| tmpl = random.choice(T1_START) |
| else: |
| tmpl = random.choice(T1_MIDDLE) |
| |
| cot_parts.append(tmpl.format(angle=step, direction=cur_dir, img_tag=img_tag)) |
|
|
| new_cot = "; ".join(cot_parts) |
| new_cot += random.choice(T1_FINAL).format(label=correct_label) |
| |
| line_data['metadata']['cot_trace'] = new_cot |
| return line_data, True |
|
|
| def process_task2(line_data): |
| """处理 Task 2: 多步指令""" |
| metadata = line_data.get("metadata", {}) |
| |
| |
| steps_degrees = metadata.get("steps_degrees", []) |
| if not steps_degrees: |
| instr = metadata.get("instruction_sequence", "") |
| steps_degrees = [int(m) for m in re.findall(r'(\d+)\s+degrees', instr)] |
| |
| instruction_seq = metadata.get("instruction_sequence", "") |
| |
| directions = re.findall(r'(clockwise|anticlockwise|counter-clockwise)', instruction_seq) |
| |
| gt_answer = line_data.get("gt_answer", "") |
| label_match = re.search(r'<answer>([A-D])</answer>', gt_answer) |
| correct_label = label_match.group(1) if label_match else "D" |
|
|
| images = line_data.get("images", {}) |
| reasoning_keys = sorted([k for k in images.keys() if k.startswith("reasoning_image_")], |
| key=lambda x: int(x.split('_')[-1])) |
| |
| |
| if len(steps_degrees) != len(reasoning_keys) + 1: |
| |
| return line_data, False |
|
|
| cot_parts = [] |
| |
| for i, angle in enumerate(steps_degrees): |
| abs_angle = abs(angle) |
| |
| cur_dir_raw = directions[i] if i < len(directions) else "clockwise" |
| cur_dir = random.choice(get_direction_variations(cur_dir_raw)) |
| |
| if i < len(reasoning_keys): |
| |
| img_key = reasoning_keys[i] |
| tmpl = random.choice(T2_STEP) |
| cot_parts.append(tmpl.format(i=i+1, angle=abs_angle, direction=cur_dir, img_key=img_key)) |
| else: |
| |
| tmpl = random.choice(T2_FINAL_STEP) |
| cot_parts.append(tmpl.format(angle=abs_angle, direction=cur_dir)) |
|
|
| new_cot = " ".join(cot_parts) |
| new_cot += random.choice(T2_CONCLUSION).format(label=correct_label) |
| |
| line_data['metadata']['cot_trace'] = new_cot |
| return line_data, True |
|
|
| def process_task3(line_data): |
| """处理 Task 3: 序列排序""" |
| metadata = line_data.get("metadata", {}) |
| old_cot = metadata.get("cot_trace", "") |
| |
| |
| if "counter-clockwise" in old_cot or "anticlockwise" in old_cot: |
| direction_raw = "anticlockwise" |
| else: |
| direction_raw = "clockwise" |
| |
| gt_answer = line_data.get("gt_answer", "") |
| label_match = re.search(r'<answer>([A-D])</answer>', gt_answer) |
| correct_label = label_match.group(1) if label_match else "A" |
| |
| |
| seq_match = re.search(r'sequence should be ([\d-]+)', old_cot) |
| final_seq_str = seq_match.group(1) if seq_match else "UNKNOWN" |
|
|
| |
| |
| segments = re.split(r'(?:Then,|After)', old_cot) |
| parsed_steps = [] |
| |
| for seg in segments: |
| |
| angle_m = re.search(r'rotat\w+\s+(\d+)\s+degrees', seg) |
| if not angle_m: continue |
| angle = int(angle_m.group(1)) |
| |
| |
| img_m = re.search(r'reasoning_image_(\d+)', seg) |
| if not img_m: continue |
| r_img_idx = img_m.group(1) |
| r_img_key = f"reasoning_image_{r_img_idx}" |
| |
| |
| match_m = re.search(r'(?:matches|resembles)\s+image\s+(\d+)', seg) |
| matched_idx = match_m.group(1) if match_m else None |
| |
| parsed_steps.append({ |
| "angle": angle, |
| "img_key": r_img_key, |
| "matched_idx": matched_idx |
| }) |
| |
| images = line_data.get("images", {}) |
| reasoning_keys = [k for k in images.keys() if k.startswith("reasoning_image_")] |
| |
| |
| if len(parsed_steps) != len(reasoning_keys): |
| return line_data, False |
|
|
| |
| cot_parts = [] |
| dir_vars = get_direction_variations(direction_raw) |
| |
| for i, step in enumerate(parsed_steps): |
| cur_dir = random.choice(dir_vars) |
| angle = step['angle'] |
| img_key = step['img_key'] |
| matched_idx = step['matched_idx'] |
| |
| if i == 0: |
| |
| tmpl = random.choice(T3_START) |
| text = tmpl.format(angle=angle, direction=cur_dir, img_key=img_key) |
| else: |
| if matched_idx: |
| |
| tmpl = random.choice(T3_MIDDLE_MATCH) |
| text = tmpl.format(angle=angle, direction=cur_dir, img_key=img_key, img_idx=matched_idx) |
| else: |
| |
| tmpl = random.choice(T3_MIDDLE_NO_MATCH) |
| text = tmpl.format(angle=angle, direction=cur_dir, img_key=img_key) |
| |
| cot_parts.append(text) |
|
|
| new_cot = " ".join(cot_parts) |
| new_cot += random.choice(T3_CONCLUSION).format(seq_str=final_seq_str, label=correct_label) |
| |
| line_data['metadata']['cot_trace'] = new_cot |
| return line_data, True |
|
|
|
|
| |
| |
| |
|
|
| def process_file(file_path, out_path, task_type, debug=False): |
| new_lines = [] |
| modified_count = 0 |
| total_count = 0 |
| |
| with open(file_path, 'r', encoding='utf-8') as f: |
| for line in f: |
| if not line.strip(): continue |
| total_count += 1 |
| data = json.loads(line) |
| |
| is_modified = False |
| try: |
| if task_type == "task1": |
| data, is_modified = process_task1(data) |
| elif task_type == "task2": |
| data, is_modified = process_task2(data) |
| elif task_type == "task3": |
| data, is_modified = process_task3(data) |
| except Exception as e: |
| if debug: print(f"[Error] Line {total_count} in {os.path.basename(file_path)}: {e}") |
| is_modified = False |
| |
| if is_modified: |
| modified_count += 1 |
| new_lines.append(data) |
| |
| with open(out_path, 'w', encoding='utf-8') as f_out: |
| for item in new_lines: |
| f_out.write(json.dumps(item) + "\n") |
| |
| return total_count, modified_count |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Rewrite CoT trace for Task 1, 2, 3") |
| parser.add_argument("--input_dir", type=str, required=True, help="Input directory root (recursive search)") |
| parser.add_argument("--output_dir", type=str, required=True, help="Output directory root") |
| parser.add_argument("--task_type", type=str, required=True, choices=["task1", "task2", "task3"], |
| help="Which task logic to apply") |
| parser.add_argument("--seed", type=int, default=42, help="Random seed for template selection") |
| parser.add_argument("--debug", action="store_true", help="Print detailed error messages") |
| |
| args = parser.parse_args() |
| random.seed(args.seed) |
| |
| |
| search_pattern = os.path.join(args.input_dir, "**", "*.jsonl") |
| files = glob(search_pattern, recursive=True) |
| |
| if not files: |
| print(f"No JSONL files found in {args.input_dir}") |
| return |
|
|
| print(f"Found {len(files)} files for {args.task_type}") |
| print(f"Input: {args.input_dir}") |
| print(f"Output: {args.output_dir}") |
| |
| total_processed = 0 |
| total_modified = 0 |
| |
| for file_path in tqdm(files, desc=f"Processing {args.task_type}"): |
| |
| rel_path = os.path.relpath(file_path, args.input_dir) |
| out_path = os.path.join(args.output_dir, rel_path) |
| os.makedirs(os.path.dirname(out_path), exist_ok=True) |
| |
| t, m = process_file(file_path, out_path, args.task_type, args.debug) |
| total_processed += t |
| total_modified += m |
| |
| print("-" * 30) |
| print(f"Done!") |
| print(f"Total Lines Processed: {total_processed}") |
| print(f"Total Lines Modified : {total_modified}") |
| print(f"Success Rate: {total_modified/total_processed:.1%}" if total_processed > 0 else "N/A") |
| print(f"Output saved to {args.output_dir}") |
|
|
| if __name__ == "__main__": |
| main() |
|
|