from __future__ import annotations import argparse import json import random import string from collections import deque from dataclasses import dataclass from pathlib import Path from typing import Dict, List, Set, Tuple from PIL import Image, ImageDraw, ImageFont # --------------------------------------------------------------------------- # Data model # --------------------------------------------------------------------------- @dataclass class MazeLayout: rows: int cols: int vertical_walls: List[List[bool]] horizontal_walls: List[List[bool]] # (side, index) for each opening in label order openings: List[Tuple[str, int]] # (side, index, row, col) in label order opening_cells: List[Tuple[str, int, int, int]] # Indices into openings[] that are the connected pair (always sorted) connected_indices: Tuple[int, int] path_length: int # --------------------------------------------------------------------------- # Maze generation (DFS / recursive backtracking) # --------------------------------------------------------------------------- def _generate_maze( rng: random.Random, rows: int, cols: int, ) -> Tuple[List[List[bool]], List[List[bool]]]: """Return (vertical_walls, horizontal_walls). vertical_walls[r][c] = True → wall on the right side of cell (r, c) horizontal_walls[r][c] = True → wall on the bottom of cell (r, c) """ visited = [[False] * cols for _ in range(rows)] vertical_walls = [[True] * cols for _ in range(rows)] horizontal_walls = [[True] * cols for _ in range(rows)] def dfs(r: int, c: int) -> None: visited[r][c] = True directions = [(-1, 0), (1, 0), (0, -1), (0, 1)] rng.shuffle(directions) for dr, dc in directions: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and not visited[nr][nc]: if dr == -1: horizontal_walls[nr][nc] = False elif dr == 1: horizontal_walls[r][c] = False elif dc == -1: vertical_walls[nr][nc] = False elif dc == 1: vertical_walls[r][c] = False dfs(nr, nc) dfs(0, 0) return vertical_walls, horizontal_walls def _open_neighbors( vertical_walls: List[List[bool]], horizontal_walls: List[List[bool]], rows: int, cols: int, r: int, c: int, ) -> List[Tuple[int, int]]: neighbors: List[Tuple[int, int]] = [] if r > 0 and not horizontal_walls[r - 1][c]: neighbors.append((r - 1, c)) if r < rows - 1 and not horizontal_walls[r][c]: neighbors.append((r + 1, c)) if c > 0 and not vertical_walls[r][c - 1]: neighbors.append((r, c - 1)) if c < cols - 1 and not vertical_walls[r][c]: neighbors.append((r, c + 1)) return neighbors def _reachable( vertical_walls: List[List[bool]], horizontal_walls: List[List[bool]], rows: int, cols: int, start: Tuple[int, int], ) -> Set[Tuple[int, int]]: queue: deque[Tuple[int, int]] = deque([start]) seen: Set[Tuple[int, int]] = {start} while queue: r, c = queue.popleft() for nr, nc in _open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c): if (nr, nc) not in seen: seen.add((nr, nc)) queue.append((nr, nc)) return seen def _path_cells( vertical_walls: List[List[bool]], horizontal_walls: List[List[bool]], rows: int, cols: int, start: Tuple[int, int], goal: Tuple[int, int], ) -> Set[Tuple[int, int]]: """BFS path between start and goal; returns the set of cells on the path.""" queue: deque[Tuple[int, int]] = deque([start]) prev: Dict[Tuple[int, int], Tuple[int, int] | None] = {start: None} while queue: r, c = queue.popleft() if (r, c) == goal: break for nr, nc in _open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c): if (nr, nc) not in prev: prev[(nr, nc)] = (r, c) queue.append((nr, nc)) if goal not in prev: return set() cells: Set[Tuple[int, int]] = set() cur: Tuple[int, int] | None = goal while cur is not None: cells.add(cur) cur = prev[cur] return cells def _opening_candidates(rows: int, cols: int, corner_buffer: int = 1) -> List[Tuple[str, int, int, int]]: """(side, border_index, row, col) for each candidate opening.""" candidates: List[Tuple[str, int, int, int]] = [] for c in range(corner_buffer, cols - corner_buffer): candidates.append(("top", c, 0, c)) candidates.append(("bottom", c, rows - 1, c)) for r in range(corner_buffer, rows - corner_buffer): candidates.append(("left", r, r, 0)) candidates.append(("right", r, r, cols - 1)) return candidates def _looks_natural( vertical_walls: List[List[bool]], horizontal_walls: List[List[bool]], rows: int, cols: int, r: int, c: int, ) -> bool: return len(_open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c)) >= 1 def _isolate_decoy( vertical_walls: List[List[bool]], horizontal_walls: List[List[bool]], rows: int, cols: int, rng: random.Random, root: Tuple[int, int], forbidden: Set[Tuple[int, int]], min_size: int, max_size: int, ) -> Set[Tuple[int, int]]: """Grow a compact subtree from root that avoids forbidden cells, then wall it off so it forms an isolated dead-end region.""" if root in forbidden: return set() queue: deque[Tuple[int, int]] = deque([root]) subtree: Set[Tuple[int, int]] = {root} max_depth = rows * cols while queue and len(subtree) < max_size: r, c = queue.popleft() neighbors = _open_neighbors(vertical_walls, horizontal_walls, rows, cols, r, c) rng.shuffle(neighbors) for nr, nc in neighbors: if (nr, nc) in subtree or (nr, nc) in forbidden: continue subtree.add((nr, nc)) queue.append((nr, nc)) if len(subtree) >= max_size: break if len(subtree) < min_size: return set() # Wall off subtree from the rest of the maze for r, c in list(subtree): if r > 0 and (r - 1, c) not in subtree: horizontal_walls[r - 1][c] = True if r < rows - 1 and (r + 1, c) not in subtree: horizontal_walls[r][c] = True if c > 0 and (r, c - 1) not in subtree: vertical_walls[r][c - 1] = True if c < cols - 1 and (r, c + 1) not in subtree: vertical_walls[r][c] = True return subtree # --------------------------------------------------------------------------- # Layout sampling # --------------------------------------------------------------------------- def sample_layout( rng: random.Random, rows: int, cols: int, num_openings: int, min_path_length_floor: int = 0, ) -> MazeLayout: """Generate a perfect maze and place border openings. Exactly two openings are connected through the maze interior; all others lead to isolated dead-end pockets (decoys). The opening order is shuffled so that the connected pair does not always occupy the first two label slots. """ vertical_walls, horizontal_walls = _generate_maze(rng, rows, cols) border_cells = _opening_candidates(rows, cols, corner_buffer=1) k = max(2, min(num_openings, len(border_cells))) # Pick a connected pair with a long interior path min_path_len = max(min_path_length_floor, (rows * cols) // 3) candidates: List[Tuple] = [] for i in range(len(border_cells)): for j in range(i + 1, len(border_cells)): a, b = border_cells[i], border_cells[j] path = _path_cells( vertical_walls, horizontal_walls, rows, cols, (a[2], a[3]), (b[2], b[3]), ) if len(path) >= min_path_len: candidates.append((a, b, path)) if candidates: first, second, path = rng.choice(candidates) else: first, second = rng.sample(border_cells, 2) path = _path_cells( vertical_walls, horizontal_walls, rows, cols, (first[2], first[3]), (second[2], second[3]), ) main_pair = [first, second] forbidden: Set[Tuple[int, int]] = set(path) # Build decoy openings total = rows * cols remaining = [ cell for cell in border_cells if cell not in main_pair and (cell[2], cell[3]) not in path and _looks_natural(vertical_walls, horizontal_walls, rows, cols, cell[2], cell[3]) ] rng.shuffle(remaining) extras: List[Tuple[str, int, int, int]] = [] for side, idx, r, c in remaining: if len(extras) >= k - 2: break subtree = _isolate_decoy( vertical_walls, horizontal_walls, rows, cols, rng, (r, c), forbidden, min_size=3, max_size=max(12, (total * 3) // 5), ) if not subtree: continue extras.append((side, idx, r, c)) forbidden.update(subtree) # Validate: ensure main pair is connected and decoys cannot reach the exit ra, ca = first[2], first[3] rb, cb = second[2], second[3] main_component = _reachable(vertical_walls, horizontal_walls, rows, cols, (ra, ca)) if (rb, cb) not in main_component: extras = [] else: valid_extras = [] for side, idx, r, c in extras: comp = _reachable(vertical_walls, horizontal_walls, rows, cols, (r, c)) if (rb, cb) not in comp: valid_extras.append((side, idx, r, c)) extras = valid_extras all_cells = main_pair + extras # Shuffle label order so connected pair is not always A-B order = list(range(len(all_cells))) rng.shuffle(order) shuffled = [all_cells[i] for i in order] conn_a = order.index(0) conn_b = order.index(1) if conn_a > conn_b: conn_a, conn_b = conn_b, conn_a return MazeLayout( rows=rows, cols=cols, vertical_walls=vertical_walls, horizontal_walls=horizontal_walls, openings=[(side, idx) for (side, idx, _, _) in shuffled], opening_cells=shuffled, connected_indices=(conn_a, conn_b), path_length=len(path), ) # --------------------------------------------------------------------------- # Rendering # --------------------------------------------------------------------------- def _carve_openings( draw: ImageDraw.ImageDraw, rows: int, cols: int, cell_size: int, wall_width: int, margin: int, openings: List[Tuple[str, int]], ) -> None: x0, y0 = margin, margin x1, y1 = margin + cols * cell_size, margin + rows * cell_size opening_set = set(openings) for c in range(cols): if ("top", c) not in opening_set: xs = margin + c * cell_size draw.rectangle( [xs - wall_width // 2, y0 - wall_width // 2, xs + cell_size + (wall_width - 1) // 2, y0 + (wall_width - 1) // 2], fill="black", ) if ("bottom", c) not in opening_set: xs = margin + c * cell_size draw.rectangle( [xs - wall_width // 2, y1 - wall_width // 2, xs + cell_size + (wall_width - 1) // 2, y1 + (wall_width - 1) // 2], fill="black", ) for r in range(rows): if ("left", r) not in opening_set: ys = margin + r * cell_size draw.rectangle( [x0 - wall_width // 2, ys - wall_width // 2, x0 + (wall_width - 1) // 2, ys + cell_size + (wall_width - 1) // 2], fill="black", ) if ("right", r) not in opening_set: ys = margin + r * cell_size draw.rectangle( [x1 - wall_width // 2, ys - wall_width // 2, x1 + (wall_width - 1) // 2, ys + cell_size + (wall_width - 1) // 2], fill="black", ) def _label_openings( draw: ImageDraw.ImageDraw, rows: int, cols: int, cell_size: int, wall_width: int, margin: int, openings: List[Tuple[str, int]], ) -> None: if not openings: return x0, y0 = margin, margin x1, y1 = margin + cols * cell_size, margin + rows * cell_size img_w = cols * cell_size + 2 * margin img_h = rows * cell_size + 2 * margin try: font = ImageFont.truetype("Arial.ttf", size=16) except Exception: try: font = ImageFont.truetype("DejaVuSans.ttf", size=16) except Exception: font = ImageFont.load_default() def measure(text: str) -> Tuple[float, float]: if hasattr(draw, "textbbox"): l, t, r, b = draw.textbbox((0, 0), text, font=font) return r - l, b - t if hasattr(font, "getbbox"): l, t, r, b = font.getbbox(text) return r - l, b - t return font.getsize(text) # type: ignore[attr-defined] offset = wall_width + 4 for i, (side, index) in enumerate(openings): label = string.ascii_uppercase[i] w, h = measure(label) if side == "top": col = max(0, min(cols - 1, index)) cx = margin + col * cell_size + cell_size / 2 x = cx - w / 2 y = y0 - offset - h elif side == "bottom": col = max(0, min(cols - 1, index)) cx = margin + col * cell_size + cell_size / 2 x = cx - w / 2 y = y1 + offset elif side == "left": row = max(0, min(rows - 1, index)) cy = margin + row * cell_size + cell_size / 2 x = x0 - offset - w y = cy - h / 2 elif side == "right": row = max(0, min(rows - 1, index)) cy = margin + row * cell_size + cell_size / 2 x = x1 + offset y = cy - h / 2 else: continue x = max(0.0, min(float(img_w - w), x)) y = max(0.0, min(float(img_h - h), y)) draw.text((x, y), label, fill="black", font=font) def render_sample( out_path: Path, layout: MazeLayout, cell_size: int, wall_width: int, margin: int, ) -> None: if wall_width % 2 == 0: wall_width += 1 rows, cols = layout.rows, layout.cols label_pad = max(16, wall_width * 2) draw_margin = margin + label_pad width = cols * cell_size + 2 * draw_margin height = rows * cell_size + 2 * draw_margin img = Image.new("RGB", (width, height), "white") draw = ImageDraw.Draw(img) _carve_openings(draw, rows, cols, cell_size, wall_width, draw_margin, layout.openings) _label_openings(draw, rows, cols, cell_size, wall_width, draw_margin, layout.openings) for r in range(rows): for c in range(cols): cx = draw_margin + c * cell_size cy = draw_margin + r * cell_size if layout.vertical_walls[r][c] and c != cols - 1: x = cx + cell_size draw.rectangle( [x - wall_width // 2, cy - wall_width // 2, x + (wall_width - 1) // 2, cy + cell_size + (wall_width - 1) // 2], fill="black", ) if layout.horizontal_walls[r][c] and r != rows - 1: y = cy + cell_size draw.rectangle( [cx - wall_width // 2, y - wall_width // 2, cx + cell_size + (wall_width - 1) // 2, y + (wall_width - 1) // 2], fill="black", ) img.save(out_path) # --------------------------------------------------------------------------- # Annotation building # --------------------------------------------------------------------------- def choose_difficulty(rows: int, cols: int, num_openings: int) -> str: total = rows * cols if total <= 100 and num_openings <= 3: return "easy" if total <= 256 and num_openings <= 5: return "medium" return "hard" def build_record( image_name: str, layout: MazeLayout, cell_size: int, wall_width: int, margin: int, ) -> Dict[str, object]: labels = [string.ascii_uppercase[i] for i in range(len(layout.openings))] answer_a = labels[layout.connected_indices[0]] answer_b = labels[layout.connected_indices[1]] opening_details = [] for i, (side, idx) in enumerate(layout.openings): opening_details.append({ "label": labels[i], "side": side, "index": idx, "is_connected": i in layout.connected_indices, }) label_list = ", ".join(labels) question = ( f"The image shows a maze with {len(labels)} labeled openings on its border: " f"{label_list}. Exactly one pair of openings is connected by a path through " f"the maze; all other pairs are blocked by walls. " f"Identify the connected pair. " f"Trace passages carefully from each opening — a path exists only if you " f"can travel from one opening to another through corridors without crossing " f"any wall. Report the connected pair in alphabetical order, formatted as " f"X-Y (for example, A-C). " f"Provide your final answer enclosed in ... tags." ) return { "image": image_name, "rows": layout.rows, "cols": layout.cols, "cell_size": cell_size, "wall_width": wall_width, "margin": margin, "num_openings": len(layout.openings), "openings": opening_details, "connected_pair": [answer_a, answer_b], "question": question, "answer": f"{answer_a}-{answer_b}", "path_length": layout.path_length, "difficulty": choose_difficulty(layout.rows, layout.cols, len(layout.openings)), } # --------------------------------------------------------------------------- # Dataset generation # --------------------------------------------------------------------------- def ensure_output_dir(root: Path) -> Tuple[Path, Path]: root.mkdir(parents=True, exist_ok=True) images_dir = root / "images" images_dir.mkdir(exist_ok=True) return root, images_dir def generate_dataset( rng: random.Random, count: int, output_dir: Path, images_dir: Path, min_rows: int, max_rows: int, min_cols: int, max_cols: int, cell_size: int, wall_width: int, margin: int, min_openings: int, max_openings: int, min_path_length_floor: int = 0, ) -> None: records: List[Dict[str, object]] = [] for idx in range(count): rows = rng.randint(min_rows, max_rows) cols = rng.randint(min_cols, max_cols) num_openings = rng.randint(min_openings, max_openings) layout = sample_layout(rng, rows, cols, num_openings, min_path_length_floor=min_path_length_floor) image_name = f"maze_{idx:05d}.png" render_sample(images_dir / image_name, layout, cell_size, wall_width, margin) records.append(build_record(f"images/{image_name}", layout, cell_size, wall_width, margin)) with (output_dir / "annotations.jsonl").open("w", encoding="utf-8") as fh: for record in records: fh.write(json.dumps(record) + "\n") data_json = { "task": "maze", "category": "sequential_traversal", "count": len(records), "items": [ {"image": r["image"], "question": r["question"], "answer": r["answer"]} for r in records ], } (output_dir / "data.json").write_text(json.dumps(data_json, indent=2)) # --------------------------------------------------------------------------- # CLI # --------------------------------------------------------------------------- def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Generate a maze puzzle dataset.") parser.add_argument("--output-root", type=Path, default=".", help="Dataset root directory.") parser.add_argument("--count", type=int, default=36) parser.add_argument("--min-rows", type=int, default=8) parser.add_argument("--max-rows", type=int, default=20) parser.add_argument("--min-cols", type=int, default=8) parser.add_argument("--max-cols", type=int, default=20) parser.add_argument("--cell-size", type=int, default=32) parser.add_argument("--wall-width", type=int, default=5) parser.add_argument("--margin", type=int, default=8) parser.add_argument("--min-openings", type=int, default=3) parser.add_argument("--max-openings", type=int, default=6) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--difficulty", type=int, default=5, help="Integer difficulty >=0; scales maze size, openings, path length.") return parser.parse_args() def main() -> None: args = parse_args() rng = random.Random(args.seed) output_dir, images_dir = ensure_output_dir(args.output_root) d = max(0, int(args.difficulty)) # Formulas (no canvas_scale — canvas self-scales via rows × cols × cell_size): # rows = cols = 10 + 2·d # num_openings = min(10, 3 + d) # min_path_length = 8 + 3·d # wall_thickness_px = max(2, 5 − 0.3·d) # dead_end_count = 3·d (decoys) args.min_rows = args.max_rows = 10 + 2 * d args.min_cols = args.max_cols = 10 + 2 * d num_openings_val = min(10, 3 + d) args.min_openings = num_openings_val args.max_openings = num_openings_val min_path_length_floor = 8 + 3 * d args.wall_width = max(2, int(round(5 - 0.3 * d))) dead_end_count = 3 * d # noqa: F841 (reserved; decoys already grown from extras) generate_dataset( rng=rng, count=args.count, output_dir=output_dir, images_dir=images_dir, min_rows=args.min_rows, max_rows=args.max_rows, min_cols=args.min_cols, max_cols=args.max_cols, cell_size=args.cell_size, wall_width=args.wall_width, margin=args.margin, min_openings=args.min_openings, max_openings=args.max_openings, min_path_length_floor=min_path_length_floor, ) print(f"Saved dataset to {args.output_root}") if __name__ == "__main__": main()