yunfengwang commited on
Commit
a25e110
·
verified ·
1 Parent(s): 766d72e

Upload scripts/generate_maze_data.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/generate_maze_data.py +355 -0
scripts/generate_maze_data.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Programmatic maze generation for cold-start SFT data.
3
+
4
+ Supports three topologies:
5
+ - rectangular grids
6
+ - circular mazes (concentric rings with angular sectors)
7
+ - hexagonal (honeycomb) lattices
8
+
9
+ Also generates unsolvable mazes by blocking the middle of a solvable path.
10
+ """
11
+
12
+ import argparse
13
+ import json
14
+ import random
15
+ import math
16
+ from pathlib import Path
17
+ from typing import List, Tuple, Optional
18
+ import numpy as np
19
+ from PIL import Image, ImageDraw
20
+
21
+
22
+ def generate_rectangular_maze(width: int, height: int) -> Tuple[np.ndarray, List[Tuple[int, int]]]:
23
+ """
24
+ Generate a rectangular maze using recursive backtracking.
25
+ Returns:
26
+ grid: (2*H-1, 2*W-1) array where 0=wall, 1=path
27
+ solution: list of (row, col) in grid coordinates
28
+ """
29
+ # Initialize grid with walls
30
+ grid = np.zeros((2 * height - 1, 2 * width - 1), dtype=np.uint8)
31
+ visited = np.zeros((height, width), dtype=bool)
32
+
33
+ def carve(r, c):
34
+ visited[r, c] = True
35
+ grid[2 * r, 2 * c] = 1
36
+ directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
37
+ random.shuffle(directions)
38
+ for dr, dc in directions:
39
+ nr, nc = r + dr, c + dc
40
+ if 0 <= nr < height and 0 <= nc < width and not visited[nr, nc]:
41
+ grid[2 * r + dr, 2 * c + dc] = 1
42
+ carve(nr, nc)
43
+
44
+ carve(0, 0)
45
+
46
+ # Solve with BFS
47
+ start = (0, 0)
48
+ end = (height - 1, width - 1)
49
+ queue = [(start, [start])]
50
+ visited_sol = set()
51
+ solution = []
52
+ while queue:
53
+ (r, c), path = queue.pop(0)
54
+ if (r, c) == end:
55
+ solution = path
56
+ break
57
+ if (r, c) in visited_sol:
58
+ continue
59
+ visited_sol.add((r, c))
60
+ for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
61
+ nr, nc = r + dr, c + dc
62
+ if 0 <= nr < height and 0 <= nc < width:
63
+ if grid[2 * r + dr, 2 * c + dc] == 1:
64
+ queue.append(((nr, nc), path + [(nr, nc)]))
65
+
66
+ return grid, solution
67
+
68
+
69
+ def make_maze_unsolvable(grid: np.ndarray, solution: List[Tuple[int, int]]) -> np.ndarray:
70
+ """Block the middle of the solution path to make it unsolvable."""
71
+ if len(solution) < 4:
72
+ return grid
73
+ mid_idx = len(solution) // 2
74
+ # Block around the middle cell
75
+ for idx in [mid_idx - 1, mid_idx]:
76
+ r, c = solution[idx]
77
+ gr, gc = 2 * r, 2 * c
78
+ # Turn path into wall
79
+ grid[gr, gc] = 0
80
+ # Also block adjacent connections
81
+ for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
82
+ if 0 <= gr + dr < grid.shape[0] and 0 <= gc + dc < grid.shape[1]:
83
+ grid[gr + dr, gc + dc] = 0
84
+ return grid
85
+
86
+
87
+ def grid_to_image(
88
+ grid: np.ndarray,
89
+ cell_size: int = 20,
90
+ wall_thickness: int = 2,
91
+ start_point: Tuple[int, int] = None,
92
+ end_point: Tuple[int, int] = None,
93
+ style: str = "default",
94
+ ) -> Image.Image:
95
+ """Render maze grid to PIL Image."""
96
+ h, w = grid.shape
97
+ img_w = w * cell_size
98
+ img_h = h * cell_size
99
+ img = Image.new("RGB", (img_w, img_h), "white")
100
+ draw = ImageDraw.Draw(img)
101
+
102
+ if style == "gradient":
103
+ for y in range(img_h):
104
+ color_val = int(255 * (1 - y / img_h))
105
+ draw.line([(0, y), (img_w, y)], fill=(color_val, color_val, 255))
106
+ elif style == "thick":
107
+ wall_thickness = max(wall_thickness, 4)
108
+
109
+ # Draw walls
110
+ for r in range(h):
111
+ for c in range(w):
112
+ if grid[r, c] == 0:
113
+ x0 = c * cell_size
114
+ y0 = r * cell_size
115
+ draw.rectangle([x0, y0, x0 + cell_size, y0 + cell_size], fill="black")
116
+
117
+ # Draw start and end markers
118
+ if start_point:
119
+ sr, sc = start_point
120
+ sx = sc * cell_size + cell_size // 2
121
+ sy = sr * cell_size + cell_size // 2
122
+ draw.ellipse([sx - 5, sy - 5, sx + 5, sy + 5], fill="lime")
123
+ if end_point:
124
+ er, ec = end_point
125
+ ex = ec * cell_size + cell_size // 2
126
+ ey = er * cell_size + cell_size // 2
127
+ draw.ellipse([ex - 5, ey - 5, ex + 5, ey + 5], fill="orange")
128
+
129
+ return img
130
+
131
+
132
+ def _cell_to_norm(r: int, c: int, H: int, W: int) -> Tuple[int, int]:
133
+ """Convert grid cell (row, col) to normalized [0, 999] coordinates (x, y)."""
134
+ x = int(c / max(W - 1, 1) * 999)
135
+ y = int(r / max(H - 1, 1) * 999)
136
+ return x, y
137
+
138
+
139
+ def _get_neighbors(r: int, c: int, grid: np.ndarray, height: int, width: int) -> List[Tuple[int, int]]:
140
+ """Get accessible neighbor cells from (r, c) in the maze grid."""
141
+ neighbors = []
142
+ for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
143
+ nr, nc = r + dr, c + dc
144
+ if 0 <= nr < height and 0 <= nc < width:
145
+ # Check if the wall between (r,c) and (nr,nc) is open
146
+ if grid[2 * r + dr, 2 * c + dc] == 1:
147
+ neighbors.append((nr, nc))
148
+ return neighbors
149
+
150
+
151
+ def _direction_name(dr: int, dc: int) -> str:
152
+ """Human-readable direction name."""
153
+ if dr == -1:
154
+ return "upper"
155
+ elif dr == 1:
156
+ return "lower"
157
+ elif dc == -1:
158
+ return "left"
159
+ elif dc == 1:
160
+ return "right"
161
+ return "forward"
162
+
163
+
164
+ def generate_maze_thinking(
165
+ grid: np.ndarray,
166
+ solution: List[Tuple[int, int]],
167
+ solvable: bool,
168
+ height: int,
169
+ width: int,
170
+ start_label: str = "lime text label",
171
+ end_label: str = "tangerine circle",
172
+ ) -> str:
173
+ """
174
+ Generate thinking content with point visual primitives.
175
+ Mimics DFS exploration with forward moves, dead-end detection, and backtracking.
176
+ """
177
+ H, W = grid.shape
178
+ lines = []
179
+ lines.append("I'll use a trial-and-error strategy to explore this maze.")
180
+
181
+ sx, sy = _cell_to_norm(solution[0][0], solution[0][1], height, width)
182
+ ex, ey = _cell_to_norm(solution[-1][0], solution[-1][1], height, width)
183
+
184
+ lines.append(f"First locate the starting point: <|point|>[[{sx},{sy}]]<|/point|>, "
185
+ f"and the destination: <|point|>[[{ex},{ey}]]<|/point|>.")
186
+ lines.append("**Start Exploring**:")
187
+
188
+ if solvable:
189
+ # Simulate DFS with occasional dead-end exploration and backtracking
190
+ step = 1
191
+ visited = set()
192
+ path_so_far = []
193
+
194
+ for idx, (r, c) in enumerate(solution):
195
+ px, py = _cell_to_norm(r, c, height, width)
196
+ visited.add((r, c))
197
+ path_so_far.append((px, py))
198
+
199
+ neighbors = _get_neighbors(r, c, grid, height, width)
200
+ unvisited_neighbors = [(nr, nc) for nr, nc in neighbors if (nr, nc) not in visited]
201
+
202
+ # At certain junctions, simulate exploring a dead-end branch
203
+ if idx > 0 and len(unvisited_neighbors) > 1 and random.random() < 0.4:
204
+ # Pick a wrong neighbor to explore briefly
205
+ wrong_neighbors = [n for n in unvisited_neighbors
206
+ if idx + 1 < len(solution) and n != solution[idx + 1]]
207
+ if wrong_neighbors:
208
+ wr, wc = random.choice(wrong_neighbors)
209
+ wpx, wpy = _cell_to_norm(wr, wc, height, width)
210
+ lines.append(
211
+ f"**Step{step}**: Reaching <|point|>[[{px},{py}]]<|/point|>, "
212
+ f"I face {len(unvisited_neighbors)} forks. "
213
+ f"Let me try the {_direction_name(wr - r, wc - c)} direction first."
214
+ )
215
+ step += 1
216
+ # Check if the wrong path is a dead end
217
+ dead_end_neighbors = _get_neighbors(wr, wc, grid, height, width)
218
+ dead_end_unvisited = [(nr, nc) for nr, nc in dead_end_neighbors
219
+ if (nr, nc) not in visited and (nr, nc) != (r, c)]
220
+ lines.append(
221
+ f"**Step{step}**: Moving to <|point|>[[{wpx},{wpy}]]<|/point|>... "
222
+ f"{'this is a dead end!' if not dead_end_unvisited else 'exploring further...'} "
223
+ f"Backtracking to <|point|>[[{px},{py}]]<|/point|>."
224
+ )
225
+ step += 1
226
+ visited.add((wr, wc))
227
+ continue
228
+
229
+ if idx == 0:
230
+ lines.append(
231
+ f"**Step{step}**: Starting at <|point|>[[{px},{py}]]<|/point|>, "
232
+ f"I see {len(neighbors)} directions to choose from."
233
+ )
234
+ elif idx == len(solution) - 1:
235
+ lines.append(
236
+ f"**Step{step}**: Arriving at <|point|>[[{px},{py}]]<|/point|>, "
237
+ f"I finally see the destination!"
238
+ )
239
+ else:
240
+ if len(unvisited_neighbors) > 0:
241
+ next_r, next_c = solution[idx + 1] if idx + 1 < len(solution) else (r, c)
242
+ direction = _direction_name(next_r - r, next_c - c)
243
+ lines.append(
244
+ f"**Step{step}**: Reaching <|point|>[[{px},{py}]]<|/point|>, "
245
+ f"continuing {direction}."
246
+ )
247
+ else:
248
+ lines.append(
249
+ f"**Step{step}**: At <|point|>[[{px},{py}]]<|/point|>, the path is clear."
250
+ )
251
+ step += 1
252
+
253
+ pt_str = ",".join(f"[{x},{y}]" for x, y in path_so_far)
254
+ lines.append(f"**Final Path**: After exploration, the correct route is:\n"
255
+ f"<|point|>[{pt_str}]<|/point|>")
256
+ lines.append(f"Successfully reaching the destination: <|point|>[[{ex},{ey}]]<|/point|>!")
257
+ else:
258
+ # For unsolvable: explore reachable region, then declare unsolvable
259
+ step = 1
260
+ visited = set()
261
+ stack = [solution[0]]
262
+ explored_points = []
263
+
264
+ while stack and step <= 15:
265
+ r, c = stack.pop()
266
+ if (r, c) in visited:
267
+ continue
268
+ visited.add((r, c))
269
+ px, py = _cell_to_norm(r, c, height, width)
270
+ explored_points.append((px, py))
271
+
272
+ neighbors = _get_neighbors(r, c, grid, height, width)
273
+ unvisited = [(nr, nc) for nr, nc in neighbors if (nr, nc) not in visited]
274
+
275
+ if not unvisited:
276
+ lines.append(
277
+ f"**Step{step}**: At <|point|>[[{px},{py}]]<|/point|>, "
278
+ f"all directions are dead ends. Backtracking."
279
+ )
280
+ else:
281
+ lines.append(
282
+ f"**Step{step}**: Reaching <|point|>[[{px},{py}]]<|/point|>, "
283
+ f"I see {len(unvisited)} unexplored direction(s). Exploring..."
284
+ )
285
+ for nr, nc in unvisited:
286
+ stack.append((nr, nc))
287
+ step += 1
288
+
289
+ lines.append(
290
+ "After exhaustive exploration of all reachable paths, "
291
+ "no valid route to the destination exists. The maze is unsolvable."
292
+ )
293
+
294
+ return "\n".join(lines)
295
+
296
+
297
+ def main():
298
+ parser = argparse.ArgumentParser()
299
+ parser.add_argument("--output_dir", type=str, default="data/sft/maze")
300
+ parser.add_argument("--num_samples", type=int, default=1000)
301
+ parser.add_argument("--min_size", type=int, default=5)
302
+ parser.add_argument("--max_size", type=int, default=15)
303
+ parser.add_argument("--unsolvable_ratio", type=float, default=0.2)
304
+ parser.add_argument("--seed", type=int, default=42)
305
+ args = parser.parse_args()
306
+
307
+ random.seed(args.seed)
308
+ np.random.seed(args.seed)
309
+
310
+ out_dir = Path(args.output_dir)
311
+ out_dir.mkdir(parents=True, exist_ok=True)
312
+ img_dir = out_dir / "images"
313
+ img_dir.mkdir(exist_ok=True)
314
+
315
+ records = []
316
+ for i in tqdm(range(args.num_samples), desc="Generating mazes"):
317
+ width = random.randint(args.min_size, args.max_size)
318
+ height = random.randint(args.min_size, args.max_size)
319
+ grid, solution = generate_rectangular_maze(width, height)
320
+
321
+ solvable = random.random() > args.unsolvable_ratio
322
+ if not solvable:
323
+ grid = make_maze_unsolvable(grid.copy(), solution)
324
+
325
+ # Render image
326
+ cell_size = random.randint(15, 30)
327
+ style = random.choice(["default", "gradient", "thick"])
328
+ start_gc = (solution[0][0] * 2, solution[0][1] * 2)
329
+ end_gc = (solution[-1][0] * 2, solution[-1][1] * 2)
330
+ img = grid_to_image(grid, cell_size, style=style, start_point=start_gc, end_point=end_gc)
331
+ img_path = img_dir / f"maze_{i:06d}.png"
332
+ img.save(img_path)
333
+
334
+ thinking = generate_maze_thinking(grid, solution, solvable, height, width)
335
+ answer = "True" if solvable else "False"
336
+ question = 'Is there a feasible way to get from the lime text label to the tangerine circle? Please draw the route if any. Display \\boxed{True} at the end if there is a path, else display \\boxed{False}.'
337
+
338
+ records.append({
339
+ "image": str(img_path.relative_to(out_dir)),
340
+ "question": question,
341
+ "thinking": thinking,
342
+ "solvable": solvable,
343
+ "answer": answer,
344
+ })
345
+
346
+ with open(out_dir / "maze_data.jsonl", "w") as f:
347
+ for rec in records:
348
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
349
+
350
+ print(f"Generated {args.num_samples} maze samples in {out_dir}")
351
+
352
+
353
+ if __name__ == "__main__":
354
+ from tqdm import tqdm
355
+ main()