interleaved-umm / scripts /rewrite.py
Caesarrr's picture
Upload ./scripts/rewrite.py with huggingface_hub
565bf0c verified
"""
脚本名称: 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
# ==========================================
# 1. 语言模板库 (Language Templates)
# ==========================================
#
# 【如何增加/修改模板】
# 1. 每个列表包含多个字符串,脚本会随机选择其中一条。
# 2. 必须保留大括号 {} 包裹的占位符,例如 {angle}, {direction}。
# 3. 如果你想增加新的表达方式,直接在对应的列表中添加字符串即可。
#
# 【通用变量说明】
# {angle} : 旋转的角度数值 (绝对值)
# {direction}: 旋转方向 (如 clockwise, to the left)
# {img_tag} : 图片标签,格式为 <image_start>[reasoning_image_x]<image_end>
# {label} : 正确选项 (A, B, C, D)
# ==========================================
# --- 通用方向词汇映射 ---
# 用于将 metadata 中的 "clockwise" 替换为更多样的表达
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"]
}
# ---------------------------------------------------------
# Task 1 模板: 单步预测 (Single-step View Prediction)
# 逻辑:
# 1. Start: 描述初始旋转。
# 2. Middle: 描述中间的连续旋转步骤。
# 3. Final: 总结最终视图并匹配选项。
# ---------------------------------------------------------
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."
]
# ---------------------------------------------------------
# Task 2 模板: 多步指令 (Multi-step Instruction Following)
# 逻辑:
# 1. Step (Intermediate): 执行指令 -> 展示 reasoning_image。
# 2. Final Step: 执行最后一步指令 -> 到达目标位置 (注意:最后一步通常没有 reasoning_image,直接对应选项)。
# 3. Conclusion: 匹配选项。
# ---------------------------------------------------------
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.",
]
# ---------------------------------------------------------
# Task 3 模板: 序列排序 (View Ordering)
# 逻辑:
# 1. Start: 确定方向,开始旋转。
# 2. Middle (No Match): 旋转后展示图片,但该图片不对应任何选项图片 (只是中间过程)。
# 3. Middle (Match): 旋转后展示图片,并且该图片与选项中的某张图 (1/2/3/4) 匹配。
# 4. Conclusion: 总结正确的顺序 (如 4-2-1-3) 并选择选项。
# ---------------------------------------------------------
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>",
]
# 当这一步的 reasoning_image 不匹配任何选项图片时使用:
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>",
]
# 当这一步的 reasoning_image 匹配了选项图片 (img_idx) 时使用:
# {img_idx} 是匹配到的图片编号 (1, 2, 3, 4)
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."
]
# ==========================================
# 2. 核心处理逻辑
# ==========================================
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 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", {})
# 优先从 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]))
# Task 2 逻辑:N 个步骤,通常有 N-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):
# 中间步骤:有 reasoning_image
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:
# 最后一步:没有 reasoning_image,直接得出结论
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", "")
# 1. 确定总体旋转方向
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"
# 2. 提取最终的排序结果 (如 "4-2-1-3")
seq_match = re.search(r'sequence should be ([\d-]+)', old_cot)
final_seq_str = seq_match.group(1) if seq_match else "UNKNOWN"
# 3. 解析旧 CoT,提取 (角度, 图片key, 是否匹配) 的三元组
# 策略:按 "Then," 或 "After" 分割句子,逐句分析
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))
# 提取 reasoning_image 编号
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}"
# 提取匹配信息 (matches image X)
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
# 4. 生成新文本
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
# ==========================================
# 3. 主程序入口
# ==========================================
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)
# 递归查找所有 jsonl 文件
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()