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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Programmatic path tracing data generation.
|
| 3 |
+
|
| 4 |
+
Generates images with curved lines that connect start/end icons.
|
| 5 |
+
The model must trace the line using visual primitives (points).
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import random
|
| 11 |
+
import math
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import List, Tuple
|
| 14 |
+
import numpy as np
|
| 15 |
+
from PIL import Image, ImageDraw
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _de_casteljau(control_points: List[Tuple[float, float]], t: float) -> Tuple[float, float]:
|
| 19 |
+
"""Evaluate a Bézier curve at parameter t using De Casteljau's algorithm."""
|
| 20 |
+
pts = list(control_points)
|
| 21 |
+
while len(pts) > 1:
|
| 22 |
+
pts = [
|
| 23 |
+
((1 - t) * pts[i][0] + t * pts[i + 1][0],
|
| 24 |
+
(1 - t) * pts[i][1] + t * pts[i + 1][1])
|
| 25 |
+
for i in range(len(pts) - 1)
|
| 26 |
+
]
|
| 27 |
+
return pts[0]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def generate_curve(
|
| 31 |
+
start: Tuple[int, int],
|
| 32 |
+
end: Tuple[int, int],
|
| 33 |
+
num_control_points: int = 3,
|
| 34 |
+
curvature: float = 1.0,
|
| 35 |
+
) -> List[Tuple[int, int]]:
|
| 36 |
+
"""Generate a smooth curved path from start to end using Bézier curves.
|
| 37 |
+
|
| 38 |
+
Per the paper: "We generate images which consist of multiple Bézier curves."
|
| 39 |
+
Uses De Casteljau's algorithm for evaluation.
|
| 40 |
+
"""
|
| 41 |
+
# Build control points: start, random intermediates, end
|
| 42 |
+
control_pts = [start]
|
| 43 |
+
for _ in range(num_control_points):
|
| 44 |
+
# Interpolate between start and end, then add random offset for curvature
|
| 45 |
+
frac = random.random()
|
| 46 |
+
base_x = start[0] + frac * (end[0] - start[0])
|
| 47 |
+
base_y = start[1] + frac * (end[1] - start[1])
|
| 48 |
+
offset_x = (random.random() - 0.5) * curvature * 200
|
| 49 |
+
offset_y = (random.random() - 0.5) * curvature * 200
|
| 50 |
+
x = max(0, min(999, int(base_x + offset_x)))
|
| 51 |
+
y = max(0, min(999, int(base_y + offset_y)))
|
| 52 |
+
control_pts.append((x, y))
|
| 53 |
+
control_pts.append(end)
|
| 54 |
+
|
| 55 |
+
# Sort intermediate control points by their projection onto start->end axis
|
| 56 |
+
# to avoid self-intersecting curves
|
| 57 |
+
if len(control_pts) > 2:
|
| 58 |
+
dx = end[0] - start[0]
|
| 59 |
+
dy = end[1] - start[1]
|
| 60 |
+
length_sq = dx * dx + dy * dy
|
| 61 |
+
if length_sq > 0:
|
| 62 |
+
intermediates = control_pts[1:-1]
|
| 63 |
+
intermediates.sort(key=lambda p: ((p[0] - start[0]) * dx + (p[1] - start[1]) * dy) / length_sq)
|
| 64 |
+
control_pts = [start] + intermediates + [end]
|
| 65 |
+
|
| 66 |
+
# Evaluate Bézier curve at uniform parameter values
|
| 67 |
+
n_segments = 50
|
| 68 |
+
path = []
|
| 69 |
+
for i in range(n_segments + 1):
|
| 70 |
+
t = i / n_segments
|
| 71 |
+
x, y = _de_casteljau(control_pts, t)
|
| 72 |
+
path.append((int(x), int(y)))
|
| 73 |
+
return path
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def generate_crossing_lines(
|
| 77 |
+
img_size: int = 800,
|
| 78 |
+
num_lines: int = 3,
|
| 79 |
+
uniform_style: bool = False,
|
| 80 |
+
) -> Tuple[Image.Image, List[Tuple[int, int]], str, str]:
|
| 81 |
+
"""
|
| 82 |
+
Generate an image with multiple curved Bézier lines crossing each other.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
uniform_style: If True, all lines share the same color and stroke width,
|
| 86 |
+
stripping away color-based shortcuts and forcing the model to rely
|
| 87 |
+
solely on curvature continuity at crossings (per paper).
|
| 88 |
+
|
| 89 |
+
Returns:
|
| 90 |
+
image, target_path_points, start_label, end_label
|
| 91 |
+
"""
|
| 92 |
+
img = Image.new("RGB", (img_size, img_size), "white")
|
| 93 |
+
draw = ImageDraw.Draw(img)
|
| 94 |
+
|
| 95 |
+
# Generate background noise
|
| 96 |
+
for _ in range(100):
|
| 97 |
+
x, y = random.randint(0, img_size - 1), random.randint(0, img_size - 1)
|
| 98 |
+
draw.point((x, y), fill=(240, 240, 240))
|
| 99 |
+
|
| 100 |
+
lines = []
|
| 101 |
+
labels_pool = ["crown", "octopus", "star", "heart", "diamond", "club", "spade",
|
| 102 |
+
"moon", "sun", "cloud", "tree", "flower", "fish", "bird"]
|
| 103 |
+
chosen_labels = random.sample(labels_pool, num_lines + 1)
|
| 104 |
+
|
| 105 |
+
# Uniform style: same color and width for all lines
|
| 106 |
+
if uniform_style:
|
| 107 |
+
uniform_color = "black"
|
| 108 |
+
uniform_width = 3
|
| 109 |
+
else:
|
| 110 |
+
uniform_color = None
|
| 111 |
+
uniform_width = None
|
| 112 |
+
|
| 113 |
+
for i in range(num_lines):
|
| 114 |
+
start = (random.randint(50, img_size - 50), random.randint(50, img_size - 50))
|
| 115 |
+
end = (random.randint(50, img_size - 50), random.randint(50, img_size - 50))
|
| 116 |
+
path = generate_curve(start, end, num_control_points=random.randint(2, 5))
|
| 117 |
+
color = uniform_color if uniform_style else random.choice(
|
| 118 |
+
["red", "blue", "green", "purple", "orange", "black"])
|
| 119 |
+
width = uniform_width if uniform_style else random.randint(2, 4)
|
| 120 |
+
lines.append({
|
| 121 |
+
"path": path, "color": color, "width": width,
|
| 122 |
+
"start": chosen_labels[i], "end": chosen_labels[i + 1],
|
| 123 |
+
})
|
| 124 |
+
|
| 125 |
+
# Draw all lines
|
| 126 |
+
for line in lines:
|
| 127 |
+
pts = line["path"]
|
| 128 |
+
# Scale to image size
|
| 129 |
+
img_pts = [(int(x / 999 * img_size), int(y / 999 * img_size)) for x, y in pts]
|
| 130 |
+
draw.line(img_pts, fill=line["color"], width=line["width"])
|
| 131 |
+
|
| 132 |
+
# Pick one line as target
|
| 133 |
+
target = random.choice(lines)
|
| 134 |
+
# Draw start/end icons as simple text markers
|
| 135 |
+
sx, sy = target["path"][0]
|
| 136 |
+
ex, ey = target["path"][-1]
|
| 137 |
+
sx_img = int(sx / 999 * img_size)
|
| 138 |
+
sy_img = int(sy / 999 * img_size)
|
| 139 |
+
ex_img = int(ex / 999 * img_size)
|
| 140 |
+
ey_img = int(ey / 999 * img_size)
|
| 141 |
+
draw.text((sx_img - 10, sy_img - 10), target["start"][:2].upper(), fill="black")
|
| 142 |
+
draw.text((ex_img - 10, ey_img - 10), target["end"][:2].upper(), fill="black")
|
| 143 |
+
|
| 144 |
+
return img, target["path"], target["start"], target["end"]
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def generate_path_thinking(path: List[Tuple[int, int]], start_label: str, end_label: str) -> str:
|
| 148 |
+
"""Generate thinking content with point visual primitives tracing the path."""
|
| 149 |
+
lines = []
|
| 150 |
+
sx, sy = path[0]
|
| 151 |
+
ex, ey = path[-1]
|
| 152 |
+
lines.append(f"I find the starting point you mentioned, it's located here: <|point|>[[{sx},{sy}]]<|/point|>.")
|
| 153 |
+
lines.append("Following this line, the visual path I observe is:")
|
| 154 |
+
# Sample points adaptively: fewer for straight segments, more for curves
|
| 155 |
+
sampled = [path[0]]
|
| 156 |
+
for i in range(1, len(path)):
|
| 157 |
+
prev = sampled[-1]
|
| 158 |
+
curr = path[i]
|
| 159 |
+
dist = math.hypot(curr[0] - prev[0], curr[1] - prev[1])
|
| 160 |
+
# Adaptive sampling: if distance > threshold, add point
|
| 161 |
+
if dist > 20 or i == len(path) - 1:
|
| 162 |
+
sampled.append(curr)
|
| 163 |
+
|
| 164 |
+
pt_str = ",".join(f"[{x},{y}]" for x, y in sampled)
|
| 165 |
+
lines.append(f"<|point|>[{pt_str}]<|/point|>")
|
| 166 |
+
lines.append(f"Following this path, it connects to: <|point|>[[{ex},{ey}]]<|/point|>.")
|
| 167 |
+
return "\n".join(lines)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def main():
|
| 171 |
+
parser = argparse.ArgumentParser()
|
| 172 |
+
parser.add_argument("--output_dir", type=str, default="data/sft/path")
|
| 173 |
+
parser.add_argument("--num_samples", type=int, default=1000)
|
| 174 |
+
parser.add_argument("--min_lines", type=int, default=2)
|
| 175 |
+
parser.add_argument("--max_lines", type=int, default=5)
|
| 176 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 177 |
+
args = parser.parse_args()
|
| 178 |
+
|
| 179 |
+
random.seed(args.seed)
|
| 180 |
+
np.random.seed(args.seed)
|
| 181 |
+
|
| 182 |
+
out_dir = Path(args.output_dir)
|
| 183 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 184 |
+
img_dir = out_dir / "images"
|
| 185 |
+
img_dir.mkdir(exist_ok=True)
|
| 186 |
+
|
| 187 |
+
records = []
|
| 188 |
+
for i in range(args.num_samples):
|
| 189 |
+
num_lines = random.randint(args.min_lines, args.max_lines)
|
| 190 |
+
# 30% of samples use uniform style (per paper: forces curvature-based reasoning)
|
| 191 |
+
use_uniform = random.random() < 0.3
|
| 192 |
+
img, path, start_label, end_label = generate_crossing_lines(
|
| 193 |
+
num_lines=num_lines, uniform_style=use_uniform)
|
| 194 |
+
img_path = img_dir / f"path_{i:06d}.png"
|
| 195 |
+
img.save(img_path)
|
| 196 |
+
|
| 197 |
+
thinking = generate_path_thinking(path, start_label, end_label)
|
| 198 |
+
question = f"Where does the {start_label} icon connect to? Put the destination icon name in \\boxed{{}}."
|
| 199 |
+
answer = f"\\boxed{{{end_label}}}"
|
| 200 |
+
|
| 201 |
+
records.append({
|
| 202 |
+
"image": str(img_path.relative_to(out_dir)),
|
| 203 |
+
"question": question,
|
| 204 |
+
"thinking": thinking,
|
| 205 |
+
"start_label": start_label,
|
| 206 |
+
"end_label": end_label,
|
| 207 |
+
"answer": answer,
|
| 208 |
+
})
|
| 209 |
+
|
| 210 |
+
with open(out_dir / "path_data.jsonl", "w") as f:
|
| 211 |
+
for rec in records:
|
| 212 |
+
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
| 213 |
+
|
| 214 |
+
print(f"Generated {args.num_samples} path tracing samples in {out_dir}")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if __name__ == "__main__":
|
| 218 |
+
main()
|