File size: 12,253 Bytes
96c7c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cdbe7c
 
 
 
 
96c7c42
 
 
 
 
232e1b3
96c7c42
 
 
232e1b3
 
 
 
96c7c42
 
 
 
 
 
8cdbe7c
96c7c42
8cdbe7c
96c7c42
 
 
 
 
8cdbe7c
 
 
232e1b3
 
 
 
96c7c42
 
 
 
 
 
 
 
 
 
232e1b3
 
 
96c7c42
 
 
 
 
7615f9a
 
 
 
232e1b3
 
 
 
 
 
 
 
 
96c7c42
 
8cdbe7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96c7c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232e1b3
 
96c7c42
232e1b3
 
 
 
 
 
 
 
96c7c42
232e1b3
 
 
 
 
 
 
 
96c7c42
 
 
8cdbe7c
 
 
232e1b3
8cdbe7c
 
 
96c7c42
 
 
 
 
 
8cdbe7c
 
 
96c7c42
 
 
 
 
 
 
 
 
8cdbe7c
96c7c42
 
 
 
 
 
 
8cdbe7c
96c7c42
 
8cdbe7c
96c7c42
8cdbe7c
96c7c42
 
 
 
 
 
8cdbe7c
96c7c42
 
 
 
 
 
 
 
 
 
 
232e1b3
96c7c42
 
 
 
 
 
8cdbe7c
 
 
96c7c42
232e1b3
 
96c7c42
8cdbe7c
8ee46b1
 
 
 
232e1b3
 
8cdbe7c
232e1b3
 
96c7c42
 
 
232e1b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96c7c42
232e1b3
96c7c42
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/env python3
"""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

# Point imageio-ffmpeg at the system ffmpeg (Ubuntu's build includes h264_nvenc;
# the bundled imageio-ffmpeg binary doesn't). Must be set BEFORE importing imageio.
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"
# Order here = left-to-right order in the composite panel.
FRAME_KINDS = ("chamber", "thermal", "galvo")
# The thermal panel is rendered from the raw `bedmatrix` IR grid when present
# (builds 013+), falling back to the legacy `frame_thermal` GIF for the three
# earliest builds (001/002/012) that predate the bedmatrix stream.
# Per-kind rotation applied post-decode (degrees clockwise). The chamber camera
# is mounted sideways on the printer, so its raw frames need a 90° CW correction
# before rendering. Other kinds are captured already in display orientation.
KIND_ROTATION_CW = {"chamber": 90}
FPS = 10
PANEL_HEIGHT = 480  # all panels resized to this height; widths float to preserve aspect ratio.
BATCH_ROWS = 1000   # pyarrow row-group iter chunk; bounds peak memory per build.


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)
    # Image.Transpose.ROTATE_N rotates N degrees CCW, so CW=N → ROTATE_(360-N).
    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,  # ~CRF 23-ish
        )
    # NVENC path. Quality target ~CRF 23 via constant-quality VBR. `p4` is the
    # balanced preset on the new naming; older NVENC firmware may report this
    # as "medium". yuv420p forced because rgb24 input → NVENC needs 4:2:0.
    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:
        # No frames of this kind exist for this build; nothing meaningful to render.
        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."""
    # Lock canvas widths up front so all subsequent frames letterbox into a fixed shape.
    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])
        # render_per_kind skips writing entirely when no frames of this kind exist
        # (and prints its own "skipping" line). Guard stat to avoid FileNotFoundError.
        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()