ppak10 commited on
Commit
7615f9a
·
1 Parent(s): 55175a6

Adds previews for timelapses.

Browse files
CLAUDE.md CHANGED
@@ -269,12 +269,17 @@ Neither blocks the ETL. They improve dataset metadata.
269
  ```
270
  .python-version # 3.13
271
  pyproject.toml # pyarrow, polars, imageio[ffmpeg], pillow, numpy
272
- .gitattributes # *.parquet, *.mp4 → LFS
273
 
274
  scripts/
275
  _lib.py # sibling-repo paths + JSONL streaming
276
- ticks/01_extract.py # the single ETL — wide-pivot + asof + burst + embed
277
- previews/01_render.py # per-build MP4 previews from data/ticks/
 
 
 
 
 
278
 
279
  data/
280
  ticks/{build_id:03d}.parquet # LFS; e.g. 001.parquet, 026.parquet
@@ -285,6 +290,10 @@ previews/
285
  thermal.mp4 # LFS; IR matrix
286
  galvo.mp4 # LFS; scan-mirror trace
287
  composite.mp4 # LFS; 1×3 panel: chamber | thermal | galvo
 
 
 
 
288
  ```
289
 
290
  There is no `source/` (raw data lives in the sibling recorder repo's `data/exports/`).
@@ -375,20 +384,45 @@ If `expand()` in the recorder ever changes, all of those column names change wit
375
 
376
  ## Current state
377
 
378
- - `ticks` config: implemented with embedded frame bytes. 12 parquet files, ~47 GB total, across builds 1, 2, 12, 13, 14, 16, 17, 25, 26, 28, 29, 30. Builds 29 and 30 were added 2026-06-28; the first 10 still carry a stale `print_profile_id` column from before the dep-drop and will lose it on next regen.
379
  - `print_profile_name` is preserved on every row; the `print_profile_id` UUID is *not* materialized here (see the architectural decision above).
380
  - `events` and `plotter_commands` not surfaced as configs.
381
  - **Forward-fill semantics deferred.** Current attach is "fresh frame within 100 ms of tick or null." Carrying the latest captured frame forward to fill null rows is left to consumers (one-line groupby + ffill); baking it into the dataset would destroy the fresh-vs-stale signal that's the whole point of keeping nulls.
382
- - `previews/` MP4s: scaffolded 2026-06-28; first full render in progress (see "Preview videos" below).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
384
  ## Adding a build — recipe
385
 
 
386
  1. New build runs in the recorder, produces telemetry / frames / position_hf in Postgres + on disk.
387
  2. Run `scripts/export.py` in the recorder repo to refresh `data/exports/`. Pass `--builds N` to scope to one build if you don't want to re-export everything.
388
- 3. (Optional, but recommended) edit `Agentic-…-Optimization/data/exports/build_to_inova_session.csv` to fill in the `inova_session_id` UUID for the new build, then commit there.
389
- 4. Run `uv run scripts/ticks/01_extract.py N` here to write `data/ticks/NNN.parquet` (zero-padded — e.g. build 7 → `007.parquet`, build 142 → `142.parquet`).
390
- 5. Run `uv run scripts/previews/01_render.py N` to generate the four preview MP4s under `previews/NNN/`. See "Preview videos" below for cost.
391
- 6. `git add data/ticks/NNN.parquet previews/NNN/` (LFS) and commit.
 
 
 
392
 
393
  ## Regenerate everything
394
 
@@ -399,7 +433,9 @@ uv run scripts/ticks/01_extract.py
399
 
400
  Takes ~2 hours, produces ~30 GB. The IO is the bottleneck; the Polars pivot and asof joins are fast.
401
 
402
- ## Preview videos
 
 
403
 
404
  `scripts/previews/01_render.py` walks `data/ticks/*.parquet` and emits four MP4s per build under `previews/{build_id:03d}/`:
405
 
@@ -408,19 +444,35 @@ Takes ~2 hours, produces ~30 GB. The IO is the bottleneck; the Polars pivot and
408
  - `galvo.mp4` — scan-mirror trace, from `frame_galvo`
409
  - `composite.mp4` — 1×3 panel (chamber | thermal | galvo)
410
 
411
- Design choices baked in:
412
- - **Source is this dataset's own parquet, not the recorder's raw frame files.** Means previews are self-contained (no recorder repo needed at render time) but only see the per-tick-attached subset (~36% chamber / ~37% galvo / ~16% thermal of ticks have a frame).
413
- - **Real-time playback at 10 fps** output duration matches build wall-clock. Build 26 (~9h54m) → ~9h54m of video. Null cells are forward-filled so the picture keeps moving through long heating stretches (this is a *viewing* convenience and does NOT contradict the no-forward-fill rule on the dataset itself — videos are not training data).
414
- - **Letterbox-fit into a canvas locked by the first non-null frame.** Some builds have a thermal config change mid-run that produces a different source aspect ratio (e.g. build 13 has 2,215 frames at 960×720 and 2 at 852×852); the lock-and-letterbox approach keeps ffmpeg happy.
415
- - **Streamed row-group iteration via pyarrow** (`BATCH_ROWS=1000`) so the whole parquet never lives in memory — necessary for the 11 GB files.
416
 
417
- Cost is non-trivial: full render of all 12 builds is ~25 GB of LFS, ~9.7 h of encode (libx264 with imageio-ffmpeg). The long-build MP4s dominate; the tiny failed-heating builds (2, 14, 16, 17, 25) cost seconds and sub-MB each.
 
 
 
 
 
 
 
 
418
 
419
- ### Regenerate previews
 
 
 
 
 
 
 
420
 
421
  ```sh
422
- uv run scripts/previews/01_render.py # all builds with parquet
423
- uv run scripts/previews/01_render.py 13 26 # specific builds
 
424
  ```
425
 
426
- Always overwrites existing previews (no skip-if-exists). For incremental work, name the build IDs.
 
269
  ```
270
  .python-version # 3.13
271
  pyproject.toml # pyarrow, polars, imageio[ffmpeg], pillow, numpy
272
+ .gitattributes # *.parquet, *.mp4, *.gif → LFS
273
 
274
  scripts/
275
  _lib.py # sibling-repo paths + JSONL streaming
276
+ ticks/
277
+ 00_recover_spool41.py # one-off: recover build 41 from NVMe spool (DB was wiped)
278
+ 00_export_new_db.py # one-off: export new-DB builds with ID offset (old_id:new_id)
279
+ 01_extract.py # the single ETL — wide-pivot + asof + burst + embed
280
+ previews/
281
+ 01_render.py # per-build MP4 previews from data/ticks/
282
+ 02_timelapse.py # per-build timelapse GIFs, one frame per print layer
283
 
284
  data/
285
  ticks/{build_id:03d}.parquet # LFS; e.g. 001.parquet, 026.parquet
 
290
  thermal.mp4 # LFS; IR matrix
291
  galvo.mp4 # LFS; scan-mirror trace
292
  composite.mp4 # LFS; 1×3 panel: chamber | thermal | galvo
293
+ timelapse_chamber.gif # LFS; layer-by-layer GIF, 25 fps, ≤ 12 s
294
+ timelapse_thermal.gif # LFS
295
+ timelapse_galvo.gif # LFS
296
+ timelapse_composite.gif # LFS; 1×3 panel GIF
297
  ```
298
 
299
  There is no `source/` (raw data lives in the sibling recorder repo's `data/exports/`).
 
384
 
385
  ## Current state
386
 
387
+ - `ticks` config: 24 parquet files across builds 001–043 (plus 040). Build 041 was recovered from the NVMe spool after the Postgres DB was wiped. Builds 042–043 are from the new DB (which restarted its BIGSERIAL at 1); see "Build ID offset" below.
388
  - `print_profile_name` is preserved on every row; the `print_profile_id` UUID is *not* materialized here (see the architectural decision above).
389
  - `events` and `plotter_commands` not surfaced as configs.
390
  - **Forward-fill semantics deferred.** Current attach is "fresh frame within 100 ms of tick or null." Carrying the latest captured frame forward to fill null rows is left to consumers (one-line groupby + ffill); baking it into the dataset would destroy the fresh-vs-stale signal that's the whole point of keeping nulls.
391
+ - `previews/` MP4s and timelapse GIFs: MP4s for builds 001–043 rendered; GIFs for 012 confirmed, full GIF render pending.
392
+
393
+ ## Build ID offset (post-DB-reset builds)
394
+
395
+ The recorder's Postgres DB was wiped between build 040 and the next print (2026-07-09). The new DB restarted its `builds_id_seq` at 1. To avoid collision with the existing dataset files (001.parquet and 002.parquet correspond to the original Hex Coasters runs), new-DB builds are offset:
396
+
397
+ | New DB id | Dataset id | Job name |
398
+ |---|---|---|
399
+ | — (spool only) | 041 | Unknown 2026_07_09 (~3h45m; DB wiped before import) |
400
+ | 1 | 042 | Nameplates 2026_07_09 (~5h40m) |
401
+ | 2 | 043 | D790 and D638 and Nameplate 2026_07_10 (~10h30m) |
402
+ | 3 | 044 | D790 and D638 and Other 2026_07_11 (in progress at time of writing) |
403
+
404
+ **To add a new build from the new DB**, use `00_export_new_db.py` with the appropriate offset instead of `export.py`:
405
+ ```sh
406
+ uv run --with psycopg2-binary scripts/ticks/00_export_new_db.py 3:44
407
+ uv run scripts/ticks/01_extract.py 44
408
+ uv run scripts/previews/01_render.py 44
409
+ uv run scripts/previews/02_timelapse.py 44
410
+ ```
411
+
412
+ The long-term fix (resetting the DB sequence or adding a global build registry) is deferred. Frame files for new-DB builds live in subdirectories named after the *original* DB id (e.g. `data/frames/1/`, `data/frames/2/`), but the paths stored in `frames.jsonl` reference those original names — the ETL reads them correctly without any renaming.
413
 
414
  ## Adding a build — recipe
415
 
416
+ **If the recorder DB is healthy (sequence hasn't reset):**
417
  1. New build runs in the recorder, produces telemetry / frames / position_hf in Postgres + on disk.
418
  2. Run `scripts/export.py` in the recorder repo to refresh `data/exports/`. Pass `--builds N` to scope to one build if you don't want to re-export everything.
419
+ 3. (Optional) edit `Agentic-…-Optimization/data/exports/build_to_inova_session.csv` for the `inova_session_id` UUID.
420
+ 4. `uv run scripts/ticks/01_extract.py N` `data/ticks/NNN.parquet`
421
+ 5. `uv run scripts/previews/01_render.py N` four MP4s under `previews/NNN/`
422
+ 6. `uv run scripts/previews/02_timelapse.py N` → four timelapse GIFs under `previews/NNN/`
423
+ 7. `git add data/ticks/NNN.parquet previews/NNN/` (LFS) and commit.
424
+
425
+ **If the recorder DB was reset (new sequence starting at 1):** use `00_export_new_db.py` with an `old_id:new_id` mapping instead of step 2. See "Build ID offset" above.
426
 
427
  ## Regenerate everything
428
 
 
433
 
434
  Takes ~2 hours, produces ~30 GB. The IO is the bottleneck; the Polars pivot and asof joins are fast.
435
 
436
+ ## Preview videos and timelapse GIFs
437
+
438
+ ### MP4 previews (`01_render.py`)
439
 
440
  `scripts/previews/01_render.py` walks `data/ticks/*.parquet` and emits four MP4s per build under `previews/{build_id:03d}/`:
441
 
 
444
  - `galvo.mp4` — scan-mirror trace, from `frame_galvo`
445
  - `composite.mp4` — 1×3 panel (chamber | thermal | galvo)
446
 
447
+ Design choices:
448
+ - **Real-time playback at 10 fps** output duration matches build wall-clock. Null cells are forward-filled (viewing convenience only; not training data).
449
+ - **Letterbox-fit into a canvas locked by the first non-null frame** (handles thermal dim drift).
450
+ - **Streamed row-group iteration** (`BATCH_ROWS=1000`) necessary for 11+ GB parquets.
451
+ - **NVENC encode** (`h264_nvenc`, K620 GPUs) with libx264 fallback (`RENDER_CPU=1`).
452
 
453
+ ```sh
454
+ uv run scripts/previews/01_render.py # all builds
455
+ uv run scripts/previews/01_render.py 13 26 # specific builds
456
+ uv run scripts/previews/01_render.py 26 --kinds chamber,composite
457
+ ```
458
+
459
+ ### Timelapse GIFs (`02_timelapse.py`)
460
+
461
+ `scripts/previews/02_timelapse.py` emits four animated GIFs per build:
462
 
463
+ - `timelapse_chamber.gif`, `timelapse_thermal.gif`, `timelapse_galvo.gif`
464
+ - `timelapse_composite.gif` — 1×3 panel
465
+
466
+ **Layer detection:** `positions.position.z2` is quantized in 100 µm buckets. Only z2 > 0 rows are used — z2 stays at 0 during pre-print heating, so this naturally excludes non-printing ticks. The *last* non-null frame in each z2 bucket is the representative (most-recent view of the layer just before recoating).
467
+
468
+ **Playback:** 25 fps, capped at 300 frames (max 12 s GIF). Builds with fewer than 300 detected layers are not padded. Null-frame levels are forward-filled within the GIF. Canvas height 240 px (half the MP4 height) to keep file sizes web-friendly.
469
+
470
+ **Composite pass:** does a single parquet stream reading all three frame columns at once (not three separate passes).
471
 
472
  ```sh
473
+ uv run scripts/previews/02_timelapse.py # all builds
474
+ uv run scripts/previews/02_timelapse.py 26 28 # specific builds
475
+ uv run scripts/previews/02_timelapse.py 26 --kinds chamber,composite
476
  ```
477
 
478
+ Always overwrites. For incremental work, name the build IDs.
README.md CHANGED
@@ -25,99 +25,196 @@ dataset_info:
25
 
26
  # Inova-Mk1-Telemetry
27
 
28
- Time-aligned printer-state recordings from Inova Mk1 SLS print runs. One row per 10 Hz **tick** of the recorder's `/state/snapshot` poll, with the full sensor state (~64 columns: temperatures, position, power, lights) on every row, the nearest camera frame paths attached when one fell in the prior 100 ms window, and any 1 kHz position-stream samples from that window collected as a nested list.
29
 
30
- Builds are denormalized into every row, so each parquet file is self-sufficient for ML — no joins needed for build context. The `print_profile_name` string the printer was running is preserved on every row; consumers who want the matching UUID from [`ppak10/Inova-Mk1-Database`](https://huggingface.co/datasets/ppak10/Inova-Mk1-Database) can resolve it themselves (one-liner shown below) this dataset deliberately doesn't bake that join in, so it has no cross-dataset dependency at load time.
31
 
32
  ```python
33
  from datasets import load_dataset
34
- ticks = load_dataset("ppak10/Inova-Mk1-Telemetry", split="train")
35
- row = ticks[0]
36
- # row["frame_chamber"] → PIL.Image.Image (or None)
37
- # row["frame_thermal"] → PIL.Image.Image (or None)
38
- # row["powderBed.temp.current"] → float (°C)
39
- # row["position_hf_burst"] list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
 
40
  ```
41
 
42
- The full image bytes ship inside each row — no separate frame download required. Filter to rows that have a particular frame kind with `ticks.filter(lambda r: r["frame_chamber"] is not None)`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  ---
45
 
46
  ## Row shape
47
 
48
- Each row is one moment in time (a single 10 Hz tick). 80+ columns:
49
 
50
  | Group | Columns | Notes |
51
  |---|---|---|
52
- | **Build context** (denormalized) | `build_id`, `job_name`, `started_at`, `ended_at`, `phase`, `print_profile_name`, `inova_session_id` | Same value on every row in a given parquet file. `inova_session_id` is null until the upstream `build_to_inova_session.csv` is filled in by hand. |
53
- | **Tick timestamp** | `ts` (`timestamp[us, UTC]`) | The `respondedAt` field on the `/state/snapshot` frame. |
54
- | **Position (10 Hz)** | `positions.position.{x,y,z1,z2,r}` | Stage position at the tick, **microns** (firmware native; e.g. `z1 = 47272.79` is 47.27 mm). Always present. |
55
  | **Lights** | `lights.lights.{enabled,count}` | |
56
- | **Power (W)** | `{laser,fanGalvo,buzzer,laserSafety,io-en,wd-en,wd-in}.power`, `powerman.power.{current,required,max}` | Per-component power draw and the overall manager state. |
57
- | **Temperature (°C)** | `{powderBed,printBed}.temp.{current,average,target}`, `{powderChamber1..4,printChamber1..4}.temp.{current,average,target}`, `{quadrant1..4,surface,surfaceAvg,surfaceMin,surfaceMax,testTemp1}.temp.{current,average}` | ~51 columns. All firmware temperatures in °C. |
58
- | **Frame images** | `frame_chamber`, `frame_galvo`, `frame_thermal` | Embedded image bytes per HF `Image` feature (struct of `{bytes, path}`). Null when no frame of that kind was captured in the 100 ms window before the tick. Loads as a `PIL.Image` via `datasets`. The `path` field inside the struct preserves the original filename for traceability. |
59
- | **Position burst** | `position_hf_burst` | A `list<struct<ts_offset_ms, x, y, z1, z2, r, has_homed>>`. Captures any 1 kHz position-stream events that fell in `(tick_ts - 100 ms, tick_ts]`. Empty list when no motion was happening. |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  ## Files
62
 
63
  ```
64
- data/ticks/{build_id:03d}.parquet # one file per build that had telemetry, zero-padded to 3 digits
65
 
66
- previews/{build_id:03d}/ # per-build MP4 previews (real-time, 10 fps)
67
- chamber.mp4 # optical
68
  thermal.mp4 # IR matrix
69
  galvo.mp4 # scan-mirror trace
70
  composite.mp4 # 1×3 panel: chamber | thermal | galvo
 
 
 
 
71
  ```
72
 
73
- 12 builds had recorded telemetry; very-short failed-heating builds (~12–38 s, no rows) produce no parquet. The HF glob `data/ticks/*.parquet` loads everything across builds. Previews are derived from the same parquet files every build that has a parquet also has previews.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  ## What's lost vs the raw exporter format
76
 
77
- This dataset is **tick-anchored**, not strict-outer-join. Compared to the upstream flat exports, three things are reduced:
78
 
79
- - **Position resolution between motion bursts**: the 1 kHz `position_hf` stream is preserved *during* motion (via the per-tick `position_hf_burst` list) but not as standalone rows between ticks. If you need the raw 1 kHz timeline outside the 100 ms windows, fall back to the upstream `position_hf/{build_id}.parquet`.
80
- - **Sparse-stream events without telemetry**: there is no row for a frame timestamp that doesn't fall near a 10 Hz tick, and no row for sparse `events` (build phase transitions, etc.). Treat this dataset as "what was the state at each tick", not "every recorded event".
81
- - **`plotter_commands`**: not exposed yet — historical builds predate the recorder feature, and the table is empty.
 
 
82
 
83
  ## Joining back to Inova-Mk1-Database
84
 
85
- Each row carries `print_profile_name` — the string the printer was running when the build started, taken straight from the `build_start` event payload. To recover the matching `PrintProfile.Id` UUID, join against the [`ppak10/Inova-Mk1-Database`](https://huggingface.co/datasets/ppak10/Inova-Mk1-Database) `PrintProfiles` entities:
86
 
87
  ```python
88
  import json
89
  from pathlib import Path
90
 
91
- # Wherever you've cloned/snapshotted Inova-Mk1-Database
92
  profiles_dir = Path("Inova-Mk1-Database/source/PrintProfiles")
93
  name_to_id = {
94
  json.load(p.open())["Name"]: json.load(p.open())["Id"]
95
  for p in profiles_dir.glob("*.json")
96
  }
97
-
98
- ticks = ticks.map(lambda r: {**r, "print_profile_id": name_to_id.get(r["print_profile_name"])})
99
  ```
100
 
101
- If `Inova-Mk1-Database` hasn't yet added the profile the build used, the lookup returns null and `print_profile_name` is still preserved as a breadcrumb.
102
-
103
- A planned authoritative `inova_session_id UUID` will replace the name-based fallback once the upstream `Agentic-Additive-Manufacturing-Process-Optimization/data/exports/build_to_inova_session.csv` has been filled in.
104
 
105
  ## Upstream
106
 
107
- The raw data lives in the sibling repository [`Agentic-Additive-Manufacturing-Process-Optimization`](https://github.com/ppak10/Agentic-Additive-Manufacturing-Process-Optimization). Its `scripts/export.py` writes flat files under `data/exports/`. This dataset reads from there directly via a sibling-folder relative path — no live database connection required.
108
-
109
- ## Previews
110
-
111
- Each build that has a parquet also has four MP4s under `previews/{build_id:03d}/`: separate `chamber.mp4` / `thermal.mp4` / `galvo.mp4` and a `composite.mp4` showing all three side-by-side. They play back at 10 fps — the tick rate — so each video's duration equals the build's wall-clock duration (build 26 → ~9h54m of video). Null frames are forward-filled so the picture keeps moving through long heating stretches.
112
 
113
- Previews are sourced from this dataset's own parquet (not the recorder's raw frames), so they see only the per-tick-attached frame subset (~36% chamber, ~37% galvo, ~16% thermal of ticks). The result is choppier than playing the recorder's raw frames at native rate, but the previews are fully self-contained.
114
 
115
  ## Regenerate
116
 
117
  ```sh
118
- uv run scripts/ticks/01_extract.py # all builds with telemetry
119
- uv run scripts/ticks/01_extract.py 13 26 # specific build ids
 
 
 
 
 
 
 
120
 
121
- uv run scripts/previews/01_render.py # all builds with parquet
122
- uv run scripts/previews/01_render.py 13 26 # specific build ids
 
123
  ```
 
25
 
26
  # Inova-Mk1-Telemetry
27
 
28
+ Time-aligned printer-state recordings from Inova Mk1 SLS 3D print runs. One row per 10 Hz **tick** the recorder's `/state/snapshot` poll with the full sensor state snapshot (~64 columns: temperatures, position, power, lights) on every row, the nearest camera frame embedded inline when one fell within the prior 100 ms window, and any 1 kHz position-stream samples from that window collected as a nested list.
29
 
30
+ 25 parquet files across builds spanning 2026-05 through 2026-07. Build metadata (job name, profile, start/end time) is denormalized into every row, so each file is self-sufficient for ML — no joins needed.
31
 
32
  ```python
33
  from datasets import load_dataset
34
+ ds = load_dataset("ppak10/Inova-Mk1-Telemetry", split="train")
35
+ row = ds[0]
36
+ # row["frame_chamber"] → PIL.Image.Image (or None)
37
+ # row["frame_thermal"] → PIL.Image.Image (or None)
38
+ # row["powderBed.temp.current"] → float (°C)
39
+ # row["positions.position.z2"] float (µm)
40
+ # row["position_hf_burst"] → list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
41
  ```
42
 
43
+ Full image bytes are embedded in each row — no separate frame download. Filter to rows with a particular frame kind:
44
+
45
+ ```python
46
+ with_chamber = ds.filter(lambda r: r["frame_chamber"] is not None)
47
+ ```
48
+
49
+ ---
50
+
51
+ ## Timelapse previews
52
+
53
+ Per-build layer-by-layer timelapse GIFs (one frame per detected print layer, 25 fps, ≤ 12 s). Below is the composite (chamber | thermal | galvo) for build 012, the first full Layers-phase run:
54
+
55
+ ![Build 012 galvo timelapse — laser scan trace per layer](previews/012/timelapse_galvo.gif)
56
+
57
+ <sub>Galvo (scan-mirror) trace for build 012 — Hex Coasters, 221 layers. Each frame is the last captured view of one print layer just before the next powder spread. Full composite (chamber | thermal | galvo) at `previews/012/timelapse_composite.gif`.</sub>
58
+
59
+ Individual-kind GIFs (`timelapse_chamber.gif`, `timelapse_thermal.gif`) and full-speed MP4 previews are also available under `previews/{build_id:03d}/`. See the **Previews** section below.
60
 
61
  ---
62
 
63
  ## Row shape
64
 
65
+ Each row is one moment in time (a single 10 Hz tick). ~80 columns:
66
 
67
  | Group | Columns | Notes |
68
  |---|---|---|
69
+ | **Build context** | `build_id`, `job_name`, `started_at`, `ended_at`, `phase`, `print_profile_name`, `inova_session_id` | Denormalized — same value on every row in a given file. `inova_session_id` is null until the upstream sidecar CSV is curated by hand. |
70
+ | **Timestamp** | `ts` (`timestamp[us, UTC]`) | `respondedAt` from `/state/snapshot`. |
71
+ | **Position (10 Hz)** | `positions.position.{x,y,z1,z2,r}` | Stage position in **microns** (firmware native; divide by 1000 for mm). Always present. `z2` advances with each deposited layer and is used for layer detection in the timelapse scripts. |
72
  | **Lights** | `lights.lights.{enabled,count}` | |
73
+ | **Power (W)** | `{laser,fanGalvo,buzzer,laserSafety,io-en,wd-en,wd-in}.power`, `powerman.power.{current,required,max}` | Per-component draw and manager state. |
74
+ | **Temperature (°C)** | `{powderBed,printBed}.temp.{current,average,target}`, `{powderChamber1..4,printChamber1..4}.temp.{current,average,target}`, `{quadrant1..4,surface,surfaceAvg,surfaceMin,surfaceMax,testTemp1}.temp.{current,average}` | ~51 columns. |
75
+ | **Frame images** | `frame_chamber`, `frame_galvo`, `frame_thermal` | HF `Image` feature (struct of `{bytes, path}`). Null when no frame of that kind was captured in the 100 ms window. Loads as `PIL.Image` via `datasets`. `path` preserves the original filename for traceability. |
76
+ | **Position burst** | `position_hf_burst` | `list<struct<ts_offset_ms, x, y, z1, z2, r, has_homed>>`. 1 kHz position events that fell in `(tick_ts 100 ms, tick_ts]`. Empty list during heating/idle. |
77
+
78
+ ### Null frames
79
+
80
+ `frame_*` columns are null when no frame of that kind was captured within the 100 ms tick window — this preserves the "is this image fresh?" signal. Forward-fill for display or training:
81
+
82
+ ```python
83
+ import polars as pl
84
+ df = pl.read_parquet("data/ticks/026.parquet")
85
+ df = df.with_columns(
86
+ pl.col("frame_chamber").forward_fill(),
87
+ pl.col("frame_thermal").forward_fill(),
88
+ pl.col("frame_galvo").forward_fill(),
89
+ )
90
+ ```
91
+
92
+ ---
93
+
94
+ ## Build inventory
95
+
96
+ 25 builds total. Very short failed-heating runs (2–24 ticks) produce a parquet but represent only seconds of recording.
97
+
98
+ | build_id | job_name | ticks | date |
99
+ |---:|---|---:|---|
100
+ | 001 | Hex Coasters 2026_05_31 | 102,805 | 2026-05-31 |
101
+ | 002 | Hex Coasters 2026_05_31 | 68 | 2026-05-31 |
102
+ | 012 | Hex Coasters 2026_05_31 | 201,660 | 2026-05-31 |
103
+ | 013 | D790 and D638 and Benchy 2026_06_02 | 13,811 | 2026-06-02 |
104
+ | 014 | D790 and D638 and Benchy 2026_06_02 | 2 | 2026-06-02 |
105
+ | 016 | D790 and D638 and Benchy 2026_06_02 | 14 | 2026-06-02 |
106
+ | 017 | D790 and D638 and Benchy 2026_06_02 | 2 | 2026-06-02 |
107
+ | 025 | D790 and D638 and Benchy 2026_06_02 | 24 | 2026-06-02 |
108
+ | 026 | D790 and D638 and Benchy 2026_06_02 | 355,580 | 2026-06-02 |
109
+ | 028 | D790 and D638 2026_06_07 | 340,162 | 2026-06-07 |
110
+ | 029 | D790 and D638 and Cards 2026_06_09 | 285,092 | 2026-06-09 |
111
+ | 030 | D790 and D638 Recycled Powder 2026_06_24 | 228,723 | 2026-06-24 |
112
+ | 031 | D790 and D638 Recycled Powder 2026_06_25 | 161,379 | 2026-06-25 |
113
+ | 032 | Hex Coasters and Nameplates and Benchies | 19,954 | 2026-06-27 |
114
+ | 033 | Hex Coasters and Nameplates and Benchies | 1,559 | 2026-06-27 |
115
+ | 034 | Hex Coasters and Nameplates and Benchies | 18,251 | 2026-06-27 |
116
+ | 035 | D790 and D638 and other objects 2026_06_27 | 430,997 | 2026-06-27 |
117
+ | 036 | Hex Coasters and Nameplates and Benchies | 734,064 | 2026-06-28 |
118
+ | 037 | D790 and D638 Debug Run 2026_06_29 | 776 | 2026-06-29 |
119
+ | 038 | D790 and D638 Debug Run 2026_06_29 | 8,294 | 2026-06-29 |
120
+ | 039 | D790 and D638 and Nameplate 2026_06_29 | 334,454 | 2026-06-29 |
121
+ | 040 | D790 and D638 and D256 and Benchy 2026_07_01 | 446,764 | 2026-07-01 |
122
+ | 041 | Unknown 2026_07_09 ¹ | 134,790 | 2026-07-09 |
123
+ | 042 | Nameplates 2026_07_09 | 203,425 | 2026-07-10 |
124
+ | 043 | D790 and D638 and Nameplate 2026_07_10 | 373,863 | 2026-07-10 |
125
+ | **total** | | **4,900,289** | |
126
+
127
+ ¹ Build 041 was recovered from the NVMe spool after the recorder's Postgres database was reset; `job_name` is a placeholder.
128
+
129
+ ---
130
 
131
  ## Files
132
 
133
  ```
134
+ data/ticks/{build_id:03d}.parquet # one file per build, zero-padded (001–043)
135
 
136
+ previews/{build_id:03d}/
137
+ chamber.mp4 # optical — real-time 10 fps, forward-filled
138
  thermal.mp4 # IR matrix
139
  galvo.mp4 # scan-mirror trace
140
  composite.mp4 # 1×3 panel: chamber | thermal | galvo
141
+ timelapse_chamber.gif # layer-by-layer, 25 fps, ≤ 12 s
142
+ timelapse_thermal.gif
143
+ timelapse_galvo.gif
144
+ timelapse_composite.gif # 1×3 panel GIF
145
  ```
146
 
147
+ The HF glob `data/ticks/*.parquet` loads the full dataset across all builds. Builds that never started printing (z2 = 0 throughout) produce a timelapse GIF with zero or one frame.
148
+
149
+ ---
150
+
151
+ ## Previews
152
+
153
+ ### Real-time MP4s
154
+
155
+ Four MP4s per build under `previews/{build_id:03d}/`: `chamber.mp4`, `thermal.mp4`, `galvo.mp4`, and `composite.mp4`. Playback at 10 fps (the tick rate), so video duration equals build wall-clock time — build 026 → ~9h54m of video. Null frames are forward-filled for viewing continuity.
156
+
157
+ ### Timelapse GIFs
158
+
159
+ Four animated GIFs per build sampled one frame per detected print layer:
160
+
161
+ - **Layer detection**: `positions.position.z2` quantized in 100 µm buckets. Only z2 > 0 rows are used, so pre-print heating is automatically excluded.
162
+ - **Representative frame**: the *last* non-null frame within each z2 bucket — the most-recent view of the layer just before recoating begins.
163
+ - **Playback**: 25 fps, capped at 300 frames (12 s max). Null-frame levels are forward-filled within the GIF.
164
+ - **Canvas**: 240 px height (half the MP4 canvas) for web-friendly file sizes.
165
+
166
+ Both previews are sourced from this dataset's own parquet (not the recorder's raw frame files), so they see only the per-tick-attached frame subset (~36% chamber, ~37% galvo, ~16% thermal attachment rate).
167
+
168
+ ---
169
 
170
  ## What's lost vs the raw exporter format
171
 
172
+ This dataset is **tick-anchored**, not a strict outer join. Three things are reduced compared to the upstream flat exports:
173
 
174
+ - **Between-tick position resolution**: the 1 kHz `position_hf` stream is preserved *during* motion via `position_hf_burst`, but not as standalone rows between ticks. For the raw 1 kHz timeline fall back to the upstream `position_hf/{build_id}.parquet`.
175
+ - **Sparse events without telemetry**: no row exists for a camera frame or `events` record that doesn't land near a 10 Hz tick. This dataset represents "state at each tick", not "every recorded event".
176
+ - **`plotter_commands`**: not surfaced — historical builds predate this recorder feature and the table is empty.
177
+
178
+ ---
179
 
180
  ## Joining back to Inova-Mk1-Database
181
 
182
+ Each row carries `print_profile_name` — the string the printer was running when the build started, taken from the `build_start` event payload. To recover the matching `PrintProfile.Id` UUID, join against [`ppak10/Inova-Mk1-Database`](https://huggingface.co/datasets/ppak10/Inova-Mk1-Database):
183
 
184
  ```python
185
  import json
186
  from pathlib import Path
187
 
 
188
  profiles_dir = Path("Inova-Mk1-Database/source/PrintProfiles")
189
  name_to_id = {
190
  json.load(p.open())["Name"]: json.load(p.open())["Id"]
191
  for p in profiles_dir.glob("*.json")
192
  }
193
+ ds = ds.map(lambda r: {**r, "print_profile_id": name_to_id.get(r["print_profile_name"])})
 
194
  ```
195
 
196
+ ---
 
 
197
 
198
  ## Upstream
199
 
200
+ Raw data lives in [`Agentic-Additive-Manufacturing-Process-Optimization`](https://github.com/ppak10/Agentic-Additive-Manufacturing-Process-Optimization). Its `scripts/export.py` produces flat JSONL/parquet files under `data/exports/`. This dataset reads from those directly — no live database connection required.
 
 
 
 
201
 
202
+ ---
203
 
204
  ## Regenerate
205
 
206
  ```sh
207
+ # Full ETL (all builds)
208
+ uv run scripts/ticks/01_extract.py
209
+
210
+ # Specific builds only
211
+ uv run scripts/ticks/01_extract.py 26 28
212
+
213
+ # MP4 previews
214
+ uv run scripts/previews/01_render.py # all builds
215
+ uv run scripts/previews/01_render.py 26 28 # specific builds
216
 
217
+ # Timelapse GIFs
218
+ uv run scripts/previews/02_timelapse.py # all builds
219
+ uv run scripts/previews/02_timelapse.py 26 28 # specific builds
220
  ```
previews/001/timelapse_chamber.gif ADDED

Git LFS Details

  • SHA256: f4fceccba5b9b0fac939e942a1f5e3ee0cb01aec5fc445703dd50b7e4fe1c8d4
  • Pointer size: 131 Bytes
  • Size of remote file: 518 kB
previews/001/timelapse_composite.gif ADDED

Git LFS Details

  • SHA256: e317442ea3730dd5d66ddd823fa5546337596ffc077962abacff989b49ca582e
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
previews/001/timelapse_galvo.gif ADDED

Git LFS Details

  • SHA256: 9113cedb3f4c1480cf9e95b6d4001f0fa00357f660a64f9a14924ffba9b9cfdc
  • Pointer size: 128 Bytes
  • Size of remote file: 462 Bytes
previews/001/timelapse_thermal.gif ADDED

Git LFS Details

  • SHA256: a520679dcc7200406fecd1d95a71d07bc2e238e4178014e329155726b116976d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.11 MB
previews/002/timelapse_chamber.gif ADDED

Git LFS Details

  • SHA256: 146b7181f8fc2beccb75c15463834861d4de48f7c6db611d0afd7f050b86eb80
  • Pointer size: 129 Bytes
  • Size of remote file: 7.42 kB
previews/002/timelapse_composite.gif ADDED

Git LFS Details

  • SHA256: 5f8b1a478c1c4de921e1232a0929596124d53a15372ad8df390061efc5384dc5
  • Pointer size: 130 Bytes
  • Size of remote file: 65.9 kB
previews/002/timelapse_galvo.gif ADDED

Git LFS Details

  • SHA256: 07b32abdc8b60d57f4be14b98859591cb03dd3874abd5c5b1a324a2a1669a194
  • Pointer size: 128 Bytes
  • Size of remote file: 462 Bytes
previews/002/timelapse_thermal.gif ADDED

Git LFS Details

  • SHA256: 7d9b0ffb46be8655a56eddcf08248df592385f3ad2e1fc1727e36f0f2b0d0cff
  • Pointer size: 130 Bytes
  • Size of remote file: 56.8 kB
previews/012/timelapse_chamber.gif ADDED

Git LFS Details

  • SHA256: 8bad86a155204b817031bd82531fd7c9e53a92b2682f04ad53baad77530ab39b
  • Pointer size: 132 Bytes
  • Size of remote file: 6.23 MB
previews/012/timelapse_composite.gif ADDED

Git LFS Details

  • SHA256: a8c16d3870ae18220238ec81e8409d90deeee92f5a3254f9894f98849d230be5
  • Pointer size: 133 Bytes
  • Size of remote file: 16.6 MB
previews/012/timelapse_galvo.gif ADDED

Git LFS Details

  • SHA256: bab050e78e6cd477f490e6634d78a7bb63eaf7d30c0d72222ba7ddb7c6fd66f0
  • Pointer size: 131 Bytes
  • Size of remote file: 599 kB
previews/012/timelapse_thermal.gif ADDED

Git LFS Details

  • SHA256: 885788ca0241d09194f2a668f835ca313133862d2d3fedd11e7ba0605e6411fd
  • Pointer size: 133 Bytes
  • Size of remote file: 11.5 MB
previews/013/timelapse_chamber.gif ADDED

Git LFS Details

  • SHA256: 7e97e763a48919271dfb375eb6aa2fc63a9341f649cffdc8fa31f764f8a0aac0
  • Pointer size: 130 Bytes
  • Size of remote file: 48.2 kB
previews/013/timelapse_composite.gif ADDED

Git LFS Details

  • SHA256: 7dd070a29dff16f010095b3319b4bb133f4dc96ed3ec2de49a83171bcfaf4e0e
  • Pointer size: 130 Bytes
  • Size of remote file: 51.6 kB
previews/013/timelapse_galvo.gif ADDED

Git LFS Details

  • SHA256: 07b32abdc8b60d57f4be14b98859591cb03dd3874abd5c5b1a324a2a1669a194
  • Pointer size: 128 Bytes
  • Size of remote file: 462 Bytes
previews/026/timelapse_chamber.gif ADDED

Git LFS Details

  • SHA256: 61b9c7d079f80d0e1743059caf6c484f0e5d37805ba0bd193e86de62c8bbc145
  • Pointer size: 132 Bytes
  • Size of remote file: 7.19 MB
previews/026/timelapse_composite.gif ADDED

Git LFS Details

  • SHA256: 1bbd5042b629a11bd4394c7cd4190a9dfb089decd3d72dbe580e9f127c513dc7
  • Pointer size: 133 Bytes
  • Size of remote file: 21.4 MB
previews/026/timelapse_galvo.gif ADDED

Git LFS Details

  • SHA256: e609ae55ca260c461939863cbe25ccf985fcf2d564b4c19c8037b77c676a900d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.13 MB
previews/026/timelapse_thermal.gif ADDED

Git LFS Details

  • SHA256: 1212785a203eaa4810d255285a658311945848cbdbb87a8e9e003fd6731af2f2
  • Pointer size: 133 Bytes
  • Size of remote file: 15.7 MB
previews/028/timelapse_chamber.gif ADDED

Git LFS Details

  • SHA256: bbe4b5bcb9b6869cf5e8f396bdcc251c23804d9f152e5ca6dad4e414b78dd197
  • Pointer size: 132 Bytes
  • Size of remote file: 7.18 MB
previews/028/timelapse_composite.gif ADDED

Git LFS Details

  • SHA256: 61bd83b44007a6dcddfad03400c7ec961c2d5b8778a208225125ede3cf4d6810
  • Pointer size: 133 Bytes
  • Size of remote file: 21.1 MB
previews/028/timelapse_galvo.gif ADDED

Git LFS Details

  • SHA256: 665c6f970afe048d3a22342707d99f38133a20b3217167b6bcb3f8f721d9ec86
  • Pointer size: 131 Bytes
  • Size of remote file: 793 kB
previews/028/timelapse_thermal.gif ADDED

Git LFS Details

  • SHA256: 9ccf71ddfcd959677c0a5948b819b94a8c3f2a5b0715214b26de45c77e7d10ff
  • Pointer size: 133 Bytes
  • Size of remote file: 15.6 MB
previews/041/chamber.mp4 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:fad4c8e7ea7d935e82a3be1c9ffe76cd270b5d972dbf4ed5431a1dd94914ad3e
3
- size 657741047
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f348c74f7f8348399b235e409ccd536322951111a6ab5bd19039ccfb22f79cd
3
+ size 657748358
scripts/previews/01_render.py CHANGED
@@ -63,7 +63,10 @@ def _decode_raw(frame_struct, kind: str) -> Image.Image | None:
63
  b = frame_struct.get("bytes")
64
  if b is None:
65
  return None
66
- img = Image.open(io.BytesIO(b)).convert("RGB")
 
 
 
67
  rot = KIND_ROTATION_CW.get(kind, 0)
68
  # Image.Transpose.ROTATE_N rotates N degrees CCW, so CW=N → ROTATE_(360-N).
69
  if rot == 90:
 
63
  b = frame_struct.get("bytes")
64
  if b is None:
65
  return None
66
+ try:
67
+ img = Image.open(io.BytesIO(b)).convert("RGB")
68
+ except Exception:
69
+ return None
70
  rot = KIND_ROTATION_CW.get(kind, 0)
71
  # Image.Transpose.ROTATE_N rotates N degrees CCW, so CW=N → ROTATE_(360-N).
72
  if rot == 90:
scripts/previews/02_timelapse.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Render per-layer timelapse GIFs for each build.
3
+
4
+ Reads data/ticks/{build_id:03d}.parquet and writes:
5
+ previews/{build_id:03d}/timelapse_chamber.gif
6
+ previews/{build_id:03d}/timelapse_thermal.gif
7
+ previews/{build_id:03d}/timelapse_galvo.gif
8
+ previews/{build_id:03d}/timelapse_composite.gif (1×3 panel: chamber | thermal | galvo)
9
+
10
+ Layer detection: positions.position.z2 is quantized in 100 µm buckets.
11
+ Only z2 > 0 rows are used — z2 stays at 0 during pre-print heating so this
12
+ naturally excludes the heating phase without needing to inspect the phase column.
13
+ The *last* non-null frame within each z2 bucket is the representative — that's
14
+ the most-recent view of the layer just before recoating begins.
15
+
16
+ Null-frame levels are forward-filled from the most recent non-null level of the
17
+ same kind, so the GIF never shows a blank panel mid-timelapse.
18
+
19
+ Subsampled to at most MAX_FRAMES (default 300). At GIF_FPS=25 that gives
20
+ a max 12-second GIF. Builds with fewer detected layers are not padded.
21
+
22
+ Canvas is scaled to GIF_PANEL_HEIGHT=240 px (half the MP4 panel height) to
23
+ keep file sizes web-friendly for README embedding.
24
+
25
+ Usage:
26
+ uv run scripts/previews/02_timelapse.py # all builds in data/ticks/
27
+ uv run scripts/previews/02_timelapse.py 26 28 # specific build ids
28
+ uv run scripts/previews/02_timelapse.py 26 --kinds chamber,composite
29
+ """
30
+ import io
31
+ import sys
32
+ from pathlib import Path
33
+
34
+ import pyarrow.parquet as pq
35
+ from PIL import Image
36
+
37
+ sys.path.insert(0, str(Path(__file__).parent.parent))
38
+ from _lib import DATA_DIR
39
+
40
+ OUTPUT_DIR = DATA_DIR.parent / "previews"
41
+ TICKS_DIR = DATA_DIR / "ticks"
42
+
43
+ FRAME_KINDS = ("chamber", "thermal", "galvo")
44
+ KIND_ROTATION_CW = {"chamber": 90} # degrees; see _decode_raw
45
+
46
+ GIF_FPS = 25
47
+ GIF_DURATION_MS = int(1000 / GIF_FPS) # 40 ms per frame
48
+ MAX_FRAMES = 300 # subsample cap → max 12 s GIF
49
+ LAYER_QUANTIZE_UM = 100 # z2 bucket size in microns
50
+ GIF_PANEL_HEIGHT = 240 # panel height in pixels for GIF canvas
51
+ BATCH_ROWS = 1000 # pyarrow streaming batch size
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Image helpers (mirrors 01_render.py exactly)
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def _decode_raw(b: bytes, kind: str) -> Image.Image | None:
59
+ """Decode raw image bytes to PIL RGB with orientation correction."""
60
+ if not b:
61
+ return None
62
+ try:
63
+ img = Image.open(io.BytesIO(b)).convert("RGB")
64
+ except Exception:
65
+ return None
66
+ rot = KIND_ROTATION_CW.get(kind, 0)
67
+ if rot == 90:
68
+ img = img.transpose(Image.Transpose.ROTATE_270)
69
+ elif rot == 180:
70
+ img = img.transpose(Image.Transpose.ROTATE_180)
71
+ elif rot == 270:
72
+ img = img.transpose(Image.Transpose.ROTATE_90)
73
+ return img
74
+
75
+
76
+ def _fit_to_canvas(img: Image.Image, canvas_w: int) -> Image.Image:
77
+ """Letterbox img into (canvas_w × GIF_PANEL_HEIGHT) with dark-gray fill."""
78
+ sw, sh = img.size
79
+ scale = min(canvas_w / sw, GIF_PANEL_HEIGHT / sh)
80
+ nw = max(1, round(sw * scale))
81
+ nh = max(1, round(sh * scale))
82
+ fitted = img.resize((nw, nh), Image.BILINEAR)
83
+ canvas = Image.new("RGB", (canvas_w, GIF_PANEL_HEIGHT), (20, 20, 20))
84
+ canvas.paste(fitted, ((canvas_w - nw) // 2, (GIF_PANEL_HEIGHT - nh) // 2))
85
+ return canvas
86
+
87
+
88
+ def _placeholder(canvas_w: int) -> Image.Image:
89
+ return Image.new("RGB", (canvas_w, GIF_PANEL_HEIGHT), (20, 20, 20))
90
+
91
+
92
+ def _canvas_width_from_bytes(b: bytes, kind: str) -> int:
93
+ """Decode one frame to determine the locked canvas width for this kind."""
94
+ img = _decode_raw(b, kind)
95
+ if img is None:
96
+ return GIF_PANEL_HEIGHT # square fallback
97
+ sw, sh = img.size
98
+ return max(2, round(sw * GIF_PANEL_HEIGHT / sh))
99
+
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # Layer data collection
103
+ # ---------------------------------------------------------------------------
104
+
105
+ def collect_layer_bytes(parquet_path: Path, kind: str) -> dict[int, bytes]:
106
+ """Single-pass stream → {z2_level: last_non_null_bytes}.
107
+
108
+ Only z2 > 0 rows are included. The dict is keyed by int(z2 / LAYER_QUANTIZE_UM);
109
+ each entry holds the bytes of the *last* non-null frame seen at that level.
110
+ Reads only two parquet columns (z2 + one frame kind) for efficiency.
111
+ """
112
+ frame_col = f"frame_{kind}"
113
+ z2_col = "positions.position.z2"
114
+ pf = pq.ParquetFile(parquet_path)
115
+ present = {f.name for f in pf.schema_arrow}
116
+ if frame_col not in present or z2_col not in present:
117
+ return {}
118
+
119
+ layer_data: dict[int, bytes] = {}
120
+ for batch in pf.iter_batches(columns=[z2_col, frame_col], batch_size=BATCH_ROWS):
121
+ z2_list = batch.column(z2_col).to_pylist()
122
+ frame_list = batch.column(frame_col).to_pylist()
123
+ for z2, struct in zip(z2_list, frame_list):
124
+ if z2 is None or z2 <= 0:
125
+ continue
126
+ level = int(z2 / LAYER_QUANTIZE_UM)
127
+ if struct is not None:
128
+ b = struct.get("bytes")
129
+ if b:
130
+ layer_data[level] = b
131
+ return layer_data
132
+
133
+
134
+ def collect_all_kinds(parquet_path: Path) -> dict[str, dict[int, bytes]]:
135
+ """Single streaming pass collecting all three kinds simultaneously.
136
+
137
+ Used by render_timelapse_composite so we don't make three separate passes
138
+ through (potentially 17+ GB) parquet files. Reads four columns: z2 + the
139
+ three frame columns. Each kind gets its own {z2_level: bytes} dict.
140
+ """
141
+ z2_col = "positions.position.z2"
142
+ pf = pq.ParquetFile(parquet_path)
143
+ present = {f.name for f in pf.schema_arrow}
144
+ read_cols = [c for c in ([z2_col] + [f"frame_{k}" for k in FRAME_KINDS]) if c in present]
145
+ if z2_col not in read_cols:
146
+ return {k: {} for k in FRAME_KINDS}
147
+
148
+ layer_data: dict[str, dict[int, bytes]] = {k: {} for k in FRAME_KINDS}
149
+ for batch in pf.iter_batches(columns=read_cols, batch_size=BATCH_ROWS):
150
+ z2_list = batch.column(z2_col).to_pylist()
151
+ for kind in FRAME_KINDS:
152
+ col = f"frame_{kind}"
153
+ if col not in read_cols:
154
+ continue
155
+ frame_list = batch.column(col).to_pylist()
156
+ for z2, struct in zip(z2_list, frame_list):
157
+ if z2 is None or z2 <= 0:
158
+ continue
159
+ level = int(z2 / LAYER_QUANTIZE_UM)
160
+ if struct is not None:
161
+ b = struct.get("bytes")
162
+ if b:
163
+ layer_data[kind][level] = b
164
+ return layer_data
165
+
166
+
167
+ # ---------------------------------------------------------------------------
168
+ # Subsampling and forward-fill
169
+ # ---------------------------------------------------------------------------
170
+
171
+ def _subsample(levels: list[int]) -> list[int]:
172
+ """Evenly subsample sorted levels down to at most MAX_FRAMES."""
173
+ if len(levels) <= MAX_FRAMES:
174
+ return levels
175
+ step = len(levels) / MAX_FRAMES
176
+ return [levels[round(i * step)] for i in range(MAX_FRAMES)]
177
+
178
+
179
+ def _forward_fill(layer_bytes: dict[int, bytes],
180
+ target_levels: list[int]) -> list[bytes | None]:
181
+ """For each target level, return the bytes at that level or the most
182
+ recent non-null bytes seen so far (forward-fill across gaps)."""
183
+ out: list[bytes | None] = []
184
+ last: bytes | None = None
185
+ for lvl in target_levels:
186
+ b = layer_bytes.get(lvl)
187
+ if b is not None:
188
+ last = b
189
+ out.append(last)
190
+ return out
191
+
192
+
193
+ # ---------------------------------------------------------------------------
194
+ # GIF writer
195
+ # ---------------------------------------------------------------------------
196
+
197
+ def _write_gif(frames: list[Image.Image], out_path: Path) -> None:
198
+ """Palette-quantize and save frames as an animated GIF."""
199
+ out_path.parent.mkdir(parents=True, exist_ok=True)
200
+ palette_frames = [
201
+ f.quantize(colors=256, method=Image.Quantize.MEDIANCUT,
202
+ dither=Image.Dither.FLOYDSTEINBERG)
203
+ for f in frames
204
+ ]
205
+ palette_frames[0].save(
206
+ out_path,
207
+ format="GIF",
208
+ save_all=True,
209
+ append_images=palette_frames[1:],
210
+ loop=0,
211
+ duration=GIF_DURATION_MS,
212
+ optimize=False,
213
+ )
214
+
215
+
216
+ # ---------------------------------------------------------------------------
217
+ # Per-build renderers
218
+ # ---------------------------------------------------------------------------
219
+
220
+ def render_timelapse_kind(parquet_path: Path, kind: str, out_path: Path) -> int:
221
+ """Write timelapse_{kind}.gif. Returns number of GIF frames written."""
222
+ layer_bytes = collect_layer_bytes(parquet_path, kind)
223
+ if not layer_bytes:
224
+ print(f" {kind:8s}: no printing-phase frames (z2 > 0), skipping")
225
+ return 0
226
+
227
+ sorted_levels = sorted(layer_bytes)
228
+ target_levels = _subsample(sorted_levels)
229
+ fill_bytes = _forward_fill(layer_bytes, target_levels)
230
+ canvas_w = _canvas_width_from_bytes(next(b for b in fill_bytes if b), kind)
231
+
232
+ pil_frames: list[Image.Image] = []
233
+ for b in fill_bytes:
234
+ img = _decode_raw(b, kind) if b else None
235
+ pil_frames.append(
236
+ _fit_to_canvas(img, canvas_w) if img else _placeholder(canvas_w)
237
+ )
238
+
239
+ _write_gif(pil_frames, out_path)
240
+ return len(pil_frames)
241
+
242
+
243
+ def render_timelapse_composite(parquet_path: Path, out_path: Path) -> int:
244
+ """Write timelapse_composite.gif (1×3 panel). Single parquet pass."""
245
+ all_bytes = collect_all_kinds(parquet_path)
246
+
247
+ all_levels = sorted(set().union(*(set(d) for d in all_bytes.values())))
248
+ if not all_levels:
249
+ print(" composite: no printing-phase frames (z2 > 0), skipping")
250
+ return 0
251
+
252
+ target_levels = _subsample(all_levels)
253
+ fill_per_kind = {k: _forward_fill(all_bytes[k], target_levels) for k in FRAME_KINDS}
254
+
255
+ canvas_widths: dict[str, int] = {}
256
+ for kind in FRAME_KINDS:
257
+ first_b = next((b for b in fill_per_kind[kind] if b), None)
258
+ canvas_widths[kind] = (
259
+ _canvas_width_from_bytes(first_b, kind) if first_b else GIF_PANEL_HEIGHT
260
+ )
261
+ total_w = sum(canvas_widths.values())
262
+
263
+ pil_frames: list[Image.Image] = []
264
+ for i in range(len(target_levels)):
265
+ composite = Image.new("RGB", (total_w, GIF_PANEL_HEIGHT), (20, 20, 20))
266
+ x = 0
267
+ for kind in FRAME_KINDS:
268
+ b = fill_per_kind[kind][i]
269
+ img = _decode_raw(b, kind) if b else None
270
+ panel = (
271
+ _fit_to_canvas(img, canvas_widths[kind])
272
+ if img else _placeholder(canvas_widths[kind])
273
+ )
274
+ composite.paste(panel, (x, 0))
275
+ x += canvas_widths[kind]
276
+ pil_frames.append(composite)
277
+
278
+ _write_gif(pil_frames, out_path)
279
+ return len(pil_frames)
280
+
281
+
282
+ def process_build(build_id: int, kinds: set[str]) -> None:
283
+ parquet_path = TICKS_DIR / f"{build_id:03d}.parquet"
284
+ if not parquet_path.exists():
285
+ print(f"build {build_id:03d}: no parquet, skipping")
286
+ return
287
+
288
+ build_dir = OUTPUT_DIR / f"{build_id:03d}"
289
+ print(f"build {build_id:03d}: timelapse GIFs → {build_dir.relative_to(Path.cwd())}/")
290
+
291
+ for kind in FRAME_KINDS:
292
+ if kind not in kinds:
293
+ continue
294
+ out = build_dir / f"timelapse_{kind}.gif"
295
+ n = render_timelapse_kind(parquet_path, kind, out)
296
+ if out.exists():
297
+ size = out.stat().st_size
298
+ print(f" {kind:8s}: {n:>4} frames → {out.name} ({size:,} bytes)")
299
+
300
+ if "composite" in kinds:
301
+ out = build_dir / "timelapse_composite.gif"
302
+ n = render_timelapse_composite(parquet_path, out)
303
+ if out.exists():
304
+ size = out.stat().st_size
305
+ print(f" composite: {n:>4} frames → {out.name} ({size:,} bytes)")
306
+
307
+
308
+ def main():
309
+ import argparse
310
+ parser = argparse.ArgumentParser(
311
+ description=__doc__,
312
+ formatter_class=argparse.RawDescriptionHelpFormatter,
313
+ )
314
+ parser.add_argument("build_ids", nargs="*", type=int,
315
+ help="Build IDs to render (default: all in data/ticks/)")
316
+ parser.add_argument(
317
+ "--kinds", default="chamber,thermal,galvo,composite",
318
+ help="Comma-separated outputs to render. "
319
+ "Valid: chamber, thermal, galvo, composite. Default: all four.",
320
+ )
321
+ args = parser.parse_args()
322
+ kinds = set(args.kinds.split(","))
323
+ unknown = kinds - (set(FRAME_KINDS) | {"composite"})
324
+ if unknown:
325
+ parser.error(f"unknown --kinds values: {sorted(unknown)}")
326
+
327
+ targets = args.build_ids or sorted(int(p.stem) for p in TICKS_DIR.glob("*.parquet"))
328
+ for bid in targets:
329
+ process_build(bid, kinds)
330
+
331
+
332
+ if __name__ == "__main__":
333
+ main()
scripts/ticks/00_export_new_db.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export new-DB builds into the export-format files with offset build IDs.
3
+
4
+ The Postgres DB was reset after build 40, so the new DB's build IDs restart at
5
+ 1. This script exports them with remapped IDs so they don't collide with the
6
+ existing dataset (builds 1-41 already processed).
7
+
8
+ Usage:
9
+ uv run --with psycopg2-binary scripts/ticks/00_export_new_db.py 1:42 2:43
10
+ uv run --with psycopg2-binary scripts/ticks/00_export_new_db.py 3:44
11
+
12
+ Each argument is old_db_id:new_dataset_id. Don't export an in-progress build
13
+ (no ended_at in the DB) — wait for it to finish and the spool to be imported.
14
+
15
+ Safe to re-run: telemetry/position_hf parquets are always overwritten; jsonl
16
+ files are checked first and skip if the new_id is already present.
17
+ """
18
+ import json
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ import psycopg2
23
+ import psycopg2.extras
24
+ import pyarrow as pa
25
+ import pyarrow.parquet as pq
26
+
27
+ sys.path.insert(0, str(Path(__file__).parent.parent))
28
+ from _lib import EXPORTS_DIR
29
+
30
+ DATABASE_URL = "postgres://inova:inova@localhost:5432/inova"
31
+ BATCH_ROWS = 100_000
32
+
33
+
34
+ def get_conn():
35
+ return psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
36
+
37
+
38
+ def export_telemetry(conn, old_id: int, new_id: int):
39
+ out = EXPORTS_DIR / "telemetry" / f"{new_id}.parquet"
40
+ out.parent.mkdir(parents=True, exist_ok=True)
41
+
42
+ schema = pa.schema([
43
+ pa.field("ts", pa.timestamp("us", tz="UTC")),
44
+ pa.field("sensor_id", pa.string()),
45
+ pa.field("kind", pa.string()),
46
+ pa.field("value", pa.float64()),
47
+ ])
48
+
49
+ with conn.cursor() as cur:
50
+ cur.execute(
51
+ "SELECT COUNT(*) AS n FROM telemetry WHERE build_id = %s", (old_id,)
52
+ )
53
+ total = cur.fetchone()["n"]
54
+ if total == 0:
55
+ print(f" [{old_id}→{new_id}] telemetry: 0 rows in DB, skipping")
56
+ return
57
+
58
+ cur.execute(
59
+ "SELECT ts, sensor_id, kind, value FROM telemetry WHERE build_id = %s ORDER BY ts",
60
+ (old_id,)
61
+ )
62
+ written = 0
63
+ with pq.ParquetWriter(out, schema, compression="zstd") as writer:
64
+ while True:
65
+ rows = cur.fetchmany(BATCH_ROWS)
66
+ if not rows:
67
+ break
68
+ table = pa.table({
69
+ "ts": pa.array([r["ts"] for r in rows], type=pa.timestamp("us", tz="UTC")),
70
+ "sensor_id": pa.array([r["sensor_id"] for r in rows], type=pa.string()),
71
+ "kind": pa.array([r["kind"] for r in rows], type=pa.string()),
72
+ "value": pa.array([float(r["value"]) for r in rows], type=pa.float64()),
73
+ }, schema=schema)
74
+ writer.write_table(table)
75
+ written += len(rows)
76
+ print(f" [{old_id}→{new_id}] telemetry: {written:,}/{total:,}...", end="\r")
77
+ print(f" [{old_id}→{new_id}] telemetry: {written:,} rows → {out.name} ")
78
+
79
+
80
+ def export_position_hf(conn, old_id: int, new_id: int):
81
+ out = EXPORTS_DIR / "position_hf" / f"{new_id}.parquet"
82
+ out.parent.mkdir(parents=True, exist_ok=True)
83
+
84
+ schema = pa.schema([
85
+ pa.field("ts", pa.timestamp("us", tz="UTC")),
86
+ pa.field("x", pa.float64()),
87
+ pa.field("y", pa.float64()),
88
+ pa.field("z1", pa.float64()),
89
+ pa.field("z2", pa.float64()),
90
+ pa.field("r", pa.float64()),
91
+ pa.field("has_homed", pa.bool_()),
92
+ ])
93
+
94
+ with conn.cursor() as cur:
95
+ cur.execute(
96
+ "SELECT ts, x, y, z1, z2, r, has_homed FROM position_hf WHERE build_id = %s ORDER BY ts",
97
+ (old_id,)
98
+ )
99
+ rows = cur.fetchall()
100
+
101
+ if not rows:
102
+ print(f" [{old_id}→{new_id}] position_hf: 0 rows")
103
+ return
104
+
105
+ table = pa.table({
106
+ "ts": pa.array([r["ts"] for r in rows], type=pa.timestamp("us", tz="UTC")),
107
+ "x": pa.array([float(r["x"]) for r in rows], type=pa.float64()),
108
+ "y": pa.array([float(r["y"]) for r in rows], type=pa.float64()),
109
+ "z1": pa.array([float(r["z1"]) for r in rows], type=pa.float64()),
110
+ "z2": pa.array([float(r["z2"]) for r in rows], type=pa.float64()),
111
+ "r": pa.array([float(r["r"]) for r in rows], type=pa.float64()),
112
+ "has_homed": pa.array([bool(r["has_homed"]) for r in rows], type=pa.bool_()),
113
+ }, schema=schema)
114
+ pq.write_table(table, out, compression="zstd")
115
+ print(f" [{old_id}→{new_id}] position_hf: {len(rows):,} rows → {out.name}")
116
+
117
+
118
+ def append_builds_jsonl(conn, old_id: int, new_id: int):
119
+ out = EXPORTS_DIR / "builds.jsonl"
120
+
121
+ if out.exists():
122
+ with out.open(encoding="utf-8") as f:
123
+ for line in f:
124
+ try:
125
+ r = json.loads(line)
126
+ if r.get("id") == new_id:
127
+ print(f" [{old_id}→{new_id}] builds.jsonl: id={new_id} already present, skipping")
128
+ return
129
+ except Exception:
130
+ pass
131
+
132
+ with get_conn() as c, c.cursor() as cur:
133
+ cur.execute("SELECT * FROM builds WHERE id = %s", (old_id,))
134
+ row = cur.fetchone()
135
+
136
+ if not row:
137
+ print(f" [{old_id}→{new_id}] builds.jsonl: build {old_id} not in DB, skipping")
138
+ return
139
+
140
+ entry = {
141
+ "id": new_id,
142
+ "job_name": row["job_name"],
143
+ "started_at": row["started_at"].isoformat() if row["started_at"] else None,
144
+ "ended_at": row["ended_at"].isoformat() if row["ended_at"] else None,
145
+ "phase": row["phase"],
146
+ "params": row["params"],
147
+ "notes": (row["notes"] or "") + f" [originally DB id={old_id}, remapped to {new_id}]",
148
+ }
149
+ with out.open("a", encoding="utf-8") as f:
150
+ f.write(json.dumps(entry) + "\n")
151
+ print(f" [{old_id}→{new_id}] builds.jsonl: appended id={new_id} ({entry['job_name']})")
152
+
153
+
154
+ def append_frames_jsonl(conn, old_id: int, new_id: int):
155
+ out = EXPORTS_DIR / "frames.jsonl"
156
+
157
+ if out.exists():
158
+ with out.open(encoding="utf-8") as f:
159
+ for line in f:
160
+ try:
161
+ r = json.loads(line)
162
+ if r.get("build_id") == new_id:
163
+ print(f" [{old_id}→{new_id}] frames.jsonl: build_id={new_id} already present, skipping")
164
+ return
165
+ except Exception:
166
+ pass
167
+
168
+ max_id = 0
169
+ if out.exists():
170
+ with out.open(encoding="utf-8") as f:
171
+ for line in f:
172
+ try:
173
+ r = json.loads(line)
174
+ max_id = max(max_id, int(r.get("id", 0)))
175
+ except Exception:
176
+ pass
177
+
178
+ with conn.cursor() as cur:
179
+ cur.execute(
180
+ "SELECT id, ts, kind, path FROM frames WHERE build_id = %s ORDER BY ts",
181
+ (old_id,)
182
+ )
183
+ rows = cur.fetchall()
184
+
185
+ if not rows:
186
+ print(f" [{old_id}→{new_id}] frames.jsonl: 0 frames in DB")
187
+ return
188
+
189
+ with out.open("a", encoding="utf-8") as f:
190
+ for i, r in enumerate(rows):
191
+ entry = {
192
+ "id": max_id + i + 1,
193
+ "build_id": new_id,
194
+ "ts": r["ts"].isoformat(),
195
+ "kind": r["kind"],
196
+ "path": r["path"],
197
+ }
198
+ f.write(json.dumps(entry) + "\n")
199
+ print(f" [{old_id}→{new_id}] frames.jsonl: appended {len(rows):,} rows")
200
+
201
+
202
+ def append_events_jsonl(conn, old_id: int, new_id: int):
203
+ """Append build_start event so load_build_to_profile_name() picks up the
204
+ print profile name for this build."""
205
+ out = EXPORTS_DIR / "events.jsonl"
206
+
207
+ if out.exists():
208
+ with out.open(encoding="utf-8") as f:
209
+ for line in f:
210
+ try:
211
+ r = json.loads(line)
212
+ if r.get("build_id") == new_id and r.get("kind") == "build_start":
213
+ print(f" [{old_id}→{new_id}] events.jsonl: build_start already present, skipping")
214
+ return
215
+ except Exception:
216
+ pass
217
+
218
+ with conn.cursor() as cur:
219
+ cur.execute(
220
+ "SELECT * FROM events WHERE build_id = %s AND kind = 'build_start' LIMIT 1",
221
+ (old_id,)
222
+ )
223
+ row = cur.fetchone()
224
+
225
+ if not row:
226
+ print(f" [{old_id}→{new_id}] events.jsonl: no build_start event in DB")
227
+ return
228
+
229
+ entry = {
230
+ "id": -(new_id),
231
+ "build_id": new_id,
232
+ "ts": row["ts"].isoformat() if row["ts"] else None,
233
+ "kind": "build_start",
234
+ "message": row["message"],
235
+ "payload": row["payload"],
236
+ }
237
+ with out.open("a", encoding="utf-8") as f:
238
+ f.write(json.dumps(entry) + "\n")
239
+ print(f" [{old_id}→{new_id}] events.jsonl: appended build_start")
240
+
241
+
242
+ def main():
243
+ if len(sys.argv) < 2:
244
+ print(__doc__)
245
+ sys.exit(1)
246
+
247
+ mappings: list[tuple[int, int]] = []
248
+ for arg in sys.argv[1:]:
249
+ try:
250
+ old_s, new_s = arg.split(":")
251
+ mappings.append((int(old_s), int(new_s)))
252
+ except ValueError:
253
+ print(f"Bad argument {arg!r} — expected old_id:new_id")
254
+ sys.exit(1)
255
+
256
+ conn = get_conn()
257
+ try:
258
+ for old_id, new_id in mappings:
259
+ print(f"\nExporting DB build {old_id} → dataset build {new_id}")
260
+ export_telemetry(conn, old_id, new_id)
261
+ export_position_hf(conn, old_id, new_id)
262
+ append_builds_jsonl(conn, old_id, new_id)
263
+ append_frames_jsonl(conn, old_id, new_id)
264
+ append_events_jsonl(conn, old_id, new_id)
265
+ finally:
266
+ conn.close()
267
+
268
+ new_ids = " ".join(str(n) for _, n in mappings)
269
+ print(f"\nDone. Run: uv run scripts/ticks/01_extract.py {new_ids}")
270
+
271
+
272
+ if __name__ == "__main__":
273
+ main()
scripts/ticks/00_recover_spool41.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """One-off recovery: build 41 from NVMe spool into export-format files.
3
+
4
+ Build 41 ran 2026-07-09 21:09 → 2026-07-10 00:55 UTC (~3h45m) but the
5
+ Postgres DB was wiped before the spool importer could process it. This script
6
+ reads the raw spool files directly and produces the same export-format files
7
+ that `export.py` would have written, with build_id=41 throughout.
8
+
9
+ Outputs (written into the recorder repo's data/exports/):
10
+ telemetry/41.parquet — (ts, sensor_id, kind, value)
11
+ position_hf/41.parquet — (ts, x, y, z1, z2, r, has_homed)
12
+ frames.jsonl — appended rows with build_id=41
13
+ builds.jsonl — appended row with id=41
14
+ events.jsonl — appended build_start row with build_id=41
15
+
16
+ Safe to re-run: telemetry and position_hf parquets are overwritten; jsonl
17
+ files are checked first and a second run skips appending if id=41 is already
18
+ present.
19
+ """
20
+ import json
21
+ import sys
22
+ from pathlib import Path
23
+ from datetime import datetime, timezone
24
+
25
+ import pyarrow as pa
26
+ import pyarrow.parquet as pq
27
+
28
+
29
+ def parse_ts(s: str) -> datetime:
30
+ """Parse ISO 8601 string (with tz offset or Z) to a UTC-aware datetime."""
31
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
32
+
33
+ sys.path.insert(0, str(Path(__file__).parent.parent))
34
+ from _lib import EXPORTS_DIR, AGENTIC_ROOT
35
+
36
+ SPOOL_DIR = Path("/home/ppak/.agentic-sls/spool/41")
37
+ BUILD_ID = 41
38
+ JOB_NAME = "Unknown 2026_07_09"
39
+
40
+
41
+ def expand_snapshot(snap: dict) -> list[dict]:
42
+ """Mirror telemetry.ts:expand() — one JSON spool line → list of rows."""
43
+ ts = snap["respondedAt"]
44
+ s = snap["data"]
45
+ rows: list[dict] = []
46
+
47
+ for k in ("x", "y", "z1", "z2", "r"):
48
+ rows.append({"ts": ts, "sensor_id": "positions", "kind": f"position.{k}",
49
+ "value": float(s["position"][k])})
50
+
51
+ rows.append({"ts": ts, "sensor_id": "lights", "kind": "lights.enabled",
52
+ "value": 1.0 if s["lights"]["isEnabled"] else 0.0})
53
+ rows.append({"ts": ts, "sensor_id": "lights", "kind": "lights.count",
54
+ "value": float(s["lights"]["lightCount"])})
55
+
56
+ for e in s["power"]["entries"]:
57
+ rows.append({"ts": ts, "sensor_id": e["id"], "kind": "power",
58
+ "value": float(e["power"])})
59
+ pm = s["power"]["powerman"]
60
+ rows.append({"ts": ts, "sensor_id": "powerman", "kind": "power.current",
61
+ "value": float(pm["currentPower"])})
62
+ rows.append({"ts": ts, "sensor_id": "powerman", "kind": "power.required",
63
+ "value": float(pm["requiredPower"])})
64
+ rows.append({"ts": ts, "sensor_id": "powerman", "kind": "power.max",
65
+ "value": float(pm["maxPower"])})
66
+
67
+ for e in s["temperature"]["entries"]:
68
+ rows.append({"ts": ts, "sensor_id": e["id"], "kind": "temp.current",
69
+ "value": float(e["currentTemperature"])})
70
+ rows.append({"ts": ts, "sensor_id": e["id"], "kind": "temp.average",
71
+ "value": float(e["averageTemperature"])})
72
+ tgt = e.get("targetTemperature")
73
+ if tgt is not None:
74
+ rows.append({"ts": ts, "sensor_id": e["id"], "kind": "temp.target",
75
+ "value": float(tgt)})
76
+
77
+ return rows
78
+
79
+
80
+ def build_telemetry_parquet() -> tuple[str, str]:
81
+ """Expand spool telemetry → data/exports/telemetry/41.parquet.
82
+ Returns (first_ts_str, last_ts_str) for builds.jsonl."""
83
+ path = SPOOL_DIR / "telemetry.ndjson"
84
+ out = EXPORTS_DIR / "telemetry" / f"{BUILD_ID}.parquet"
85
+ out.parent.mkdir(parents=True, exist_ok=True)
86
+
87
+ schema = pa.schema([
88
+ pa.field("ts", pa.timestamp("us", tz="UTC")),
89
+ pa.field("sensor_id", pa.string()),
90
+ pa.field("kind", pa.string()),
91
+ pa.field("value", pa.float64()),
92
+ ])
93
+
94
+ BATCH = 50_000
95
+ first_ts = last_ts = None
96
+ bad = 0
97
+ total = 0
98
+
99
+ with pq.ParquetWriter(out, schema, compression="zstd") as writer:
100
+ buf: list[dict] = []
101
+
102
+ def flush():
103
+ nonlocal total
104
+ if not buf:
105
+ return
106
+ ts_arr = pa.array([parse_ts(r["ts"]) for r in buf], type=pa.timestamp("us", tz="UTC"))
107
+ table = pa.table({
108
+ "ts": ts_arr,
109
+ "sensor_id": pa.array([r["sensor_id"] for r in buf], type=pa.string()),
110
+ "kind": pa.array([r["kind"] for r in buf], type=pa.string()),
111
+ "value": pa.array([r["value"] for r in buf], type=pa.float64()),
112
+ }, schema=schema)
113
+ writer.write_table(table)
114
+ total += len(buf)
115
+ buf.clear()
116
+
117
+ with path.open(encoding="utf-8") as f:
118
+ for line in f:
119
+ line = line.strip()
120
+ if not line:
121
+ continue
122
+ try:
123
+ snap = json.loads(line)
124
+ except json.JSONDecodeError:
125
+ bad += 1
126
+ continue
127
+ ts = snap.get("respondedAt")
128
+ if first_ts is None:
129
+ first_ts = ts
130
+ last_ts = ts
131
+ try:
132
+ rows = expand_snapshot(snap)
133
+ except Exception:
134
+ bad += 1
135
+ continue
136
+ buf.extend(rows)
137
+ if len(buf) >= BATCH:
138
+ flush()
139
+ flush()
140
+
141
+ print(f" telemetry: {total:,} rows, {bad} bad lines → {out.name}")
142
+ return first_ts, last_ts
143
+
144
+
145
+ def build_position_parquet():
146
+ path = SPOOL_DIR / "position.ndjson"
147
+ out = EXPORTS_DIR / "position_hf" / f"{BUILD_ID}.parquet"
148
+ out.parent.mkdir(parents=True, exist_ok=True)
149
+
150
+ schema = pa.schema([
151
+ pa.field("ts", pa.timestamp("us", tz="UTC")),
152
+ pa.field("x", pa.float64()),
153
+ pa.field("y", pa.float64()),
154
+ pa.field("z1", pa.float64()),
155
+ pa.field("z2", pa.float64()),
156
+ pa.field("r", pa.float64()),
157
+ pa.field("has_homed", pa.bool_()),
158
+ ])
159
+
160
+ rows: list[dict] = []
161
+ bad = 0
162
+ with path.open(encoding="utf-8") as f:
163
+ for line in f:
164
+ line = line.strip()
165
+ if not line:
166
+ continue
167
+ try:
168
+ rec = json.loads(line)
169
+ d = rec["data"]
170
+ rows.append({
171
+ "ts": rec["respondedAt"],
172
+ "x": float(d["x"]),
173
+ "y": float(d["y"]),
174
+ "z1": float(d["z1"]),
175
+ "z2": float(d["z2"]),
176
+ "r": float(d["r"]),
177
+ "has_homed": bool(d["hasHomed"]),
178
+ })
179
+ except Exception:
180
+ bad += 1
181
+
182
+ if rows:
183
+ table = pa.table({
184
+ "ts": pa.array([parse_ts(r["ts"]) for r in rows], type=pa.timestamp("us", tz="UTC")),
185
+ "x": pa.array([r["x"] for r in rows], type=pa.float64()),
186
+ "y": pa.array([r["y"] for r in rows], type=pa.float64()),
187
+ "z1": pa.array([r["z1"] for r in rows], type=pa.float64()),
188
+ "z2": pa.array([r["z2"] for r in rows], type=pa.float64()),
189
+ "r": pa.array([r["r"] for r in rows], type=pa.float64()),
190
+ "has_homed": pa.array([r["has_homed"] for r in rows], type=pa.bool_()),
191
+ }, schema=schema)
192
+ pq.write_table(table, out, compression="zstd")
193
+ print(f" position_hf: {len(rows):,} rows, {bad} bad lines → {out.name}")
194
+
195
+
196
+ def append_frames_jsonl():
197
+ path = SPOOL_DIR / "frames.ndjson"
198
+ out = EXPORTS_DIR / "frames.jsonl"
199
+
200
+ # Idempotency: skip if already appended.
201
+ if out.exists():
202
+ with out.open(encoding="utf-8") as f:
203
+ for line in f:
204
+ try:
205
+ r = json.loads(line)
206
+ if r.get("build_id") == BUILD_ID:
207
+ print(f" frames.jsonl: build {BUILD_ID} already present, skipping")
208
+ return
209
+ except Exception:
210
+ pass
211
+
212
+ # Determine the highest existing frame id so we can assign new ones.
213
+ max_id = 0
214
+ if out.exists():
215
+ with out.open(encoding="utf-8") as f:
216
+ for line in f:
217
+ try:
218
+ r = json.loads(line)
219
+ max_id = max(max_id, int(r.get("id", 0)))
220
+ except Exception:
221
+ pass
222
+
223
+ rows: list[dict] = []
224
+ bad = 0
225
+ with path.open(encoding="utf-8") as f:
226
+ for line in f:
227
+ line = line.strip()
228
+ if not line:
229
+ continue
230
+ try:
231
+ rec = json.loads(line)
232
+ rows.append({
233
+ "id": max_id + len(rows) + 1,
234
+ "build_id": BUILD_ID,
235
+ "ts": rec["respondedAt"],
236
+ "kind": rec["kind"],
237
+ "path": rec["path"],
238
+ })
239
+ except Exception:
240
+ bad += 1
241
+
242
+ with out.open("a", encoding="utf-8") as f:
243
+ for r in rows:
244
+ f.write(json.dumps(r) + "\n")
245
+ print(f" frames.jsonl: appended {len(rows):,} rows, {bad} bad lines")
246
+
247
+
248
+ def append_builds_jsonl(started_at: str, ended_at: str):
249
+ out = EXPORTS_DIR / "builds.jsonl"
250
+
251
+ if out.exists():
252
+ with out.open(encoding="utf-8") as f:
253
+ for line in f:
254
+ try:
255
+ r = json.loads(line)
256
+ if r.get("id") == BUILD_ID:
257
+ print(f" builds.jsonl: build {BUILD_ID} already present, skipping")
258
+ return
259
+ except Exception:
260
+ pass
261
+
262
+ row = {
263
+ "id": BUILD_ID,
264
+ "job_name": JOB_NAME,
265
+ "started_at": started_at,
266
+ "ended_at": ended_at,
267
+ "phase": "recovered",
268
+ "params": {"notes": "recovered from NVMe spool after DB reset"},
269
+ "notes": "spool-only recovery; job_name is a placeholder",
270
+ }
271
+ with out.open("a", encoding="utf-8") as f:
272
+ f.write(json.dumps(row) + "\n")
273
+ print(f" builds.jsonl: appended build {BUILD_ID}")
274
+
275
+
276
+ def append_events_jsonl(started_at: str):
277
+ """Add a build_start event so load_build_to_profile_name() can find
278
+ this build. Profile name is unknown; leave null."""
279
+ out = EXPORTS_DIR / "events.jsonl"
280
+
281
+ if out.exists():
282
+ with out.open(encoding="utf-8") as f:
283
+ for line in f:
284
+ try:
285
+ r = json.loads(line)
286
+ if r.get("build_id") == BUILD_ID and r.get("kind") == "build_start":
287
+ print(f" events.jsonl: build_start for {BUILD_ID} already present, skipping")
288
+ return
289
+ except Exception:
290
+ pass
291
+
292
+ row = {
293
+ "id": -41,
294
+ "build_id": BUILD_ID,
295
+ "ts": started_at,
296
+ "kind": "build_start",
297
+ "message": JOB_NAME,
298
+ "payload": {"printProfileName": None, "notes": "recovered from spool"},
299
+ }
300
+ with out.open("a", encoding="utf-8") as f:
301
+ f.write(json.dumps(row) + "\n")
302
+ print(f" events.jsonl: appended build_start for build {BUILD_ID}")
303
+
304
+
305
+ def main():
306
+ if not SPOOL_DIR.exists():
307
+ print(f"Spool dir not found: {SPOOL_DIR}")
308
+ sys.exit(1)
309
+
310
+ print(f"Recovering build {BUILD_ID} from spool: {SPOOL_DIR}")
311
+ started_at, ended_at = build_telemetry_parquet()
312
+ build_position_parquet()
313
+ append_frames_jsonl()
314
+ append_builds_jsonl(started_at, ended_at)
315
+ append_events_jsonl(started_at)
316
+ print("Done. Run: uv run scripts/ticks/01_extract.py 41")
317
+
318
+
319
+ if __name__ == "__main__":
320
+ main()