| |
| """Render preview MP4s for each build's parquet. |
| |
| Reads data/ticks/{build_id:03d}.parquet and writes: |
| previews/{build_id:03d}/chamber.mp4 (optical) |
| previews/{build_id:03d}/thermal.mp4 |
| previews/{build_id:03d}/galvo.mp4 |
| previews/{build_id:03d}/composite.mp4 (1x3 panel: chamber | thermal | galvo) |
| |
| Playback is at 10 fps (= tick rate), so the video duration matches the build's |
| wall-clock duration. Null frames are forward-filled with the most recent |
| captured frame of that kind, so the preview keeps moving even during the |
| sparse stretches (heating, idle). |
| |
| Source is the dataset's own parquet — no recorder repo needed. The trade-off |
| is that ~half of upstream-captured frames don't survive the per-tick attach, |
| so motion looks chunkier than playing the raw recorder frames would. |
| |
| The thermal panel is rendered from the raw `bedmatrix` IR grid (inferno colormap |
| over a fixed absolute °C range; see _thermal.py) whenever it's present — builds |
| 013+. The three earliest builds (001/002/012) predate the bedmatrix stream and |
| fall back to the legacy pre-rendered `frame_thermal` GIF. |
| |
| Usage: |
| uv run scripts/previews/01_render.py # all builds in data/ticks/ |
| uv run scripts/previews/01_render.py 13 26 # specific build ids |
| """ |
| import io |
| import os |
| import sys |
| from pathlib import Path |
|
|
| |
| |
| os.environ.setdefault("IMAGEIO_FFMPEG_EXE", "/usr/bin/ffmpeg") |
|
|
| import imageio.v2 as iio |
| import numpy as np |
| import pyarrow.parquet as pq |
| from PIL import Image |
|
|
| sys.path.insert(0, str(Path(__file__).parent.parent)) |
| sys.path.insert(0, str(Path(__file__).parent)) |
| from _lib import DATA_DIR |
| from _thermal import bedmatrix_to_image |
|
|
| OUTPUT_DIR = DATA_DIR.parent / "previews" |
| TICKS_DIR = DATA_DIR / "ticks" |
| |
| FRAME_KINDS = ("chamber", "thermal", "galvo") |
| |
| |
| |
| |
| |
| |
| KIND_ROTATION_CW = {"chamber": 90} |
| FPS = 10 |
| PANEL_HEIGHT = 480 |
| BATCH_ROWS = 1000 |
|
|
|
|
| def _even(n: int) -> int: |
| """H.264 requires even dimensions; round up if odd.""" |
| return n if n % 2 == 0 else n + 1 |
|
|
|
|
| def _decode_raw(frame_struct, kind: str) -> Image.Image | None: |
| """Decode an HF Image struct to a PIL Image (RGB), applying KIND_ROTATION_CW |
| if the kind needs orientation correction. None when missing.""" |
| if frame_struct is None: |
| return None |
| b = frame_struct.get("bytes") |
| if b is None: |
| return None |
| try: |
| img = Image.open(io.BytesIO(b)).convert("RGB") |
| except Exception: |
| return None |
| rot = KIND_ROTATION_CW.get(kind, 0) |
| |
| if rot == 90: |
| img = img.transpose(Image.Transpose.ROTATE_270) |
| elif rot == 180: |
| img = img.transpose(Image.Transpose.ROTATE_180) |
| elif rot == 270: |
| img = img.transpose(Image.Transpose.ROTATE_90) |
| return img |
|
|
|
|
| def _decode_cell(cell, kind: str) -> Image.Image | None: |
| """Decode one struct cell to a PIL RGB image, dispatching on struct shape: |
| a `bedmatrix` struct (has 'values') renders as an inferno heatmap; a frame |
| Image struct (has 'bytes') decodes + orientation-corrects. None when missing.""" |
| if cell is None: |
| return None |
| if "values" in cell: |
| return bedmatrix_to_image(cell) |
| return _decode_raw(cell, kind) |
|
|
|
|
| def _thermal_column(parquet_path: Path) -> str: |
| """Which column feeds the thermal panel for this build: 'bedmatrix' when the |
| raw IR matrix has any non-null cell, else the legacy 'frame_thermal'. The |
| bedmatrix stream started at build 013, so 001/002/012 fall back to the GIF.""" |
| pf = pq.ParquetFile(parquet_path) |
| if "bedmatrix" not in {f.name for f in pf.schema_arrow}: |
| return "frame_thermal" |
| for batch in pf.iter_batches(columns=["bedmatrix"], batch_size=BATCH_ROWS): |
| for cell in batch.column("bedmatrix").to_pylist(): |
| if cell is not None: |
| return "bedmatrix" |
| return "frame_thermal" |
|
|
|
|
| def _columns_for_build(parquet_path: Path) -> dict[str, str]: |
| """Map each panel kind → the parquet column that feeds it for this build.""" |
| return { |
| "chamber": "frame_chamber", |
| "thermal": _thermal_column(parquet_path), |
| "galvo": "frame_galvo", |
| } |
|
|
|
|
| def _fit_to_canvas(img: Image.Image, canvas_w: int) -> np.ndarray: |
| """Letterbox `img` into a (canvas_w × PANEL_HEIGHT) gray canvas, preserving aspect. |
| Locking on the canvas dims is required because some builds have frames whose |
| source dimensions drift mid-build (e.g. thermal IR config changes).""" |
| sw, sh = img.size |
| scale = min(canvas_w / sw, PANEL_HEIGHT / sh) |
| new_w = max(1, round(sw * scale)) |
| new_h = max(1, round(sh * scale)) |
| fitted = img.resize((new_w, new_h), Image.BILINEAR) |
| canvas = Image.new("RGB", (canvas_w, PANEL_HEIGHT), (20, 20, 20)) |
| canvas.paste(fitted, ((canvas_w - new_w) // 2, (PANEL_HEIGHT - new_h) // 2)) |
| return np.asarray(canvas) |
|
|
|
|
| def _placeholder(width: int) -> np.ndarray: |
| """Gray panel shown before the first frame of a kind has been seen.""" |
| return np.full((PANEL_HEIGHT, width, 3), 20, dtype=np.uint8) |
|
|
|
|
| def _iter_struct_batches(parquet_path: Path, columns: list[str]): |
| """Yield (n_rows, dict[col -> list[struct|None]]) per row-group batch.""" |
| pf = pq.ParquetFile(parquet_path) |
| for batch in pf.iter_batches(columns=columns, batch_size=BATCH_ROWS): |
| cols = {c: batch.column(c).to_pylist() for c in columns} |
| yield batch.num_rows, cols |
|
|
|
|
| def _open_writer(out_path: Path): |
| """Open an MP4 writer. Uses NVENC on the K620 GPUs when available, falling |
| back to libx264 if the env var RENDER_CPU=1 forces software encode.""" |
| out_path.parent.mkdir(parents=True, exist_ok=True) |
| if os.environ.get("RENDER_CPU") == "1": |
| return iio.get_writer( |
| out_path, fps=FPS, codec="libx264", |
| macro_block_size=1, quality=6, |
| ) |
| |
| |
| |
| return iio.get_writer( |
| out_path, fps=FPS, codec="h264_nvenc", |
| macro_block_size=1, |
| ffmpeg_params=[ |
| "-preset", "p4", |
| "-rc", "vbr", |
| "-cq", "23", |
| "-pix_fmt", "yuv420p", |
| ], |
| ) |
|
|
|
|
| def _probe_first_frame_width(parquet_path: Path, kind: str, col: str) -> int | None: |
| """Find the first non-null cell in `col`, compute the locked canvas width |
| from its post-decode aspect ratio (height = PANEL_HEIGHT). Returns None if |
| no frame of that kind ever appears.""" |
| for n_rows, cols in _iter_struct_batches(parquet_path, [col]): |
| for struct in cols[col]: |
| img = _decode_cell(struct, kind) |
| if img is not None: |
| sw, sh = img.size |
| return _even(max(2, round(sw * PANEL_HEIGHT / sh))) |
| return None |
|
|
|
|
| def render_per_kind(parquet_path: Path, kind: str, out_path: Path, col: str) -> int: |
| """Write one MP4 of a single panel kind, forward-filled. Returns frame count.""" |
| width = _probe_first_frame_width(parquet_path, kind, col) |
| if width is None: |
| |
| print(f" {kind:8s}: no frames of this kind, skipping") |
| return 0 |
| last: np.ndarray | None = None |
| frames_written = 0 |
| with _open_writer(out_path) as writer: |
| for n_rows, cols in _iter_struct_batches(parquet_path, [col]): |
| for struct in cols[col]: |
| img = _decode_cell(struct, kind) |
| if img is not None: |
| last = _fit_to_canvas(img, width) |
| writer.append_data(last if last is not None else _placeholder(width)) |
| frames_written += 1 |
| return frames_written |
|
|
|
|
| def render_composite(parquet_path: Path, out_path: Path, cols_map: dict[str, str]) -> int: |
| """Write the 1×3 composite. All three panels share the tick timeline.""" |
| |
| widths = {k: (_probe_first_frame_width(parquet_path, k, cols_map[k]) or PANEL_HEIGHT) |
| for k in FRAME_KINDS} |
| cols_to_read = [cols_map[k] for k in FRAME_KINDS] |
| last: dict[str, np.ndarray | None] = {k: None for k in FRAME_KINDS} |
| frames_written = 0 |
| with _open_writer(out_path) as writer: |
| for n_rows, cols in _iter_struct_batches(parquet_path, cols_to_read): |
| for i in range(n_rows): |
| for k in FRAME_KINDS: |
| img = _decode_cell(cols[cols_map[k]][i], k) |
| if img is not None: |
| last[k] = _fit_to_canvas(img, widths[k]) |
| panels = [ |
| last[k] if last[k] is not None else _placeholder(widths[k]) |
| for k in FRAME_KINDS |
| ] |
| writer.append_data(np.hstack(panels)) |
| frames_written += 1 |
| return frames_written |
|
|
|
|
| def process_build(build_id: int, kinds: set[str]) -> None: |
| parquet_path = TICKS_DIR / f"{build_id:03d}.parquet" |
| if not parquet_path.exists(): |
| print(f"build {build_id:03d}: no parquet, skipping") |
| return |
| build_dir = OUTPUT_DIR / f"{build_id:03d}" |
| print(f"build {build_id:03d}: rendering → {build_dir.relative_to(Path.cwd())}/") |
| cols_map = _columns_for_build(parquet_path) |
| if ("thermal" in kinds or "composite" in kinds): |
| print(f" thermal source: {cols_map['thermal']}") |
| for kind in FRAME_KINDS: |
| if kind not in kinds: |
| continue |
| out = build_dir / f"{kind}.mp4" |
| n = render_per_kind(parquet_path, kind, out, cols_map[kind]) |
| |
| |
| if out.exists(): |
| print(f" {kind:8s}: {n:>7,} frames → {out.name} ({out.stat().st_size:,} bytes)") |
| if "composite" in kinds: |
| out = build_dir / "composite.mp4" |
| n = render_composite(parquet_path, out, cols_map) |
| if out.exists(): |
| print(f" composite: {n:>7,} frames → {out.name} ({out.stat().st_size:,} bytes)") |
|
|
|
|
| def main(): |
| import argparse |
| parser = argparse.ArgumentParser(description=__doc__, |
| formatter_class=argparse.RawDescriptionHelpFormatter) |
| parser.add_argument("build_ids", nargs="*", type=int, |
| help="Specific build IDs to render (default: all in data/ticks/)") |
| parser.add_argument("--kinds", default="chamber,thermal,galvo,composite", |
| help="Comma-separated outputs to render. Default: all four. " |
| "Useful for re-rendering just one kind, e.g. " |
| "--kinds chamber,composite after a chamber-orientation change.") |
| args = parser.parse_args() |
| kinds = set(args.kinds.split(",")) |
| unknown = kinds - (set(FRAME_KINDS) | {"composite"}) |
| if unknown: |
| parser.error(f"unknown --kinds values: {sorted(unknown)}; " |
| f"valid: {sorted(set(FRAME_KINDS) | {'composite'})}") |
| targets = args.build_ids or sorted(int(p.stem) for p in TICKS_DIR.glob("*.parquet")) |
| for bid in targets: |
| process_build(bid, kinds) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|