Download quasar/data/synthetic.py from AtlasAI-org/Quasar: direct link, hf CLI and curl.
- Browser
- Download file 18.8 kB
-
https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/data/synthetic.py
- Command line
-
hf download hf://AtlasAI-org/Quasar/quasar/data/synthetic.py
-
curl -L -o synthetic.py https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/data/synthetic.py
18.8 kB
| """Procedural images and videos with exact ground truth, plus an analyzer that measures them. | |
| Everything here is generated locally (no external data, no license questions). The same | |
| attribute vocabulary is used for rendering, captioning and for *measuring* model outputs, so | |
| prompt-following and motion can be scored quantitatively instead of by eyeballing samples. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| from dataclasses import dataclass, field, replace | |
| import numpy as np | |
| from PIL import Image, ImageDraw | |
| RES = 64 | |
| SS = 4 # supersampling factor for anti-aliased edges | |
| COLORS: dict[str, tuple[int, int, int]] = { | |
| "red": (220, 40, 40), "green": (40, 180, 60), "blue": (50, 90, 235), "yellow": (240, 220, 50), | |
| "purple": (150, 60, 200), "orange": (245, 140, 30), "white": (240, 240, 240), "cyan": (40, 210, 220), | |
| } | |
| BACKGROUNDS: dict[str, tuple[int, int, int]] = { | |
| "black": (15, 15, 15), "gray": (105, 105, 105), "navy": (20, 30, 85), "brown": (85, 55, 30), | |
| } | |
| SHAPES = ("circle", "square", "triangle") | |
| SIZES = {"small": 5.0, "medium": 9.0, "large": 13.0} # half-extent in pixels | |
| GRID = { # name -> (col, row) in a 3x3 layout | |
| "top left": (0, 0), "top": (1, 0), "top right": (2, 0), | |
| "left": (0, 1), "center": (1, 1), "right": (2, 1), | |
| "bottom left": (0, 2), "bottom": (1, 2), "bottom right": (2, 2), | |
| } | |
| CELL_CENTERS = (16.0, 32.0, 48.0) | |
| POS_PHRASE = { | |
| "top left": "in the top left", "top": "at the top", "top right": "in the top right", | |
| "left": "on the left", "center": "in the center", "right": "on the right", | |
| "bottom left": "in the bottom left", "bottom": "at the bottom", "bottom right": "in the bottom right", | |
| } | |
| # (shape, color) pairs never shown during training: compositional-generalisation probe. | |
| HOLDOUT_COMBOS = {("triangle", "purple"), ("circle", "orange"), ("square", "cyan")} | |
| MOTIONS = ("left", "right", "up", "down", "bounce", "cw", "ccw", "grow", "shrink", "still", "collide") | |
| MOTION_PHRASE = { | |
| "left": "moving left", "right": "moving right", "up": "moving up", "down": "moving down", | |
| "cw": "rotating clockwise", "ccw": "rotating counterclockwise", "grow": "growing", | |
| "shrink": "shrinking", "still": "standing still", | |
| } | |
| DIR_VEC = {"left": (-1, 0), "right": (1, 0), "up": (0, -1), "down": (0, 1)} | |
| SHAPE_WORDS = {"circle": ["circle", "ball", "dot"], "square": ["square", "box"], "triangle": ["triangle"]} | |
| class Obj: | |
| shape: str | |
| color: str | |
| half: float | |
| cx: float | |
| cy: float | |
| angle: float = 0.0 # degrees, clockwise on screen | |
| def size_name(self) -> str: | |
| return min(SIZES, key=lambda k: abs(SIZES[k] - self.half)) | |
| class ImageSpec: | |
| obj: Obj | |
| bg: str | |
| pos: str | |
| class VideoSpec: | |
| frames: list[list[Obj]] # per frame, list of objects | |
| bg: str | |
| motion: str | |
| hdir: str = "" # horizontal drift for "bounce" | |
| meta: dict = field(default_factory=dict) | |
| # ----------------------------------------------------------------------------- rendering | |
| def _polygon(o: Obj) -> list[tuple[float, float]]: | |
| h = o.half | |
| if o.shape == "square": | |
| pts = [(-h, -h), (h, -h), (h, h), (-h, h)] | |
| else: # triangle: apex up, base at bottom, fills half of its bounding square | |
| pts = [(0.0, -h), (h, h), (-h, h)] | |
| a = math.radians(o.angle) | |
| c, s = math.cos(a), math.sin(a) | |
| # y points down, so this standard rotation appears clockwise on screen for positive angles | |
| return [((x * c - y * s + o.cx) * SS, (x * s + y * c + o.cy) * SS) for x, y in pts] | |
| def render(objs: list[Obj], bg: str) -> np.ndarray: | |
| """Render objects onto a background; returns uint8 [64, 64, 3].""" | |
| im = Image.new("RGB", (RES * SS, RES * SS), BACKGROUNDS[bg]) | |
| d = ImageDraw.Draw(im) | |
| for o in objs: | |
| if o.shape == "circle": | |
| d.ellipse([(o.cx - o.half) * SS, (o.cy - o.half) * SS, (o.cx + o.half) * SS, (o.cy + o.half) * SS], fill=COLORS[o.color]) | |
| else: | |
| d.polygon(_polygon(o), fill=COLORS[o.color]) | |
| return np.asarray(im.resize((RES, RES), Image.BOX)) | |
| def render_video(spec: VideoSpec) -> np.ndarray: | |
| return np.stack([render(objs, spec.bg) for objs in spec.frames]) | |
| # ----------------------------------------------------------------------------- sampling | |
| def _combo_ok(shape: str, color: str, holdout: str) -> bool: | |
| """holdout: 'exclude' (training), 'only' (generalisation probe) or 'any'.""" | |
| held = (shape, color) in HOLDOUT_COMBOS | |
| return holdout == "any" or (held if holdout == "only" else not held) | |
| def _pick_shape_color(rng: np.random.Generator, holdout: str, shapes=SHAPES) -> tuple[str, str]: | |
| while True: | |
| shape, color = str(rng.choice(shapes)), str(rng.choice(list(COLORS))) | |
| if _combo_ok(shape, color, holdout): | |
| return shape, color | |
| def sample_image_spec(rng: np.random.Generator, holdout: str = "exclude") -> ImageSpec: | |
| shape, color = _pick_shape_color(rng, holdout) | |
| size = str(rng.choice(list(SIZES))) | |
| pos = str(rng.choice(list(GRID))) | |
| return _place(shape, color, size, pos, str(rng.choice(list(BACKGROUNDS))), rng) | |
| def _place(shape: str, color: str, size: str, pos: str, bg: str, rng: np.random.Generator) -> ImageSpec: | |
| half = SIZES[size] | |
| col, row = GRID[pos] | |
| j = lambda: float(rng.uniform(-3, 3)) | |
| cx = float(np.clip(CELL_CENTERS[col] + j(), half + 1, RES - half - 1)) | |
| cy = float(np.clip(CELL_CENTERS[row] + j(), half + 1, RES - half - 1)) | |
| return ImageSpec(Obj(shape, color, half, cx, cy), bg, pos) | |
| def make_image_spec(shape: str, color: str, size: str, pos: str, bg: str, seed: int = 0) -> ImageSpec: | |
| return _place(shape, color, size, pos, bg, np.random.default_rng(seed)) | |
| EDITS = ("color", "move", "size", "background", "shape") | |
| def sample_edit(rng: np.random.Generator, src: ImageSpec) -> tuple[str, ImageSpec, str]: | |
| """Pick an edit; returns (edit_type, target_spec, canonical instruction).""" | |
| o = src.obj | |
| while True: | |
| kind = str(rng.choice(EDITS)) | |
| if kind == "color": | |
| c = str(rng.choice([c for c in COLORS if c != o.color])) | |
| if _combo_ok(o.shape, c, "exclude"): | |
| return kind, replace(src, obj=replace(o, color=c)), f"change the color to {c}" | |
| elif kind == "shape": | |
| s = str(rng.choice([s for s in SHAPES if s != o.shape])) | |
| if _combo_ok(s, o.color, "exclude"): | |
| return kind, replace(src, obj=replace(o, shape=s)), f"turn it into a {s}" | |
| elif kind == "size": | |
| z = str(rng.choice([z for z in SIZES if z != o.size_name])) | |
| t = _place(o.shape, o.color, z, src.pos, src.bg, rng) | |
| return kind, replace(t, obj=replace(t.obj, cx=float(np.clip(o.cx, SIZES[z] + 1, RES - SIZES[z] - 1)), | |
| cy=float(np.clip(o.cy, SIZES[z] + 1, RES - SIZES[z] - 1)))), f"make it {z}" | |
| elif kind == "move": | |
| p = str(rng.choice([p for p in GRID if p != src.pos])) | |
| return kind, _place(o.shape, o.color, o.size_name, p, src.bg, rng), f"move it to the {p}" | |
| else: | |
| b = str(rng.choice([b for b in BACKGROUNDS if b != src.bg])) | |
| return kind, replace(src, bg=b), f"change the background to {b}" | |
| def sample_video_spec(rng: np.random.Generator, n_frames: int = 8, holdout: str = "exclude", motion: str | None = None) -> VideoSpec: | |
| motion = motion or str(rng.choice(MOTIONS)) | |
| bg = str(rng.choice(list(BACKGROUNDS))) | |
| T = n_frames | |
| if motion == "collide": | |
| # exclude: neither ball is a held-out combo; only: at least one is (only orange circles are held out) | |
| ok = lambda a, b: holdout == "any" or (("circle", a) in HOLDOUT_COMBOS or ("circle", b) in HOLDOUT_COMBOS) == (holdout == "only") | |
| c1, c2 = rng.choice([c for c in COLORS], size=2, replace=False) | |
| while not ok(str(c1), str(c2)): | |
| c1, c2 = rng.choice([c for c in COLORS], size=2, replace=False) | |
| half, v = 6.0, float(rng.uniform(3, 4.5)) | |
| y = float(rng.uniform(16, 48)) | |
| x1, x2 = float(rng.uniform(8, 14)), float(rng.uniform(50, 56)) | |
| frames = [] | |
| v1, v2 = v, -v | |
| for _ in range(T): | |
| frames.append([Obj("circle", str(c1), half, x1, y), Obj("circle", str(c2), half, x2, y)]) | |
| x1, x2 = x1 + v1, x2 + v2 | |
| if x2 - x1 <= 2 * half: # elastic collision: swap velocities | |
| v1, v2 = v2, v1 | |
| x1, x2 = x1 + 2 * v1, x2 + 2 * v2 | |
| return VideoSpec(frames, bg, motion, meta={"colors": [str(c1), str(c2)]}) | |
| shapes = ("circle",) if motion == "bounce" else ("square", "triangle") if motion in ("cw", "ccw") else SHAPES | |
| shape, color = _pick_shape_color(rng, holdout, shapes) | |
| size = str(rng.choice(["small", "medium"] if motion in ("left", "right", "up", "down", "bounce") else list(SIZES))) | |
| half = SIZES[size] | |
| lo, hi = half + 1, RES - half - 1 | |
| frames: list[list[Obj]] = [] | |
| hdir = "" | |
| if motion in DIR_VEC: | |
| dx, dy = DIR_VEC[motion] | |
| v = float(rng.uniform(3, 5)) | |
| travel = v * (T - 1) | |
| start = lambda d: float(rng.uniform(lo, hi - travel)) if d > 0 else float(rng.uniform(lo + travel, hi)) if d < 0 else float(rng.uniform(lo, hi)) | |
| x, y = start(dx), start(dy) | |
| frames = [[Obj(shape, color, half, x + dx * v * t, y + dy * v * t)] for t in range(T)] | |
| elif motion == "bounce": | |
| vx = float(rng.uniform(1.5, 3)) * (1 if rng.random() < 0.5 else -1) | |
| hdir = "right" if vx > 0 else "left" | |
| x = float(rng.uniform(lo, hi - 7 * abs(vx))) if vx > 0 else float(rng.uniform(lo + 7 * abs(vx), hi)) | |
| y, vy, g = float(rng.uniform(lo, 26)), 0.0, float(rng.uniform(2.5, 4.0)) | |
| for _ in range(T): | |
| frames.append([Obj(shape, color, half, x, y)]) | |
| for _ in range(4): # substeps for a clean bounce | |
| vy += g / 4 | |
| y += vy / 4 | |
| if y > hi: | |
| y, vy = 2 * hi - y, -0.9 * vy | |
| x += vx | |
| elif motion in ("cw", "ccw"): | |
| step = float(rng.uniform(12, 22)) * (1 if motion == "cw" else -1) | |
| x, y, a0 = float(rng.uniform(lo, hi)), float(rng.uniform(lo, hi)), float(rng.uniform(0, 90)) | |
| frames = [[Obj(shape, color, half, x, y, a0 + step * t)] for t in range(T)] | |
| elif motion in ("grow", "shrink"): | |
| a, b = (4.0, 14.0) if motion == "grow" else (14.0, 4.0) | |
| x, y = float(rng.uniform(15, 49)), float(rng.uniform(15, 49)) | |
| frames = [[Obj(shape, color, a + (b - a) * t / (T - 1), x, y)] for t in range(T)] | |
| else: # still | |
| x, y = float(rng.uniform(lo, hi)), float(rng.uniform(lo, hi)) | |
| frames = [[Obj(shape, color, half, x, y)] for _ in range(T)] | |
| return VideoSpec(frames, bg, motion, hdir) | |
| def render_clutter(rng: np.random.Generator) -> np.ndarray: | |
| """Tokenizer-only augmentation: 1-6 shapes in arbitrary RGB colours on a random gradient. | |
| Broadens what the visual codec can represent beyond the 8-colour palette (e.g. user uploads). | |
| """ | |
| c0, c1 = rng.integers(0, 256, 3), rng.integers(0, 256, 3) | |
| t = np.linspace(0, 1, RES * SS)[:, None, None] if rng.random() < 0.5 else np.linspace(0, 1, RES * SS)[None, :, None] | |
| base = (c0 * (1 - t) + c1 * t).astype(np.uint8) | |
| im = Image.fromarray(np.broadcast_to(base, (RES * SS, RES * SS, 3)).copy()) | |
| d = ImageDraw.Draw(im) | |
| for _ in range(int(rng.integers(1, 7))): | |
| o = Obj(str(rng.choice(SHAPES)), "red", float(rng.uniform(3, 20)), float(rng.uniform(0, RES)), float(rng.uniform(0, RES)), float(rng.uniform(0, 360))) | |
| fill = tuple(int(v) for v in rng.integers(0, 256, 3)) | |
| if o.shape == "circle": | |
| d.ellipse([(o.cx - o.half) * SS, (o.cy - o.half) * SS, (o.cx + o.half) * SS, (o.cy + o.half) * SS], fill=fill) | |
| else: | |
| d.polygon(_polygon(o), fill=fill) | |
| return np.asarray(im.resize((RES, RES), Image.BOX)) | |
| # ----------------------------------------------------------------------------- captions | |
| def caption_image(spec: ImageSpec, rng: np.random.Generator | None = None) -> str: | |
| """Canonical caption when rng is None (used as a target); otherwise a random paraphrase (prompt).""" | |
| o = spec.obj | |
| if rng is None: | |
| return f"a {o.size_name} {o.color} {o.shape} {POS_PHRASE[spec.pos]} on a {spec.bg} background" | |
| w = str(rng.choice(SHAPE_WORDS[o.shape])) | |
| templates = [ | |
| f"a {o.size_name} {o.color} {w} {POS_PHRASE[spec.pos]} on a {spec.bg} background", | |
| f"a {o.color} {w} {POS_PHRASE[spec.pos]} on a {spec.bg} background, {o.size_name}", | |
| f"{spec.bg} background with a {o.size_name} {o.color} {w} {POS_PHRASE[spec.pos]}", | |
| f"an image of a {o.size_name} {o.color} {w} {POS_PHRASE[spec.pos]}, {spec.bg} background", | |
| f"a {o.size_name} {o.color} {w} {POS_PHRASE[spec.pos]} on a {spec.bg} background", | |
| ] | |
| return str(rng.choice(templates)) | |
| def caption_video(spec: VideoSpec, rng: np.random.Generator | None = None) -> str: | |
| if spec.motion == "collide": | |
| c1, c2 = spec.meta["colors"] | |
| return f"a {c1} circle and a {c2} circle colliding on a {spec.bg} background" | |
| o = spec.frames[0][0] | |
| size = "medium" if spec.motion in ("grow", "shrink") else o.size_name | |
| if spec.motion == "bounce": | |
| name = "ball" if rng is None else str(rng.choice(["ball", "circle"])) | |
| what = f"a {size} {o.color} {name} bouncing to the {spec.hdir}" | |
| else: | |
| name = o.shape if rng is None else str(rng.choice(SHAPE_WORDS[o.shape])) | |
| what = f"a {size} {o.color} {name} {MOTION_PHRASE[spec.motion]}" | |
| if spec.motion in ("grow", "shrink"): | |
| what = f"a {o.color} {name} {MOTION_PHRASE[spec.motion]}" | |
| if rng is None or rng.random() < 0.6: | |
| return f"{what} on a {spec.bg} background" | |
| return str(rng.choice([f"{what}", f"video of {what} on a {spec.bg} background", f"{spec.bg} background, {what}"])) | |
| def parse_caption(text: str) -> dict: | |
| """Extract attribute words from (generated) caption text; missing attributes map to None.""" | |
| t = " " + text.lower().replace(",", " ") + " " | |
| find = lambda opts: next((o for o in sorted(opts, key=len, reverse=True) if f" {o} " in t), None) | |
| shape = find(["circle", "square", "triangle", "ball", "box", "dot"]) | |
| shape = {"ball": "circle", "dot": "circle", "box": "square"}.get(shape, shape) | |
| pos = next((p for p, ph in sorted(POS_PHRASE.items(), key=lambda kv: -len(kv[1])) if ph in t), None) | |
| bg = next((b for b in BACKGROUNDS if f"{b} background" in t), None) | |
| motion = next((m for m, ph in MOTION_PHRASE.items() if ph in t), None) | |
| if " bouncing" in t: | |
| motion = "bounce" | |
| if " colliding" in t: | |
| motion = "collide" | |
| color = next((w for w in t.split() if w in COLORS), None) # fg and bg colour names never overlap | |
| return {"shape": shape, "color": color, "size": find(list(SIZES)), "pos": pos, "bg": bg, "motion": motion} | |
| # ----------------------------------------------------------------------------- analysis | |
| def _nearest(rgb: np.ndarray, table: dict[str, tuple[int, int, int]]) -> str: | |
| names = list(table) | |
| d = ((np.array([table[n] for n in names], dtype=np.float32) - rgb.astype(np.float32)) ** 2).sum(-1) | |
| return names[int(d.argmin())] | |
| def analyze_image(img: np.ndarray, min_area: int = 12) -> dict: | |
| """Measure background, dominant object colour/shape/size/position of a uint8 [H,W,3] image.""" | |
| img = np.asarray(img) | |
| border = np.concatenate([img[0], img[-1], img[:, 0], img[:, -1]]).astype(np.float32) | |
| bg_rgb = np.median(border, axis=0) | |
| bg = _nearest(bg_rgb, BACKGROUNDS) | |
| dist = np.sqrt(((img.astype(np.float32) - bg_rgb) ** 2).sum(-1)) | |
| mask = dist > 70 | |
| area = int(mask.sum()) | |
| out = {"bg": bg, "area": area, "color": None, "shape": None, "size": None, "pos": None, "cx": None, "cy": None} | |
| if area < min_area: | |
| return out | |
| ys, xs = np.nonzero(mask) | |
| w, h = xs.max() - xs.min() + 1, ys.max() - ys.min() + 1 | |
| cx, cy = (xs.min() + xs.max()) / 2.0, (ys.min() + ys.max()) / 2.0 # bbox centre (triangle mass centroid sits low) | |
| fill = area / float(w * h) | |
| out.update( | |
| color=_nearest(np.median(img[mask], axis=0), COLORS), | |
| shape="square" if fill > 0.88 else "circle" if fill > 0.69 else "triangle", | |
| size=min(SIZES, key=lambda k: abs(SIZES[k] - max(w, h) / 2)), | |
| cx=cx, cy=cy, | |
| pos=next(p for p, (c, r) in GRID.items() if c == min(2, int(cx // (RES / 3))) and r == min(2, int(cy // (RES / 3)))), | |
| ) | |
| return out | |
| def analyze_video(frames: np.ndarray) -> dict: | |
| """Per-frame analysis + trajectory summary for single-object clips.""" | |
| per = [analyze_image(f) for f in frames] | |
| pts = [(p["cx"], p["cy"]) for p in per if p["cx"] is not None] | |
| diffs = [float(np.abs(frames[i + 1].astype(np.float32) - frames[i].astype(np.float32)).mean()) for i in range(len(frames) - 1)] | |
| out = {"frames": per, "detected": len(pts), "frame_diffs": diffs} | |
| if len(pts) >= 2: | |
| out["dx"], out["dy"] = pts[-1][0] - pts[0][0], pts[-1][1] - pts[0][1] | |
| areas = [p["area"] for p in per if p["cx"] is not None] | |
| out["area_ratio"] = areas[-1] / max(1, areas[0]) | |
| return out | |
| def motion_direction(dx: float, dy: float, min_travel: float = 6.0) -> str: | |
| """Classify a displacement as left/right/up/down/still.""" | |
| if max(abs(dx), abs(dy)) < min_travel: | |
| return "still" | |
| if abs(dx) >= abs(dy): | |
| return "right" if dx > 0 else "left" | |
| return "down" if dy > 0 else "up" | |
| def _self_check() -> None: | |
| rng = np.random.default_rng(0) | |
| ok = 0 | |
| for _ in range(200): | |
| s = sample_image_spec(rng) | |
| a = analyze_image(render([s.obj], s.bg)) | |
| ok += (a["color"], a["shape"], a["pos"], a["bg"], a["size"]) == (s.obj.color, s.obj.shape, s.pos, s.bg, s.obj.size_name) | |
| print(f"analyzer exact-match on ground truth renders: {ok}/200") | |
| p = parse_caption(caption_image(s)) | |
| assert (p["shape"], p["color"], p["pos"], p["bg"], p["size"]) == (s.obj.shape, s.obj.color, s.pos, s.bg, s.obj.size_name), p | |
| for m in ("left", "right", "up", "down"): | |
| v = sample_video_spec(rng, motion=m) | |
| a = analyze_video(render_video(v)) | |
| assert motion_direction(a["dx"], a["dy"]) == m, (m, a["dx"], a["dy"]) | |
| assert parse_caption(caption_video(v))["motion"] == m | |
| if __name__ == "__main__": | |
| _self_check() | |