Merge branch hand-recorder (the hand dataset recorder) into experimental

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DeeJanuzandClaude Opus 5.5 committed 2026-10-03 14:35:37 -06:00
commit 8b1327fe1a
80 files changed
+15397 -70

No files matched your search

+11 -3
View File
@@ -1,6 +1,7 @@
# Hand tracking, built into build/ (hands/build.sh runs this in the dev container):
# make ft-camd (camd/: runs on the host, so linked statically) and ft-hands (track/)
# make tools ft-handreplay and ft-ringplay, for recordings
# make check builds and runs the C++ unit tests (tests/sides_test.cpp)
# The first build fetches ncnn (NCNN_TAG) and builds it into build/ncnn, which takes a few
# minutes. NCNN=DIR uses an ncnn install already built instead.
NCNN_TAG = 20260526
@@ -11,7 +12,7 @@ CXXFLAGS += -std=c++17 -fopenmp -I$(NCNN)/include/ncnn
LDLIBS = $(NCNN)/lib/libncnn.a -ljsoncpp -fopenmp -lpthread
CAMD = camd/camd.c camd/tp.c camd/xrcams.c
TRACK = track/calib.cpp track/nets.cpp track/tracker.cpp track/io.cpp track/record.cpp track/pinch.cpp
TRACK = track/calib.cpp track/nets.cpp track/tracker.cpp track/io.cpp track/record.cpp track/pinch.cpp track/sides.cpp
HDR = $(wildcard track/*.h) camd/fhring.h include/fh_hands.h include/fh_gestures.h
all: build/ft-camd build/ft-hands
@@ -29,6 +30,13 @@ build/ft-handreplay: track/replay.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ track/replay.cpp $(TRACK) $(LDLIBS)
build/sides-test: tests/sides_test.cpp $(TRACK) $(HDR) $(NCNN)/lib/libncnn.a
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ tests/sides_test.cpp $(TRACK) $(LDLIBS)
check: build/sides-test
build/sides-test
build/ft-ringplay: track/ringplay.cpp track/record.h camd/fhring.h
@mkdir -p build
$(CXX) $(CXXFLAGS) -o $@ track/ringplay.cpp
@@ -44,6 +52,6 @@ build/ncnn/install/lib/libncnn.a:
cmake --build build/ncnn/build --target install > build/ncnn/build.log
clean:
rm -f build/ft-camd build/ft-hands build/ft-handreplay build/ft-ringplay
rm -f build/ft-camd build/ft-hands build/ft-handreplay build/ft-ringplay build/sides-test
.PHONY: all tools clean
.PHONY: all tools check clean
+57 -6
View File
@@ -36,7 +36,7 @@ hands/run.sh uninstall
Settings in `~/.config/frametop.conf` (`FT_<name>` in the environment overrides them), read when ft-camd and ft-hands start:
- `HANDS_SWAP_SIDES=1`: the two side cameras' names are swapped (see ft-camd below). Check with `tools/check_sides.py --ring`.
- `HANDS_SWAP_SIDES=auto` (the default): ft-hands tells from the hands which side camera is which, and corrects ft-camd's names when they're backwards (see "Which camera is which" below). `1` forces them exchanged and `0` forces ft-camd's names; ft-hands still checks and logs a warning if the hands disagree.
- `HANDS_CPUS=5,6,7`: the CPUs the model threads run on (below).
- `HANDS_CAMERAS` (`auto`), `HANDS_BRIGHT` (`all`), `HANDS_BRIGHT_ON` (40), `HANDS_BRIGHT_OFF` (25): which cameras ft-hands tracks with, as `--cams`, `--bright`, `--bright-on` and `--bright-off` (see ft-hands). `HANDS_CAMERAS=mono` also keeps ft-camd off the colour cameras.
- `HANDS_COLOR_LEFT` (`color_video0`), `HANDS_COLOR_CROP` (`subtract`): how the colour module's calibration maps onto its images, as `--color-left` and `--color-crop`.
@@ -86,7 +86,14 @@ Options:
It exits when XRService exits, or when a camera's buffers keep going stale, which means XRService has reallocated them. The service starts it again, and it attaches to the new buffers.
**Which camera is which:** video9 is `slam_left`, video13 is `slam_right`, video6 is `upper_left` and video7 is `upper_right`. This was checked by rendering the same view from each camera with the factory calibration. But ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and after some XRService restarts it gets them backwards. Then every hand is seen by one camera only, at the wrong depth, and the hand holes land beside the hands. With the headset on, looking at a room with some texture, `tools/check_sides.py --ring` says whether the names are right (exit 0), swapped (exit 3), or it can't tell (exit 2). When they're swapped, set `HANDS_SWAP_SIDES=1`. The colour cameras are video3 (`arcimx616 0-0010`) and video0 (`0-001a`); which of them is `passthrough_left` in the module's calibration is for `tools/check_color.py` to settle, on a recording with texture in view.
**Which camera is which:** video9 is `slam_left`, video13 is `slam_right`, video6 is `upper_left` and video7 is `upper_right`. This was checked by rendering the same view from each camera with the factory calibration. But ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and after some XRService restarts it gets them backwards. Then every hand is seen by one camera only, at the wrong depth, and the hand holes land beside the hands. ft-hands now catches this by itself (`track/sides.h`, `HANDS_SWAP_SIDES=auto`):
- Whenever a hand's landmarks are found in two cameras at once (one of them a side camera), it intersects the rays through the 21 landmarks twice: once with the calibrations as named, once with the two side cameras exchanged. The same hand seen the right way meets within a few mm, in front of both cameras and as far away as its size says. The wrong way misses by centimetres or meets behind a camera.
- With the names wrong, the tracker never gets such pairs on its own: it hands the hand over to where the wrong calibration puts it and finds nothing there. So 5 times a second while undecided, the check places a tracked hand in 3D under the other naming and runs the landmark model where that puts it in the other side camera.
- It decides after 10 votes one way and none the other, or 20 with at most a fifth the other way, over at least 1 s. That takes about 1-2 s of hands in view. If the names are backwards, it exchanges them; the tracked views move with their images. Then it checks once more, more strictly.
- The log says what it found (`side cameras: SWAPPED, now exchanged after 3.2 s (votes ...)`). So does `/run/user/UID/frametop-hands/sides.json`, which the hand recorder reads. Recordings get a `DIR/sides.json` (hands/rec/sides.py has the rules).
- `--record-only` can't tell (it tracks nothing): it records ft-camd's names unless `--sides 0|1` says otherwise.
`tools/check_sides.py --ring` is the independent check from the scene (ORB matches meeting under each naming): exit 0 as named, 3 swapped, 2 can't tell. `--pair upper` checks the upper pair the same way: in every recording so far (3 XRService starts, both side namings) the upper pair was named right. The colour cameras are video3 (`arcimx616 0-0010`) and video0 (`0-001a`); which of them is `passthrough_left` in the module's calibration is for `tools/check_color.py` to settle, on a recording with texture in view.
## ft-hands
@@ -102,14 +109,14 @@ Options:
- `--threads N`: model threads, pinned to the `--cpus` list. Default 3.
- `--cpus LIST`: CPUs for the model threads and the main loop. Default `5,6,7` (`HANDS_CPUS`). SteamOS starts user processes on CPUs 0-4, and XRService's head tracking runs on 2-3. With the headset on, a step took 8.4 ms on 5-7 against 13.2 ms on 2-4, and SteamVR's frame timing didn't change (2026-09-29, three rounds of the same replayed frames).
- `--contrast MODE` or `PALM/HAND`: how crops are equalized before the models see them: `clahe[:CLIP]`, `none`, or `stretch` (1st-99th percentile). Default `clahe:2/none`. In the dim recording, CLAHE let the palm search find about 10% more hands, but it made the landmarks jitter more (published median 6.9 mm, against 6.0 mm with plain landmark crops).
- `--swap-sides`: swap the two side cameras (`HANDS_SWAP_SIDES`, see ft-camd).
- `--sides auto|0|1`: which side camera is which (`HANDS_SWAP_SIDES`, see "Which camera is which"); `--swap-sides` is `--sides 1`.
- `--seconds N`: stop after N seconds.
- `--status S`: how often to print status, in seconds.
- `--models DIR`: where the models are.
- `--nice N`: niceness. Default 5, so the VR stack wins contested CPUs.
- `--no-publish`: don't write the hands and gestures files.
- `--no-gestures`: hands for the cutouts only. No pinch or grip detection, so nothing reaches the pointer and a closing hand doesn't raise the rate to 30 Hz. The gestures file is removed at start. `ft-cutouts` runs it this way.
- `--record DIR`, `--record-for S`: save every frame set for S seconds (default 120) to `DIR/sets.bin`. That's about 80 MB/s. Sending the tracker SIGUSR1 (`pkill -USR1 -x ft-hands`) starts a recording in `~/.local/share/frametop/hands/rec-<time>` without a restart. Recordings are images of your hands and room: they stay on the headset unless you move them.
- `--record DIR`, `--record-for S`, `--record-hz N`: save every frame set for S seconds (default 120) to `DIR/sets.bin`, or at most N sets a second with `--record-hz` (the hand recorder uses 10). Every set is about 80 MB/s. Sending the tracker SIGUSR1 (`pkill -USR1 -x ft-hands`) starts a recording in `~/.local/share/frametop/hands/rec-<time>` without a restart. Recordings are images of your hands and room: they stay on the headset unless you move them.
- `--record-only`: record without tracking or publishing, so it can run beside the live tracker. Give it `--record DIR`, since SIGUSR1 would reach both trackers. With `ft-camd --with-dark`, recordings also hold each camera's newest dark frame as `<name>_dk`, which doubles the rate. With `--with-color`, each colour camera's newest frame is saved with every set, as `color_video<N>`, which adds about 70 MB/s. Run the recorder at normal I/O priority: idle I/O priority stalled a 165 MB/s recording.
- `--keep-presence P`: the landmark presence a tracked view needs to stay tracked. New views always need 0.5. Default 0.5. Lowering it to 0.2 barely helped in the bright recording, because lost hands drop to near-zero presence.
- `--ring PATH`: read frames from another ring, such as `ft-ringplay`'s.
@@ -197,7 +204,7 @@ hands/build/ft-handreplay ~/.local/share/frametop/hands/rec-20260929-120000 --co
Python, with NumPy and OpenCV. `setup/dev-container.sh` doesn't install them, because Fedora's `python3-opencv` pulls in over a gigabyte; in the dev container, run `sudo dnf install python3-numpy python3-opencv` once. Off the Frame, `FRAME_JOB_DEVICE_ROOT` can point at a folder with copies of the headset's calibration files.
- `tools/check_sides.py --ring` (or a recording): are the side cameras named right?
- `tools/check_sides.py --ring` (or a recording, a sets file, `--pair upper`, `--calib DIR`, `--json`): are the side cameras named right, from the scene? ft-handreplay's `--sides file|0|1|auto` replays with DIR/sides.json's names (the default), as recorded, exchanged, or as auto decides, and reports what the side check found and when.
- `tools/check_color.py REC`: how the colour module's calibration maps onto its images.
- `tools/show_set.py REC`: a recording's frame sets as images.
- `tools/watch_gestures.py [--distance]`: pinches and grips, live.
@@ -207,15 +214,59 @@ Python, with NumPy and OpenCV. `setup/dev-container.sh` doesn't install them, be
To try the hand cutouts without restarting the desktop, `screens/build/ft-handtest [--distance m] [--width m] [--seconds s]` (built by `screens/build.sh`, run in the dev container, with hand tracking on) shows a test panel of its own, a light grid 1 m wide and 0.8 m ahead by default, and cuts your hands out of it the way ft-screens cuts them out of the screens.
## Camera check
Hand tracking needs all four mono cameras and the headset's IR light. With the Arcturus colour module attached, SteamVR's XRService loads an FPGA image ("VCINT") onto the module every time it opens the cameras: when SteamVR starts and after every wake. When that load fails, XRService runs only the two side cameras, the frames come out darker and noisier, and ft-hands finds no hands at all. It happened on 2026-10-02 at 17:02, after the headset slept; the hand recorder then said "I can't see your hands" for a whole session.
`hands/camcheck.py` (system Python, standard library) tells whether the four cameras run: `ok`, `degraded: upper cameras and IR light off (VCINT FPGA failed to load)` (or another `degraded:` reason), or `unknown` (SteamVR not running, the cameras closed while the headset sleeps). It prints the log lines and other evidence it used; `--json` is for programs; the exit status is 0, 1 or 2. It reads:
- the running XRService's log (`~/.local/share/Steam/logs/xrservice.txt`): the last camera start (from the FPGA check to the next "Closing tracking camera interfaces"), its VCINT result, `Upper cameras FPGA interleaving support: N`, `Created N tasks (T tracking, P passthrough)` and the `TrackingCameraInit` lines. A wake that works prints no "Created N tasks", so an older one doesn't count;
- which `/dev/video*` XRService has open (`/proc/PID/fd`; video9 and video13 are the side pair, video6 and video7 the upper pair). Only on the host: the dev container can't read another process's open files, so there it's skipped;
- ft-camd's ring header, when it runs: how many mono cameras it publishes.
The hand recorder runs it before a session (DESIGN.md, "Camera check"). `hands/tests/test_camcheck.py` runs it on the 2026-10-02 log cut at several points, and on made-up logs.
### The watcher (off by default)
`hands/ft-camwatch` follows the XRService log (a stat every 2 s, reading only what's new). On a VCINT failure it posts a notification in the Frametop desktop, on the desktop's own D-Bus, found through its plasmashell as `decoration/apply.sh` does. With `CAMWATCH_AUTO_RESTART=1` in `~/.config/frametop.conf` it also restarts SteamVR, but only:
- while the headset isn't worn (frame-job's check: `vrcompositor` runs and a `/sys/class/backlight/*/brightness` is over 0), and after it has been off for `CAMWATCH_IDLE_S` (60);
- with no app Steam launched (`SteamLaunch AppId=N` in a process's arguments; `CAMWATCH_IGNORE_APPIDS` lists ids that don't count) and nobody on the remote desktop (an established connection to the VNC port, `VNC_PORT`, 5900);
- once per failure, and not again within `CAMWATCH_COOLDOWN_MIN` (30) of the last automatic restart. It remembers both in `~/.local/state/frametop/camwatch.json`, so its own restart doesn't reset them.
It logs every decision to the journal. `ft-camwatch --once` prints the state and what it would do, and does nothing; `--dry-run` keeps watching without acting. `hands/frametop-camwatch.service` is the unit (a template, `@REPO@` as in the others; nothing installs or enables it yet). It isn't `PartOf=steamvr.service`, so it outlives the restart it asks for. `CAMWATCH_NOTIFY=0` turns the notification off. `hands/tests/test_camwatch.py` tests its decisions with made-up inputs.
### What a SteamVR restart does to Frametop
Read from the code on the experimental branch, not tried live:
- ft-screens quits when SteamVR does: on `VREvent_Quit` it ends its Wayland display (`screens/vr.cpp`, `ft_vr_poll`; `screens/compositor.c`, `handle_vr_event`). It never connects to SteamVR again: `ft_vr_init` runs once, at its start.
- KWin runs nested in ft-screens, so the Frametop desktop ends with it, every window in it too (the hand recorder's as well). Its unit, `frametop-desktop`, is a transient `systemd-run` unit with `Restart=no`, so the desktop doesn't come back by itself: start it again (Desktop in the library, or `desktops.sh start`).
- When the unit stops, systemd ends what's left in it. `session/keep-apps.sh` moves programs started in the desktop out of the unit first, but only `desktops.sh stop` runs it; here they stop too. Programs in the dev container (ft-screens, the hand recorder) are in the container's cgroup and end when their Wayland connection goes.
- The units that are `PartOf=steamvr.service` restart with it: `frametop-camd`, `frametop-hands`, the pointer helper, gaze and power, and the hand recorder's own transient ft-camd and ft-hands units.
### Verified, and what's a guess
Verified, from the XRService logs of 2026-10-01 and 2026-10-02 and the running system:
- The failure's log lines and its effect: "Failed to load VCINT FPGA image when passthrough cameras are connected", interleaving support 0, "Created 4 tasks (2 tracking, 2 passthrough)", and only video9 and video13 opened. At 19:38-19:59 XRService held only those two of the four (plus video0 and video3), and ft-camd published two mono cameras.
- A wake's load can work and can fail. Both wakes in the logs started from an FPGA that answered nothing ("ERROR/UNKNOWN"): the one at 2026-10-01 16:39 loaded VCINT, the one at 2026-10-02 17:02 failed ("FPGA config_done signal did not assert").
- After a reboot the FPGA reads PASSTHRU and SteamVR's start loads VCINT (2026-10-01 21:53, 2026-10-02 13:39).
- A SteamVR restart within a boot found VCINT still loaded and loaded nothing (2026-10-01 15:27): XRService checks the FPGA when it starts and loads only when it must.
Guesses, not tested:
- **Whether a SteamVR restart fixes it.** After a failed load the FPGA doesn't answer, so a new XRService would run the same load a wake runs, which has worked once and failed once. It's never been tried after a failure. If it doesn't help, only a reboot is known to work (the FPGA comes up as PASSTHRU, and the load at SteamVR's start has worked both times).
- That the IR light is off because of the FPGA: the frames are darker and the illuminator ring isn't seen, and the FPGA loader lists a `room_led_en` pin, but nothing shows the light's state directly.
- That a sleep and wake (taking the headset off long enough) would retry the load too: it should, since every wake loads VCINT, but no failure has been followed by a wake yet.
- How the Frametop desktop behaves on a SteamVR restart (above): read from the code only.
- That Steam-launched apps carry `SteamLaunch AppId=N`: from Steam on other Linux systems; no VR game has run on the Frame to confirm it.
## Build
`hands/build.sh` builds in the dev container on the Frame, into `hands/build/`, with `hands/Makefile`. The first build fetches ncnn at a pinned tag (`NCNN_TAG` in the Makefile) and builds it into `hands/build/ncnn`, which takes a few minutes; `NCNN=DIR` points at an ncnn install already built instead. ft-camd is linked statically, because it runs on the host, which has an older glibc than the container.
## Known issues
- **The side cameras can come out swapped.** ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and some XRService restarts reverse it. For now it's caught by hand: `tools/check_sides.py --ring`, then `HANDS_SWAP_SIDES=1`. It needs a fix in ft-camd, or at least an automatic check when it starts.
- **The side cameras can come out swapped.** ft-camd tells the side cameras' buffers apart only by XRService's allocation order, and some XRService restarts reverse it. ft-hands corrects it from the hands (`HANDS_SWAP_SIDES=auto`, the default). Until it has seen about 1-2 s of hands in both namings' reach, the cutouts may sit beside the hands. ft-camd itself still can't tell.
- **The colour cameras can't be used while the headset is worn.** The colour module then writes only a half-size image into the top-left quarter of its buffers, and ft-camd drops those frames. So the service runs the mono cameras only, and tracking in bright light, where the mono cameras see dark hands, doesn't get the colour pair's help.
- **The colour calibration mapping isn't settled.** Which colour camera is `passthrough_left` (`HANDS_COLOR_LEFT`) and how the module's crop applies (`HANDS_COLOR_CROP`) still need `tools/check_color.py` on a recording with a lit, textured view.
- **Depth when one camera loses the hand.** A hand seen in one camera drifts 10% per update toward the one-camera depth guess (`kMonoDepthGain`, 0.1, in `track/tracker.cpp`). In the 2026-09-30 replays that was worse than keeping the last distance (see "3D" above). A smaller gain, such as 0.02, is the next thing to try.
- **Pinches aren't reliable enough for everyday use yet.** That's why hand tracking stays off until `ft-handsctl on`, and `POINTER_HANDS` is 0 by default.
- **SteamVR can leave the upper cameras and the IR light off after a wake**, and then no hands are found. See "Camera check" above: `camcheck.py` tells, the hand recorder won't start a session, and the fix is a SteamVR restart or a reboot.
- **Floating windows don't get hand cutouts.** Their panels show crops of the client buffer, which the cutouts' side-by-side buffer doesn't match (`screens/vr.cpp`, `UpdateCutouts`).
+422
View File
@@ -0,0 +1,422 @@
#!/usr/bin/env python3
"""camcheck: are the headset's four mono tracking cameras running, so that ft-camd and
ft-hands see them all?
The Frame has four mono IR tracking cameras: the side pair slam_left and slam_right
(/dev/video9 and /dev/video13) and the upper pair (/dev/video6 and /dev/video7). With the
Arcturus colour module attached, SteamVR's XRService loads an FPGA image ("VCINT") onto the
module whenever it opens the cameras (at start and after every wake). When that load fails
(seen 2026-10-02 17:02, after a sleep), XRService runs only the two side cameras, the IR
illuminator seems to stay off, and ft-hands finds no hands at all.
What it looks at, cheapest first, all read-only:
1. The newest XRService log (~/.local/share/Steam/logs/xrservice.txt, a symlink to the
running instance's log): the last camera start, its VCINT result, "Upper cameras FPGA
interleaving support: N", "Created N tasks (T tracking, P passthrough)" and the
TrackingCameraInit lines. A wake doesn't always print "Created N tasks", so the parser
tracks each camera start ("episode") from the FPGA check to the next close.
2. Which /dev/video* XRService has open (/proc/PID/fd). Only on the host: the dev container
can't read another process's fd table (checked 2026-10-02), and then this is skipped.
3. A running ft-camd's ring header (/run/user/UID/frametop-hands/cam-ring): how many mono
cameras it publishes.
Status: "ok", "degraded: <why>" or "unknown" (SteamVR not running, the cameras closed while
the headset sleeps, no log). Exit status 0, 1, 2 for those.
python3 hands/camcheck.py # the status and its evidence
python3 hands/camcheck.py --json # for programs
python3 hands/camcheck.py --log FILE --no-proc --no-ring # a saved log only (tests)
System Python, standard library only; session.py and ft-camwatch import it.
"""
import argparse
import glob
import json
import os
import re
import struct
import sys
import time
LOG_DIR = os.path.expanduser("~/.local/share/Steam/logs")
LOG_LINK = os.path.join(LOG_DIR, "xrservice.txt")
SIDE_NODES = (9, 13) # slam_left, slam_right (TrackingCameraInit index 0 and 1)
UPPER_NODES = (6, 7) # the upper pair (index 2 and 3)
TRACKING = 4
VCINT_REASON = "upper cameras and IR light off (VCINT FPGA failed to load)"
DEGRADED_VCINT = "degraded: " + VCINT_REASON
# What the window and the recorder say when the check fails this way.
USER_TEXT = ("The headset's upper cameras and IR light are off. SteamVR couldn't start the colour camera "
"module (it happens sometimes after the headset sleeps). Restart SteamVR, or restart the headset "
"if that doesn't fix it.")
ANSI = re.compile(r"\x1b\[[0-9;]*m")
STAMP = re.compile(r"^\w{3} \w{3} \d{2} \d{4} (\d{2}:\d{2}:\d{2})\.\d+ (\w+): ?(.*)$")
# Lines worth reading; anything else is skipped before the regexes (the log grows by MBs a day).
KEYS = ("FPGA", "VCINT", "Created", "TrackingCameraInit", "Closing tracking camera", "Streaming",
"systemd suspend", "systemd resume", "XRService logging to", "Exiting XRService")
RE_PASSTHRU = re.compile(r"Passthrough connected but FPGA is (\S+) - loading VCINT")
RE_INTERLEAVE = re.compile(r"Upper cameras FPGA interleaving support: (\d)")
RE_TASKS = re.compile(r"Created (\d+) tasks \((\d+) tracking, (\d+) passthrough\)")
RE_INIT = re.compile(r"TrackingCameraInit: index: (\d+)\. video device: /dev/video(\d+)")
RE_STREAM = re.compile(r"Streaming resumed \(FPGA: (\S+), VC interleaving: (\w+)\)")
RE_STATE = re.compile(r"FPGA state check: (\S+)")
class LogState:
"""Reads an XRService log line by line (feed), so the watcher can follow it as it grows.
An episode is one opening of the cameras: from the first FPGA, task or camera-init line
after the log starts or after "Closing tracking camera interfaces", to the next close."""
def __init__(self, path=""):
self.path = path
self.instance = "" # the "XRService logging to" line's time
self.exited = False
self.closed = False # the cameras were closed and haven't opened again
self.closed_at = ""
self.episode = None
self.nodes = {} # TrackingCameraInit index -> /dev/videoN, from the whole log
self.failures = [] # [(time, line)]: every VCINT failure in this log
self.lines = 0
def _new_episode(self, t):
self.closed = False
self.episode = {"start": t, "fpga_before": "", "vcint": "", "interleave": None, "tasks": None,
"inits": {}, "stream": "", "failure": "", "evidence": []}
if self.closed_at:
self.episode["evidence"].append(self.closed_at)
def _ep(self, t):
if self.episode is None or self.closed:
self._new_episode(t)
return self.episode
def feed(self, raw):
self.lines += 1
if not any(k in raw for k in KEYS):
return
line = ANSI.sub("", raw).rstrip("\n")
m = STAMP.match(line)
if not m:
return # the FPGA loader's own output, without a time
t, _level, text = m.groups()
short = ("%s %s" % (t, text))[:220]
if "XRService logging to" in text:
lines = self.lines
self.__init__(self.path)
self.instance, self.lines = t, lines
return
if "Exiting XRService" in text:
self.exited = True
return
if "Closing tracking camera interfaces" in text:
self.closed, self.closed_at = True, short
return
if "systemd suspend notification" in text or "systemd resume notification" in text:
if "resume" in text:
self.closed_at = (self.closed_at + " / " if self.closed_at else "") + short
return
m = RE_PASSTHRU.search(text)
if m:
ep = self._ep(t)
ep["fpga_before"] = m.group(1)
ep["evidence"].append(short)
return
if "FPGA image VCINT loaded and verified successfully" in text:
ep = self._ep(t)
ep["vcint"] = "ok"
ep["evidence"].append(short)
return
if "Failed to load VCINT FPGA image" in text:
ep = self._ep(t)
ep["vcint"] = "failed"
ep["failure"] = t
ep["evidence"].append(short)
self.failures.append((t, short))
return
if "FPGA load failed" in text:
self._ep(t)["evidence"].append(short)
return
m = RE_INTERLEAVE.search(text)
if m:
ep = self._ep(t)
ep["interleave"] = int(m.group(1))
ep["evidence"].append(short)
return
m = RE_TASKS.search(text)
if m:
ep = self._ep(t)
ep["tasks"] = tuple(int(v) for v in m.groups())
ep["evidence"].append(short)
return
m = RE_INIT.search(text)
if m:
ep = self._ep(t)
idx, node = int(m.group(1)), int(m.group(2))
ep["inits"][idx] = node
self.nodes[idx] = node
ep["evidence"].append(short)
return
m = RE_STREAM.search(text)
if m:
ep = self._ep(t)
ep["stream"] = "%s, interleaving %s" % m.groups()
ep["evidence"].append(short)
return
m = RE_STATE.search(text)
if m:
ep = self._ep(t)
if not ep["fpga_before"] and not ep["vcint"]:
ep["fpga_before"] = m.group(1)
if m.group(1) == "VCINT":
ep["vcint"] = "loaded" # already there: no load needed (a SteamVR restart in the same boot)
ep["evidence"].append(short)
def feed_text(self, text):
for line in text.splitlines():
self.feed(line)
return self
def upper_nodes(self):
got = tuple(self.nodes[i] for i in (2, 3) if i in self.nodes)
return got if len(got) == 2 else UPPER_NODES
def tracking_nodes(self):
got = tuple(self.nodes[i] for i in range(TRACKING) if i in self.nodes)
return got if len(got) == TRACKING else SIDE_NODES + UPPER_NODES
def verdict(self):
"""(status, reason, evidence): status "ok", "degraded" or "unknown"."""
if self.lines == 0:
return "unknown", "the XRService log is empty", []
if self.exited:
return "unknown", "XRService has exited (SteamVR isn't running)", []
if self.episode is None:
return "unknown", "the cameras haven't started yet in this log", []
ep = self.episode
ev = ep["evidence"][-14:]
if self.closed:
return "unknown", "the cameras are closed (the headset is asleep, or SteamVR is stopping)", \
ev + [self.closed_at]
tracking = len(ep["inits"]) if ep["inits"] else (ep["tasks"][1] if ep["tasks"] else None)
if ep["vcint"] == "failed":
return "degraded", VCINT_REASON, ev
if tracking is not None and tracking < TRACKING:
why = "only %d of %d tracking cameras running" % (tracking, TRACKING)
if ep["interleave"] == 0:
why += " (upper cameras' FPGA interleaving off)"
return "degraded", why, ev
if tracking == TRACKING:
return "ok", "%d tracking cameras running" % TRACKING, ev
return "unknown", "the cameras are starting", ev
def snapshot(self):
status, reason, ev = self.verdict()
ep = self.episode or {}
return {"status": status, "reason": reason, "evidence": ev, "log": self.path, "instance": self.instance,
"episode": {k: (list(v) if isinstance(v, tuple) else v) for k, v in ep.items() if k != "evidence"},
"failure": "%s@%s" % (self.path, ep["failure"]) if ep.get("vcint") == "failed" else ""}
# ------------------------------------------------------------------------------------------
# Processes
def proc_argv(pid):
try:
with open("/proc/%s/cmdline" % pid, "rb") as f:
return [a.decode(errors="replace") for a in f.read().split(b"\0") if a]
except OSError:
return []
def xrservice_pid():
"""XRService's pid (its main thread renames itself XRServiceLoopTh), or None."""
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/comm" % pid) as f:
if not f.read().startswith("XRService"):
continue
except OSError:
continue
argv = proc_argv(pid)
if argv and os.path.basename(argv[0]) == "XRService":
return int(pid)
return None
def xrservice_fds(pid):
"""{"videos": [N, ...], "log": path or ""} from /proc/PID/fd, or None if it can't be read
(the dev container can't)."""
try:
fds = os.listdir("/proc/%d/fd" % pid)
except OSError:
return None
videos, log = set(), ""
for fd in fds:
try:
target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
except OSError:
continue
m = re.match(r"/dev/video(\d+)$", target)
if m:
videos.add(int(m.group(1)))
elif re.search(r"/XRService-[^/]*\.log$", target):
log = target
if not videos and not log:
return None # nothing readable: as good as no access
return {"videos": sorted(videos), "log": log}
def newest_log():
"""The running XRService's log: the xrservice.txt symlink, else the newest by time."""
if os.path.exists(LOG_LINK):
return os.path.realpath(LOG_LINK)
found = glob.glob(os.path.join(LOG_DIR, "XRService-*", "XRService-*.log"))
found += glob.glob(os.path.join(LOG_DIR, "XRService-*.log"))
found = [p for p in found if os.path.isfile(p)]
return max(found, key=os.path.getmtime) if found else ""
def read_log(path):
st = LogState(path)
with open(path, "r", errors="replace") as f:
for line in f:
st.feed(line)
return st
# ------------------------------------------------------------------------------------------
# ft-camd's ring (camd/fhring.h; the header only, as session.py's Ring reads it)
RING_HDR = struct.Struct("<8sIIIIQqQ16x")
RING_CAM = struct.Struct("<32s32siIIIIIQQQQQIf24x")
FH_CAM_DARK, FH_CAM_COLOR = 1, 2
def default_ring():
return "/run/user/%d/frametop-hands/cam-ring" % os.getuid()
def read_ring(path):
"""{"alive", "writer_pid", "mono": [{"name", "sensor", "node"}]} or None (no ring)."""
try:
with open(path, "rb") as f:
data = f.read(RING_HDR.size + 8 * RING_CAM.size)
except OSError:
return None
if len(data) < RING_HDR.size:
return None
magic, version, _, ncams, _, _, writer, _ = RING_HDR.unpack_from(data, 0)
if magic != b"FHRING01" or version != 1:
return None
hb = struct.unpack_from("<Q", data, 40)[0]
alive = hb != 0 and (time.clock_gettime_ns(time.CLOCK_MONOTONIC) - hb) / 1e9 < 2.0
mono = []
for i in range(min(ncams, 8)):
off = RING_HDR.size + i * RING_CAM.size
if off + RING_CAM.size > len(data):
break
f = RING_CAM.unpack_from(data, off)
sensor = f[0].split(b"\0", 1)[0].decode(errors="replace")
name = f[1].split(b"\0", 1)[0].decode(errors="replace")
if f[13] & (FH_CAM_DARK | FH_CAM_COLOR) or name.endswith("_dk") or name.startswith("color"):
continue
mono.append({"name": name, "sensor": sensor, "node": f[2]})
return {"alive": alive, "writer_pid": writer, "mono": mono}
# ------------------------------------------------------------------------------------------
# The check
def check(log=None, proc=True, ring=True, ring_path=None):
"""The cameras' state: {"status": "ok"|"degraded"|"unknown", "summary": "ok" or
"degraded: ..." or "unknown: ...", "reason", "evidence": [lines], "log", "xrservice", "ring"}."""
evidence = []
pid = xrservice_pid() if proc else None
fds = xrservice_fds(pid) if pid else None
path = log or (fds or {}).get("log") or newest_log()
state = None
if path:
try:
state = read_log(path)
except OSError as e:
evidence.append("log %s: %s" % (path, e))
if state:
status, reason, ev = state.verdict()
evidence += ["log %s:" % path] + [" " + e for e in ev]
else:
status, reason = "unknown", "no XRService log in %s" % LOG_DIR
out = {"log": path, "xrservice": None, "ring": None,
"episode": state.snapshot()["episode"] if state else {},
"failure": state.snapshot()["failure"] if state else ""}
if proc:
if pid is None:
# The log can't tell a killed XRService from a running one; no process settles it.
evidence.append("XRService isn't running")
status, reason = "unknown", "SteamVR isn't running (no XRService)"
elif fds is None:
evidence.append("XRService pid %d: its open files can't be read here (in the dev container?)" % pid)
out["xrservice"] = {"pid": pid, "videos": None}
else:
videos = fds["videos"]
want = state.tracking_nodes() if state else SIDE_NODES + UPPER_NODES
upper = state.upper_nodes() if state else UPPER_NODES
have = [n for n in want if n in videos]
evidence.append("XRService pid %d has open: %s (tracking cameras: %s; upper: %s)" % (
pid, " ".join("video%d" % n for n in videos) or "no cameras",
" ".join("video%d" % n for n in want), " ".join("video%d" % n for n in upper)))
out["xrservice"] = {"pid": pid, "videos": videos, "tracking_open": len(have)}
closed = state is not None and state.closed
if not closed and len(have) == TRACKING and status == "unknown":
status, reason = "ok", "XRService has all %d tracking cameras open" % TRACKING
elif not closed and videos and not all(n in videos for n in upper) and status != "degraded":
status, reason = "degraded", ("XRService has %d of %d tracking cameras open (the upper pair "
"is missing)" % (len(have), TRACKING))
if ring:
r = read_ring(ring_path or default_ring())
out["ring"] = r
if r is None:
evidence.append("ft-camd: no camera ring (not running)")
else:
names = " ".join(c["name"] for c in r["mono"]) or "none"
evidence.append("ft-camd (pid %d, %s): %d mono cameras: %s" % (
r["writer_pid"], "running" if r["alive"] else "stale ring", len(r["mono"]), names))
if r["alive"] and len(r["mono"]) < TRACKING and status == "ok":
status, reason = "degraded", ("ft-camd publishes only %d of %d mono cameras (it started while "
"they were missing: restart it)" % (len(r["mono"]), TRACKING))
out.update(status=status, reason=reason, evidence=evidence,
summary="ok" if status == "ok" else "%s: %s" % (status, reason))
return out
def is_vcint_failure(result):
return bool(result) and result.get("status") == "degraded" and result.get("reason") == VCINT_REASON
def main(argv=None):
ap = argparse.ArgumentParser(description="Are the headset's four mono tracking cameras running?")
ap.add_argument("--json", action="store_true", help="print the result as JSON")
ap.add_argument("--log", help="read this XRService log (default: the running instance's)")
ap.add_argument("--no-proc", action="store_true", help="don't look at XRService's process")
ap.add_argument("--no-ring", action="store_true", help="don't look at ft-camd's ring")
ap.add_argument("--ring", help="ft-camd's ring (default /run/user/UID/frametop-hands/cam-ring)")
a = ap.parse_args(argv)
r = check(log=a.log, proc=not a.no_proc, ring=not a.no_ring, ring_path=a.ring)
if a.json:
print(json.dumps(r, indent=1))
else:
print(r["summary"])
for line in r["evidence"]:
print(" " + line)
return {"ok": 0, "degraded": 1}.get(r["status"], 2)
if __name__ == "__main__":
sys.exit(main())
+21
View File
@@ -0,0 +1,21 @@
# Template: the installer replaces @REPO@ with the repo path on the Frame. Not installed or
# enabled by anything yet (hands/README.md, "Camera check").
[Unit]
Description=Frametop camera watch: tells you when SteamVR leaves the headset's upper cameras off
Documentation=file://@REPO@/hands/README.md
# Not PartOf=steamvr.service: it has to outlive the SteamVR restart it may ask for.
[Service]
# On the host, system Python, standard library only. It stats the XRService log every 2 s and
# reads only what's new. Notifications go to the Frametop desktop's own D-Bus (found through its
# plasmashell). With CAMWATCH_AUTO_RESTART=1 in ~/.config/frametop.conf it may restart SteamVR
# while the headset isn't worn: that also closes the Frametop desktop.
ExecStart=/usr/bin/python3 @REPO@/hands/ft-camwatch
Restart=on-failure
RestartSec=30
Nice=10
CPUQuota=5%
MemoryMax=64M
[Install]
WantedBy=default.target
+378
View File
@@ -0,0 +1,378 @@
#!/usr/bin/env python3
"""ft-camwatch: watches SteamVR's XRService log for the camera failure that turns off the
headset's upper cameras and IR light (a VCINT FPGA load that fails, usually after a wake;
hands/camcheck.py), tells the Frametop desktop, and can restart SteamVR by itself.
Off by default: hands/frametop-camwatch.service is a template the installer doesn't enable.
Settings in ~/.config/frametop.conf:
CAMWATCH_AUTO_RESTART=1 restart SteamVR on a failure (default 0: only a notification). Only
while the headset isn't worn (frame-job's check: vrcompositor runs and
a backlight is on), after it has been off for CAMWATCH_IDLE_S, with no
Steam-launched app running and nobody on the remote desktop (VNC).
At most once per failure, and not again within CAMWATCH_COOLDOWN_MIN.
CAMWATCH_IDLE_S=60 how long the headset must be off first
CAMWATCH_COOLDOWN_MIN=30 the least time between two automatic restarts
CAMWATCH_IGNORE_APPIDS= Steam app ids that don't count as a running VR app (comma-separated)
CAMWATCH_NOTIFY=1 post a notification in the Frametop desktop (0: log only)
A SteamVR restart also closes the Frametop desktop and every window in it (ft-screens quits
with SteamVR, and the desktop's unit doesn't restart: see hands/README.md, "Camera check").
It follows the log with a stat every 2 s (no inotify, nothing else while all is well), and
logs every decision to stdout (the journal). --dry-run never notifies or restarts; --once
prints the state and what it would do now, and exits.
"""
import argparse
import json
import os
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import camcheck # noqa: E402
CONF = os.path.expanduser("~/.config/frametop.conf")
STATE = os.path.expanduser("~/.local/state/frametop/camwatch.json")
BACKLIGHTS = "/sys/class/backlight"
POLL_S = 2.0
MAX_READ = 16 << 20 # a poll reads at most this much of a log that grew
NOTIFY_TITLE = "Hand tracking: cameras off"
NOTIFY_TEXT = ("The headset's upper cameras and IR light are off: SteamVR couldn't start the colour camera "
"module (it happens sometimes after the headset sleeps). Restart SteamVR, or the headset if "
"that doesn't fix it. Restarting SteamVR closes this desktop and its windows.")
DEFAULTS = {"CAMWATCH_AUTO_RESTART": "0", "CAMWATCH_IDLE_S": "60", "CAMWATCH_COOLDOWN_MIN": "30",
"CAMWATCH_IGNORE_APPIDS": "", "CAMWATCH_NOTIFY": "1", "VNC_PORT": "5900"}
def log(text):
print("%s %s" % (time.strftime("%H:%M:%S"), text), flush=True)
def read_conf(path=CONF):
"""KEY=VALUE lines of a shell-style file (comments and quotes stripped), over DEFAULTS."""
conf = dict(DEFAULTS)
try:
with open(path) as f:
for line in f:
line = line.split("#", 1)[0].strip()
if "=" not in line:
continue
k, v = line.split("=", 1)
k, v = k.strip(), v.strip().strip("'\"")
if k.replace("_", "").isalnum():
conf[k] = v
except OSError:
pass
return conf
def conf_int(conf, key):
try:
return int(float(conf.get(key, DEFAULTS.get(key, "0"))))
except ValueError:
return int(DEFAULTS.get(key, "0") or 0)
# ------------------------------------------------------------------------------------------
# What's going on around (all read-only, from /proc and /sys)
def process_running(name):
for pid in os.listdir("/proc"):
if pid.isdigit():
try:
with open("/proc/%s/comm" % pid) as f:
if f.read().strip() == name:
return True
except OSError:
pass
return False
def headset_worn(backlights=BACKLIGHTS):
"""frame-job's check: vrcompositor runs and any panel's backlight is on (SteamVR turns the
panels off 5 s after the headset comes off)."""
lit = False
try:
for name in os.listdir(backlights):
try:
with open(os.path.join(backlights, name, "brightness")) as f:
lit = lit or int(f.read().strip()) > 0
except (OSError, ValueError):
pass
except OSError:
return False
return lit and process_running("vrcompositor")
def vr_apps(ignore=()):
"""Apps Steam launched ("SteamLaunch AppId=N" in a process's arguments, as Steam's reaper
runs them): ["AppId=N ..."]. Steam's own processes, SteamVR's and Frametop's services aren't
launched this way. A guess: no VR game has been run on the Frame to confirm the form."""
out = set()
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
argv = camcheck.proc_argv(pid)
if "SteamLaunch" not in argv:
continue
ids = [a.split("=", 1)[1] for a in argv if a.startswith("AppId=")]
if ids and ids[0] not in ignore:
out.add("AppId=" + ids[0])
return sorted(out)
def remote_viewers(port=5900, tables=("/proc/net/tcp", "/proc/net/tcp6")):
"""Established connections to the remote desktop's VNC port, from /proc/net/tcp(6)."""
out = []
for path in tables:
try:
with open(path) as f:
next(f)
for line in f:
p = line.split()
if len(p) > 3 and p[3] == "01" and int(p[1].rsplit(":", 1)[1], 16) == port:
out.append(p[2])
except (OSError, StopIteration, ValueError):
pass
return out
def frametop_bus():
"""The Frametop desktop's D-Bus (from its plasmashell, as decoration/apply.sh finds it), or None."""
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
with open("/proc/%s/comm" % pid) as f:
if f.read().strip() != "plasmashell":
continue
with open("/proc/%s/environ" % pid, "rb") as f:
env = dict(kv.split(b"=", 1) for kv in f.read().split(b"\0") if b"=" in kv)
except OSError:
continue
if env.get(b"XDG_RUNTIME_DIR", b"").endswith(b"/frametop") and b"DBUS_SESSION_BUS_ADDRESS" in env:
return env[b"DBUS_SESSION_BUS_ADDRESS"].decode()
return None
def notify(title, text):
bus = frametop_bus()
if not bus:
log("no Frametop desktop running: no notification")
return False
r = subprocess.run(["notify-send", "-a", "Frametop", "-u", "critical", "-i", "dialog-warning", title, text],
env=dict(os.environ, DBUS_SESSION_BUS_ADDRESS=bus), capture_output=True, text=True,
timeout=10)
if r.returncode:
log("notify-send failed (%d): %s" % (r.returncode, r.stderr.strip()))
return r.returncode == 0
def restart_steamvr():
# --no-block: the job runs in systemd; the Frametop desktop closing doesn't cut it short.
r = subprocess.run(["systemctl", "--user", "restart", "--no-block", "steamvr.service"],
capture_output=True, text=True, timeout=30)
log("systemctl --user restart steamvr.service: exit %d %s" % (r.returncode, (r.stderr or "").strip()))
return r.returncode == 0
def environment(conf):
ignore = tuple(a.strip() for a in conf.get("CAMWATCH_IGNORE_APPIDS", "").replace(",", " ").split() if a.strip())
return {"steamvr": camcheck.xrservice_pid() is not None, "worn": headset_worn(),
"vr_apps": vr_apps(ignore), "remote": remote_viewers(conf_int(conf, "VNC_PORT"))}
# ------------------------------------------------------------------------------------------
# The decision (pure: tests feed it made-up states)
def new_memory():
return {"pending": "", "notified": [], "restarted": {}, "last_restart": 0.0, "idle_since": None, "why": ""}
def decide(now, failure, env, mem, conf):
"""What to do now. failure: the current VCINT failure's id ("" if none: the cameras run,
or they're closed); env: {"steamvr", "worn", "vr_apps", "remote"} (only looked at while a
failure is current); mem: new_memory(), updated in place; now: wall-clock seconds.
Returns [("log", text) | ("notify", failure) | ("restart", failure)]."""
acts = []
if not failure:
if mem["pending"]:
acts.append(("log", "failure %s is no longer current" % mem["pending"]))
mem.update(pending="", idle_since=None, why="")
return acts
if mem["pending"] != failure:
mem.update(pending=failure, why="")
acts.append(("log", "VCINT failure: %s (upper cameras and IR light off)" % failure))
if failure not in mem["notified"]:
mem["notified"] = (mem["notified"] + [failure])[-20:]
if conf.get("CAMWATCH_NOTIFY", "1") != "0":
acts.append(("notify", failure))
if env.get("worn"):
mem["idle_since"] = None
elif mem["idle_since"] is None:
mem["idle_since"] = now
idle_s = conf_int(conf, "CAMWATCH_IDLE_S")
cooldown = conf_int(conf, "CAMWATCH_COOLDOWN_MIN") * 60
if conf.get("CAMWATCH_AUTO_RESTART", "0") != "1":
why = "no automatic restart (CAMWATCH_AUTO_RESTART=1 in ~/.config/frametop.conf turns it on)"
elif failure in mem["restarted"]:
why = "SteamVR was restarted once for this failure already: restart the headset"
elif mem["last_restart"] and now - mem["last_restart"] < cooldown:
why = "no restart: the last automatic one was %d min ago (cooldown %d min)" % (
(now - mem["last_restart"]) // 60, cooldown // 60)
elif not env.get("steamvr"):
why = "no restart: SteamVR isn't running"
elif env.get("worn"):
why = "no restart while the headset is worn"
elif env.get("vr_apps"):
why = "no restart: a VR app is running (%s)" % ", ".join(env["vr_apps"])
elif env.get("remote"):
why = "no restart: someone is on the remote desktop (%s)" % ", ".join(env["remote"])
elif now - mem["idle_since"] < idle_s:
why = "waiting for the headset to stay off for %d s" % idle_s
else:
mem["restarted"][failure] = now
mem["last_restart"] = now
why = "restarting SteamVR (the headset is off, nothing else in VR)"
acts.append(("log", why))
acts.append(("restart", failure))
mem["why"] = why
return acts
if why != mem["why"]:
mem["why"] = why
acts.append(("log", why))
return acts
def load_memory(path=STATE):
mem = new_memory()
try:
with open(path) as f:
saved = json.load(f)
mem["notified"] = list(saved.get("notified", []))[-20:]
mem["restarted"] = dict(saved.get("restarted", {}))
mem["last_restart"] = float(saved.get("last_restart", 0.0))
except (OSError, ValueError, TypeError, AttributeError):
pass
return mem
def save_memory(mem, path=STATE):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump({"notified": mem["notified"], "restarted": mem["restarted"],
"last_restart": mem["last_restart"]}, f)
os.replace(tmp, path)
# ------------------------------------------------------------------------------------------
# Following the log
class Follower:
"""The running XRService's log, read as it grows. A new log (SteamVR restarted) starts afresh."""
def __init__(self, path=None):
self.fixed = path
self.path, self.ino, self.offset, self.rest = "", None, 0, ""
self.state = None
def poll(self):
path = self.fixed or camcheck.newest_log()
if not path:
return None
try:
st = os.stat(path)
except OSError:
return self.state
if path != self.path or st.st_ino != self.ino or st.st_size < self.offset:
self.path, self.ino, self.offset, self.rest = path, st.st_ino, 0, ""
self.state = camcheck.LogState(path)
log("following %s" % path)
if st.st_size > self.offset:
with open(path, "rb") as f:
f.seek(self.offset)
data = f.read(MAX_READ)
self.offset += len(data)
text = self.rest + data.decode(errors="replace")
lines = text.split("\n")
self.rest = lines.pop()
for line in lines:
self.state.feed(line)
return self.state
def current_failure(state, steamvr_running=True):
"""The failure id if the log's current camera start is a VCINT failure, else ""."""
if state is None or not steamvr_running:
return ""
snap = state.snapshot()
return snap["failure"] if snap["status"] == "degraded" and snap["reason"] == camcheck.VCINT_REASON else ""
def act(acts, dry):
changed = False
for kind, arg in acts:
if kind == "log":
log(arg)
elif kind == "notify":
changed = True
if dry:
log("(dry run) would notify: %s" % NOTIFY_TITLE)
else:
notify(NOTIFY_TITLE, NOTIFY_TEXT)
elif kind == "restart":
changed = True
if dry:
log("(dry run) would restart SteamVR")
else:
restart_steamvr()
return changed
def main(argv=None):
ap = argparse.ArgumentParser(description="Watch for the camera failure that turns off the upper cameras.")
ap.add_argument("--dry-run", action="store_true", help="log what it would do; never notify or restart")
ap.add_argument("--once", action="store_true", help="look once, print the decision (a dry run), and exit")
ap.add_argument("--log", help="follow this file instead of the running XRService's log (tests)")
ap.add_argument("--state", default=STATE, help="where it remembers past failures (default %(default)s)")
a = ap.parse_args(argv)
dry = a.dry_run or a.once
mem = load_memory(a.state)
follower = Follower(a.log)
conf = read_conf()
conf_mtime = 0.0
log("watching; automatic restart %s" % ("on" if conf.get("CAMWATCH_AUTO_RESTART") == "1" else "off"))
while True:
try:
m = os.stat(CONF).st_mtime
except OSError:
m = 0.0
if m != conf_mtime:
conf, conf_mtime = read_conf(), m
state = follower.poll()
failure = current_failure(state)
env = {}
if failure or mem["pending"]:
env = environment(conf)
if not env["steamvr"] and not a.log:
failure = "" # the log's last word, but XRService is gone
acts = decide(time.time(), failure, env, mem, conf)
if a.once:
snap = state.snapshot() if state else {"status": "unknown", "reason": "no log"}
print("log: %s\nstate: %s %s\nenvironment: %s" % (follower.path, snap["status"], snap["reason"],
json.dumps(env)))
act(acts, True)
return 0
if act(acts, dry) and not dry:
save_memory(mem, a.state)
time.sleep(POLL_S)
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit(0)
+97
View File
@@ -0,0 +1,97 @@
# Recording your hands for the Frametop hand dataset
Version: 2026-10-03
Frametop's hand tracking needs a small model that finds hands in the headset's camera images. To train it, we're collecting recordings of many people's hands into a public dataset. This page explains what the hand recorder records, where it goes, and what you agree to if you take part. Please read all of it.
## Who runs this
Frametop is an independent open-source project, maintained by DeeJanuz (<https://github.com/DeeJanuz>). It isn't affiliated with or endorsed by Valve or Hugging Face. Steam and Steam Frame are trademarks of Valve Corporation. This text was written without a lawyer, in good faith; if something in it seems wrong or unclear, please say so before you take part.
You can reach the maintainer through the Frametop repository's issues (<https://github.com/DeeJanuz/frametop/issues>) or the dataset's discussion page on Hugging Face. Both are public.
## Who can take part
- You must be **18 or older**.
- For now, you can't take part if you live in **Illinois, Texas or Washington** (USA). Those states have laws about biometric data (such as hand geometry) that need more than this project can provide yet.
- Take part only if you're comfortable with images of your hands and the room in front of you being public.
## What is recorded
While a session runs, the hand recorder saves:
- **Camera images.** Infrared images from the headset's 4 tracking cameras, about 10 sets a second. They show your hands, your arms, your clothing and whatever is in front of you: your room, your desk and the things on it. They're grey, low-detail images, but people and things can be recognised in them. The size and shape of your hands can be measured from them: that's part of what they're for.
- **Motion.** The position and rotation of the headset, many times a second, and of the controllers when you use them in the recording.
- **Prompts.** What you were asked to do and when, and what the live hand tracker saw at the time.
- **Calibration.** Where the cameras sit on the headset and how their lenses bend the image. Serial numbers and other fields that identify your headset are removed first, and the export lists what was removed.
- **Your answers.** Which objects you had, the lighting, whether you wore sleeves, rings or a watch, your handedness if you gave it, and any notes you typed in the checklist or in Review. Notes are uploaded with the recordings and read by the maintainer: don't put anything in them that identifies you.
- **Times.** When each session was recorded, with your time zone.
- **A contributor id.** A random number made on your headset the first time you agree to this page. It isn't made from your name, your Steam account or your headset. It keeps your sessions together and lets you withdraw them.
The recorder doesn't record sound, your name, your email address or your Steam account. The tracking cameras look outward, so your eyes and face aren't recorded, unless a mirror or something shiny shows them: avoid those.
**Your Hugging Face account.** You upload with your own Hugging Face account, and your pull request shows its username next to your contributor id, publicly. So anyone can see which Hugging Face account contributed which recordings. Use an account you're happy to have linked to them.
## What it's used for
- Training and testing hand-tracking models: finding hands, their keypoints, their shape and how far away they are. Mainly for Frametop's hand cutouts, and by anyone else for non-commercial work under the dataset's license.
- It isn't used to recognise or identify people, and the dataset's terms forbid anyone from trying.
## Nothing leaves your headset unless you send it
- Recordings stay on your headset, in `~/.local/share/frametop/hands/contrib`. Nothing is uploaded automatically.
- Before you share anything, you can watch every recording in the Review page. You can delete any stretch of a recording, a whole take or a whole session. Export leaves out what you deleted.
- You upload the export yourself, from the Upload page. That opens a pull request on the dataset. The maintainer checks it before it becomes part of the dataset, and may decline it. Until it's merged, you can close the pull request yourself.
## Where it goes
- **The dataset is public.** It's hosted on Hugging Face (<https://huggingface.co/datasets/DeeJanuz/frametop-hands>), whose servers may be outside your country, for example in the USA. Anyone who accepts the dataset's terms can download it.
- People who download it agree not to try to identify anyone or anything in it, and to delete recordings that are later withdrawn. We can't enforce that against everyone: assume copies may exist.
- Recordings stay in the dataset until they're withdrawn or the dataset is taken down.
## Keep other people and private things out of view
While recording, please:
- face away from other people, mirrors, screens showing private things, papers, letters, photos and anything else you wouldn't want public;
- make sure nobody else's face or hands are in view, and record only where the people you share the space with are fine with it;
- don't record children.
If something private got into a recording, delete that stretch in Review before you export. If you notice it after uploading, withdraw the session (below).
## Safety
The sessions ask you to move your hands and arms around you, out to full reach. Sit where you normally use the headset, clear an arm's reach around you, and stop whenever anything is uncomfortable. You take part at your own risk.
## The license
- **The dataset is published under Creative Commons Attribution-NonCommercial 4.0 (CC BY-NC 4.0).** Anyone may use it for non-commercial purposes, with attribution. Your contribution is credited by its contributor id, not your name.
- **You also give the maintainer of Frametop a non-exclusive, worldwide, royalty-free license to use your contribution for any purpose, including commercially.** That includes copying it, changing it, and training, publishing and selling models made from it, in Frametop and elsewhere. The maintainer today is DeeJanuz. If someone else, or an organization, takes over maintaining Frametop, this license passes to them. It's non-exclusive: you keep any rights you have in your recordings and can do what you like with your own copies. It ends for a recording when you withdraw it, except for models already trained with it.
- You confirm that you have the right to give these licenses: the recordings are yours, and nothing in them belongs to someone who hasn't agreed.
- There is no payment. The dataset and the hand recorder come with no warranty, and as far as the law allows, the maintainer isn't liable for any loss or damage from taking part.
## Withdrawing
You can withdraw a contribution at any time, without giving a reason:
- **Before it's merged:** close your pull request on Hugging Face. The maintainer deletes its files.
- **After it's merged:** post on the dataset's discussion page, or in the Frametop repository's issues, with your contributor id (shown in the hand recorder) and which sessions, or "all". Post from the Hugging Face account that uploaded them if you can, so the maintainer can tell it's you; otherwise, say how to check. These requests are public, so don't add anything else that identifies you.
Then, usually within 30 days:
- your recordings are deleted from the dataset and purged from its repository's history, so they can't be downloaded from there again;
- they're left out of anything trained after that.
What can't be undone: copies others downloaded before the withdrawal, and models already trained with them.
## Your rights
Depending on where you live (for example in the EU or the UK, under the GDPR), the law may give you more rights over this data: to get a copy of it, to have it corrected or deleted, to object to its use, and to complain to your data protection authority. The data is used because you agreed to it, and you can withdraw that agreement at any time, as above. Withdrawing doesn't make earlier use unlawful. To use any of these rights, contact the maintainer as above.
## Changes to this text
If this text changes, the hand recorder shows the new version and asks you again before your next session. Each upload records the version you agreed to, and recordings you already uploaded stay under that version, unless you agree to a newer one or withdraw them.
## Agreeing
By ticking the three boxes and "Agree and continue", you confirm that you're 18 or older, that you don't live in Illinois, Texas or Washington, and that you agree to the above. You can still decide not to upload anything.
+366
View File
@@ -0,0 +1,366 @@
# Hand recorder: design (Phase 1 of the hands plan)
The hand recorder guides a person through recording their hands with the headset's cameras. It saves the recordings as files, lets them review and delete anything, then exports a package to contribute to the open hand dataset. Recordings never leave the headset unless the person uploads them.
The plan this belongs to is `~/Desktop/Projects/frame-hands/notes/hands-plan.md` (on the maintainer's Frame). In short, the dataset trains a small hand model for Frametop's hand cutouts.
## Parts
| Part | What it does |
|---|---|
| `hands/rec/panel/ft-handpanel.cpp` (C++, dev container) | The headset panel: a SteamVR overlay fixed to the head that shows the prompts. It also places the "touch the dot" target in the room and logs head and controller poses. Driven over `@ft_handpanel`. |
| `hands/rec/session.py` (Python, no Qt) | The session runner. It reads `script.json`, starts and stops the recordings, and drives the panel. It reads the live hands file for feedback and writes each take's files. It also runs from the command line (`--dry-run`) for testing. |
| `hands/rec/script.json` | The guided script: sections, prompts, timings. |
| `hands/rec/poses/` | The pose pictures, `poses.json` and its PNGs (below). |
| `hands/rec/takes.py` (Python, no Qt) | Reads sessions and takes from disk: frame sets for review, deleted ranges, export (compress, strip, manifest, checksums). |
| `hands/rec/ft_handrec.py` + `main.qml` (PySide6 + Kirigami, dev container) | The desktop window: consent, the before-you-start checklist, the session controls, review, export and upload instructions. |
| `hands/rec/ft-handrec` | The host launcher, like `input-settings/ft-input-settings`. |
| `hands/rec/build.sh` | Builds `ft-handpanel` into `hands/rec/build/`, like `gaze/build.sh`. |
| `hands/rec/CONSENT.md`, `hands/rec/UPLOAD.md` | The texts the window shows. |
| `hands/rec/install.sh` | Installs the recorder on a Frame with Frametop: the dev container's packages, hands/build.sh, the panel, ft-camd's capabilities, and the menu entry (`uninstall` removes the entry). |
| ft-hands `--record-hz N` (done) | Records at most N frame sets a second. The recorder uses 10. |
| `hands/camcheck.py` (shared, standard library) | Are all four mono cameras running? The recorder runs it before a session and when a step sees no hands (below; `hands/README.md`, "Camera check"). |
Every part runs in the dev container, as ft-hands and Input Settings do. The host Python isn't used: it lacks PySide6 and zstd. `setup/dev-container.sh` gains `zstd`.
## Processes during a session
- **ft-camd** publishes the camera ring. If it isn't running, the session starts it as the transient user unit `frametop-handrec-camd.service`, the way `hands/ft-cutouts` starts `frametop-cutouts-camd.service` (needs `hands/build/ft-camd` with capabilities: `hands/run.sh caps`). An ft-camd already running from ft-cutouts or ft-handsctl is used as it is.
- **A tracking ft-hands** gives feedback through the hands file: which hands are seen, the palm's distance, the index tip. If none is running, the session starts `ft-hands --no-gestures --status 0` (unit `frametop-handrec-hands.service`). An ft-hands already running is used as it is.
- **A recording ft-hands** runs once per recording part: `ft-hands --record-only --record DIR --record-for SECONDS --record-hz 10 --status 0 --sides auto|0|1` (below, "Side cameras"). It runs as a plain child process of the session, ended with SIGTERM when the part ends. SIGTERM ends ft-hands' loop, and `Recorder` writes out its queue when it's destroyed. In step mode (below) a part is one step's countdown and hold, so a take has one part per step (about 40 in the hand poses); in auto mode a take is one part, plus one more after each pause. `--record-for` is only a safety net.
- Why a process per part rather than one kept alive and paused: measured in the dev container with `ft-ringplay`'s ring (2026-10-02), `ft-hands --record-only` writes its first set 16-27 ms after it starts and ends 4-6 ms after SIGTERM, so a new part costs nothing the 3 s countdown doesn't cover. Every reader already takes parts in order (`takes.py`, `validate.py` through the export's single stream, the labeller's `fhl_io.py`, numbering `sets-10.bin` after `sets-9.bin`), ft-hands needs no new control, and nothing is written while a step waits. Before the hold starts the session checks that the part has written a set (`Recorder.has_data`, up to 3 s more), so the hold is recorded from its first frame.
- **Side cameras.** ft-camd can name the two side cameras the wrong way round (hands/README.md, "Which camera is which"). The tracking ft-hands decides from the hands within about 2 s of them being in view (`HANDS_SWAP_SIDES=auto`, hands/track/sides.h) and publishes that in `/run/user/UID/frametop-hands/sides.json`. The session reads it (`sides.py`, `read_live`) and stores it in session.json `"sides"`. Each later part is recorded named right (`--sides 1` or `0`). Parts recorded before the decision use ft-camd's names (`--sides auto`; a record-only ft-hands can't tell), and readers rename them (`sides.py`). Each part's `names_swapped` goes into take.json `"parts"`. Without a tracking ft-hands nothing decides: `"swapped": null`, the names stay as recorded, and the maintainer's check (`hub_review check`, check_sides on a few sets per take) tells. `takes.py sides SESSION --set swapped|named` records a decision by hand.
- **ft-handpanel** runs as a child process with `--watch-stdin`. It shows the panel and logs poses during each take.
- **The headset button's reader** is a thread of the session (`ButtonReader`, below), not a process.
Test hooks:
- `--ring PATH` goes to both ft-hands (`ft-ringplay` publishes a recording there, so the whole flow runs without the headset).
- `--no-start` uses only what's already running.
- `--dry-run` runs no processes and only prints the panel commands, with timing sped up by `--speed X`.
- `--next-after S` presses Next by itself after S seconds of waiting (real time), so a step-mode session runs unattended. Lines on stdin steer it too: `n` or an empty line is Next, `p` pause or resume, `r` redo, `s` skip the section, `q` stop.
- `--no-headset-button` leaves the headset's button alone (`ft-handrec --no-headset-button` too). `--button-device PATH` reads it from PATH instead, an event device or a FIFO of `input_event` structs, also in a dry run: a simulated button for tests.
- `--auto` runs the timed flow; `--poses DIR` takes the pose pictures from DIR; `--plan` prints the sections, their steps and length.
- `--ignore-cameras` (`ft-handrec --ignore-cameras` too) starts even when the camera check fails. A dry run and `--ring` skip the check by themselves.
## Files
```
~/.local/share/frametop/hands/contrib/
profile.json consent and contributor id (below)
sessions/<YYYYMMDD-HHMMSS>/ (a second session started in the same second gets -2, and so on)
session.json the session: checklist answers, lighting, versions, mode, takes
calibration.json /persist/xrservice.json with identifying fields removed (below)
device.json the rig's pose in the CAD frame from /persist/device_config.json (below)
takes/<NN>-<section>/
sets.bin ft-hands' recording (FHSET01, hands/track/record.h), 10 sets/s: the first part
sets-2.bin, sets-3.bin, ... the next parts (step mode: one per step; any mode: after a pause)
prompts.jsonl what the person was asked to do, when (below)
poses.jsonl head and controller poses from ft-handpanel (below)
take.json {"section", "title", "started_ns", "ended_ns", "status": "complete"|"stopped"|"skipped",
"deleted": [[from_ns, to_ns], ...], "notes": "",
"parts": {"sets.bin": {"names_swapped": false}, "sets-2.bin": {...}},
"clock": [[mono_ns, raw_minus_mono_ns], ...]}
exports/<session>/ what export writes (below)
```
All `_ns` times are CLOCK_MONOTONIC nanoseconds, the clock of `dqbuf_ns` in sets.bin and of `capture_ns` in the hands file. sets.bin's `capture_ns` is the camera clock (CLOCK_MONOTONIC_RAW). The two drift apart with NTP's corrections: on 2026-10-03 RAW ran 0.80 s ahead, gaining about 10 ppm. take.json `"clock"` samples the difference (RAW minus MONOTONIC, as ft-hands' `raw_minus_mono_ns()`) when each part starts and stops, so a set's exposure time on the poses' clock is `capture_ns - raw_minus_mono_ns`, interpolated between samples. `dqbuf_ns` is on the right clock already, but a few ms after the exposure. Takes recorded before 2026-10-03 have no `"clock"`.
### profile.json
```json
{"schema": 1, "contributor": "<random uuid4>", "consent": {"version": "2026-10-02", "accepted": "<ISO time>", "adult": true},
"optional": {"handedness": "right|left|both|", "notes": ""}}
```
No name, email, or account. The contributor id is random, so several sessions from one person can be held out together in evaluation. Withdrawal also goes by that id.
### session.json
```json
{"schema": 1, "tool": "ft-handrec <git describe>", "started": "<ISO>", "contributor": "<uuid>",
"lighting": {"chosen": "dim|room|daylight|indoor", "source": "measured|picked", "measured": "indoor|daylight|",
"ambient_ir": 0.0, "ring": {"<cam>": {"mean": 0.0, "dark_mean": 0.0}}},
"checklist": {"objects": ["pencil", "phone", "cup", "keyboard", "mouse", "gamepad", "small"], "own_objects": ["..."],
"controllers": "straps|none", "sleeves": "short|long|", "rings": false, "watch": false, "notes": ""},
"device": {"steamos": "<VERSION_ID from /etc/os-release>", "steamvr": "<version if known>", "cameras": [{"name", "width", "height"}]},
"mode": "step|auto", "quick": false, "shuffle": {"seed": 123, "sweeps": {"pose-sweeps": [{"id", "hands", "cues"}]}},
"takes": ["01-hand-size", "..."],
"camera": {"status": "ok|unknown|degraded", "reason": "..."}, "stop_reason": "...",
"sides": {"swapped": true|false|null, "decided_by": "auto|config|option|manual", "state": "decided|confirmed|...",
"evidence": {"as_named": 0, "swapped": 10, "seconds": 1.8, "miss_mm": [-1, 4.2], "probes": 30, "found": 10},
"decided_at": "<ISO>", "decided_ns": 0}}
```
`sides`: whether ft-camd's side camera names were backwards during the session (`swapped`), as the live tracker decided it (above, "Side cameras"); `null` while nobody knows. A part's names are right when its take.json `names_swapped` equals `swapped`. Parts without a `parts` entry were recorded with ft-camd's names. Sessions from before this have no `sides`.
`camera` is the camera check's verdict at the start (no paths or log lines: those go to `session.log`). `stop_reason` is there when a session was stopped at the no-hands screen, with the check's result.
A session started before step mode existed has no `mode`: it ran as `auto`. `quick` and `shuffle` (below, "Sweeps" and "Quick round") are missing from sessions before the sweeps.
### calibration.json
This is a copy of `/persist/xrservice.json` (`/run/host/persist/` in the container). Keep the cameras' intrinsics and extrinsics, and drop anything that identifies the unit: keys containing `serial`, `sn`, `uuid`, `mac` or `id`, or values that look like serial numbers. List what was removed in `session.json` (`"calibration_removed": [...]`), so a reviewer can check it.
### device.json
The head frame needs the rig's pose in the CAD frame, from `/persist/device_config.json`. Only two of its keys are kept, `cv.cad_from_cal` (Cam0 in the CAD frame) and `head` (the head in CAD), in the shape the labeller in frame-hands `train/label` reads, as its `cut.py` writes it:
```json
{"cv": {"cad_from_cal": {"method": "FrontAndUpperCamPositions", "plus_x": [x, y, z], "plus_z": [x, y, z], "position": [x, y, z]}},
"head": {"plus_x": [x, y, z], "plus_z": [x, y, z], "position": [x, y, z]}}
```
The rest of that file identifies the unit (serial number, display EDID) and is never copied. The two kept keys go through `strip_calibration` as well, and anything it removes is listed in `calibration_removed` as `device.json:<path>`. Sessions recorded before device.json existed have none: they still validate, with a warning, and the labeller falls back to another unit's pose.
### prompts.jsonl
One JSON object per line:
```json
{"t": 123, "event": "take", "section": "static-poses", "take": "03-static-poses"}
{"t": 123, "event": "prompt", "id": "static-poses/fist/left/near", "text": "...", "hands": "left|right|both|none",
"pose": "fist", "distance": "near|mid|far|", "position": "centre|left|right|up|down|", "object": "", "controller": false}
{"t": 123, "event": "target", "id": "touch/3", "head": [x, y, z], "room": [x, y, z], "state": "show|hold|done|timeout"}
{"t": 123, "event": "bar", "target": 0.0}
{"t": 123, "event": "feedback", "left": true, "right": false, "palm_m": [0.0, 0.0]}
{"t": 123, "event": "pause"}
{"t": 123, "event": "resume"}
{"t": 123, "event": "ready", "id": "static-poses/fist/left/near", "seconds": 3}
{"t": 123, "event": "wait"}
{"t": 123, "event": "redo", "id": "static-poses/fist/left/near", "from": 123, "to": 123}
{"t": 123, "event": "nohands", "id": "hand-size/flat/both", "reads": 120, "published": 118}
{"t": 123, "event": "end", "status": "complete|stopped|skipped"}
```
`feedback` is written about twice a second while recording. It's the live tracker's view, kept for later checks; it's not a label.
A prompt holds from its `prompt` until the next `prompt`, `ready`, `wait` or `end`. A step in step mode reads:
```
ready Next pressed: recording part N starts, the 3-2-1 countdown runs (recorded, no label)
prompt the hold: its labels start here
(bar, target, feedback, pause/resume during the hold)
wait the hold is over: no labels from here; part N stops
```
The touch-the-dot targets after the first follow straight on: no `ready` or `wait` between them. `redo` marks a try done again (R): `from` is that step's `ready` (or its `prompt` if it had none), `to` its end. Its prompt is skipped; the sets stay. In auto mode there's no `ready` or `wait`, and the intro is a recorded prompt `<section>/intro`. `nohands` marks the first hand-size step stopped because no hand was seen (below, "Camera check"); a `redo` over the same range follows it, so the try gets no labels. A sweep step (below, "Sweeps") has a `prompt` per cue, each with its `pose`, `"cue": true` and `"step"`, the step's id; its `ready`, `wait` and `redo` carry the step's id. Readers that knew only `prompt` and `end` keep working, but they'd give the countdown to the step before: `hub_review.py` (frame-hands `train/hub`) shows it as "(countdown)", redone prompts as "(redone)" and cues as "[pose] text"; `FORMAT.md` in the dataset repo has the rules.
### poses.jsonl
ft-handpanel writes one line per sample, 250 a second, from `GetDeviceToAbsoluteTrackingPose(TrackingUniverseStanding, 0)`:
```json
{"t": 123, "hmd": {"m": [12 floats, row-major 3x4], "r": 200, "ok": true},
"left": {"m": [...], "r": 200, "ok": true}, "right": null}
```
`r` is `ETrackingResult` (200 = Running_OK, 201 = Running_OutOfRange, and so on). `left` and `right` are the devices holding those controller roles, or null. No device serials are logged.
## The panel (`ft-handpanel`)
- **Placement.** A SteamVR overlay fixed to the head, like `gaze/panel/ft-gazepanel.cpp`: key `frametop.handpanel`, sort order 250. It sits 1.2 m ahead, centred 12 degrees above straight ahead, so the hands stay clear below it. It's 36 degrees wide, 4:3, 1024x768 pixels, dim and see-through. It's drawn on the CPU with stb_truetype (and stb_image for the pose pictures, PNG only, the same pinned stb commit) into three shared DMA-BUFs SteamVR imports once, as ft-gazepanel does, and is drawn again only when something changes.
- **Layout.** The title and step on top (a red "Rec" by the step while recording), a rule. With a pose picture or a diagram, a 14-degree column on the left holds the picture (or the flipped copy and the picture side by side) and the where-to diagram under it; the text takes the right. The text column holds the instruction, the orange note, the big countdown ("3", "2", "1", then "Hold" or "Go") and the cyan action line ("Ready? Press Space or click Next"), centred together. At the bottom: the near/far bar, the hand chips, the time-left bar and the key hints.
- **Socket.** Abstract unix datagram `@ft_handpanel` (`--socket NAME`). A sender with an address gets `ok ...` or `error ...`.
- **Options:** `--watch-stdin` (quit when stdin closes), `--socket NAME`, `--distance M`, `--no-vr`. `--no-vr` makes no SteamVR connection and prints each picture's text to stdout: for testing without a headset.
Commands (UTF-8; `|` starts a new line in text):
| Command | Effect |
|---|---|
| `show` / `hide` | The panel. A "show" makes it visible with its first picture. |
| `title <text>` | Big line at the top. |
| `step <text>` | Small line at the top right, e.g. `Section 3 of 11`. |
| `text <text>` | The instruction, large, wrapped to the panel's width, centred. |
| `note <text>` | An orange line under the instruction: a warning ("I can't see your left hand"). Empty clears it. |
| `countdown <0..1>` / `countdown off` | A thin bar along the bottom: the share of this prompt's time left. |
| `hands <left> <right>` | Two chips, "Left hand" and "Right hand", each `seen` (green), `lost` (orange) or `off` (hidden). |
| `bar <target 0..1> <current 0..1 or -1> [near label] [far label]` / `bar off` | The near/far bar for the push out and back: a horizontal track with a target marker and the hand's current position. |
| `paused on` / `paused off` | A "Paused" overlay over the picture. |
| `image <path> [mirror\|both]` / `image off` | The pose picture, a PNG (below), in the left column. `mirror` flips it (a left hand); `both` draws a flipped copy on its left. A file that can't be read: `error ...` and no picture. |
| `where <position\|-> <distance\|->` / `where off` | The where-to diagram under the picture: a 3x3 front view with the asked cell lit (`centre`, `left`, `right`, `up`, `down`, and the push sections' `chest`, `desk`, `eye`), and a side view of the head and three marks for `near` ("Close"), `mid` ("Halfway out") and `far` ("Arm out"). `-` leaves that half out. |
| `action <text>` | The cyan line under the instruction (empty clears it). |
| `big <text>` | Large cyan text under the instruction: the countdown (empty clears it). |
| `keys <text>` | The faint key hints along the bottom. |
| `rec on` / `rec off` | The red "Rec" by the step line. |
| `strip <cue> <path>\|<mode>\|<label>;...` / `strip off` | A sweep's row of pose pictures (path `-`: none; mode `-` or `mirror`), each with its label under it; the one at index `cue` (from 0, -1 for none) framed in cyan and bright, the others dim. It sits along the bottom of the space left, the where-to diagram at its right end if there is one, and the text above it; it takes the left column's place. Each picture is loaded once. A file that can't be read: `error can't read ...`, and that item shows an empty frame. |
| `target <x> <y> <z> [show\|hold <0..1>\|done]` / `target off` | The touch target: a small sphere-like dot about 2 cm across, in its own overlay (`frametop.handpanel.target`). The point is in the head frame (metres, +x right, +y up, -z forward). The first `target` with a new point places it in the room with the current HMD pose, and it stays there. Later commands with the same point change only the state. `hold` draws a filling ring, `done` turns it green. Reply: `ok <room x> <room y> <room z>`. |
| `poses start <path>` / `poses stop` | Log poses to the path (appending, `poses.jsonl` format above) from a thread at 250 Hz, until stopped. |
| `devices` | Reply: `ok hmd <r> left <r or -> right <r or ->`, the current `ETrackingResult` values (`-` for no device in that role). |
| `head` | Reply: `ok <12 floats>`, the current HMD pose (standing universe). |
| `ping` | `ok shown` or `ok hidden`. |
It quits on SteamVR's quit event, as ft-gazepanel does. `--no-vr --dump DIR` writes each picture to `DIR/panel.pam`, to check the layout without a headset.
## The pose pictures (`poses/`)
`poses/poses.json` maps the script's `pose` ids to pictures: `{"<pose>": {"file": "<name>.png", "two_hands": false, "caption": "..."}}`. Each PNG is RGBA, square (512x512), drawn as the wearer sees it: a right hand, unless `two_hands` (then it shows both). How a prompt shows it (`session.pose_view`):
| Prompt's `hands` | Picture |
|---|---|
| `right` (and `any`, `none`, empty) | as drawn |
| `left` | flipped left to right (`image ... mirror`) |
| `both`, not `two_hands` | a flipped copy on the left, the picture on the right (`image ... both`) |
| anything, `two_hands` | as drawn |
A pose with no entry, or whose file is missing, shows no picture: the text alone. The session reads `poses.json` when it starts. The window shows the same picture (QML `Image.mirror`), its caption, and the same diagram.
## The script (`script.json`)
```json
{"version": 1,
"cue_names": {"thumbs-up": "Thumbs up", "...": "..."},
"sections": [
{"id": "hand-size", "title": "Hand size", "requires": [], "intro": "text shown before the first prompt: 4 s, or until Next", "go": "Hold",
"quick": true, "prompts": [{"text": "...", "cues": ["flat", "flat-back", "spread"], "cue_s": 5, "hands": "both", "distance": "mid"}]},
{"id": "pose-sweeps", "title": "Hand poses", "kind": "sweep", "quick": true, "cue_s": 4, "step_s": 20,
"groups": [["open", "fist", "point", "pinch"], ["ok", "thumbs-up", "spread", "claw"], ["count-1", "...", "count-5"]],
"sweeps": [{"hands": "both", "group": "next", "text": "..."}, {"hands": "left", "group": "any", "quick": false, "text": "..."}]},
{"id": "objects", "title": "Things you hold", "requires": ["objects"], "for_each": "object",
"prompts": [{"text": "Pick up the {object} and use it the way you normally would.", "seconds": 15, "hands": "both", "object": "{object}"}]},
{"id": "touch", "title": "Touch the dot", "kind": "targets", "hold_s": 1.0, "timeout_s": 8,
"targets": [[0.0, -0.15, -0.40], ...], "text": "Touch the dot with your index fingertip and hold still."},
{"id": "controller-push", "title": "Depth with controllers", "requires": ["controllers"], "kind": "bar",
"intro": "...", "heights": ["chest", "desk", "eye", "left", "right"], "reps": 5, "period_s": 6, "near_m": 0.2, "far_m": 0.6}
]}
```
- `requires`: `objects` (at least one object ticked), `controllers` (straps ticked). A section whose requirements aren't met is skipped and logged.
- `go`: the word the countdown ends on, "Go" unless set ("Hold" for the still poses).
- `quick`: the section is in a quick round; a step with `"quick": false` isn't (below).
- `kind`:
- `prompts` (the default): each prompt shows for its `seconds` with a countdown. A prompt with `cues` (and `cue_s`) is a sweep step with those cues in that order, `seconds` = cues x cue_s (hand size; the mouse and switch step).
- `sweep`: steps built from `sweeps` (below).
- `targets`: each target shows until the live index tip is within 3 cm of it for `hold_s`, or `timeout_s` passes.
- `bar`: the target marker sweeps near to far and back, `reps` times per height, at `period_s` per sweep. The current marker follows the live palm distance.
- Each section is one take. Prompts within it are marked in `prompts.jsonl`.
- `cue_names`: the short labels under the strip's pictures (otherwise the pose id).
### Sweeps
The second in-headset session (sessions/20261002-202734) took about 16 min and was "super long and kind of annoying": the 36 held poses alone took 7.9 min, 3.2 of it reading, and the person skipped the wrist turns and gave up on the bare push after 3 steps. The labels come from the auto-labeller (teacher model and triangulation, frame-hands `train/label`), not from the prompts, so what the recordings need is variety (shapes, distances, angles), not clean holds. So the poses are swept:
- A sweep step shows a strip of 2-5 pose pictures and asks for slow, continuous movement (near and far, all around) while the hands change shape with the lit picture. The light moves on every `cue_s` (4 s), cycling, over `step_s` (20 s): 5 cues for a group of 4 or 5. Each cue is a `prompt` event with that `pose`, `"cue": true` and `"step"` (the step's id); `distance` and `position` are "" (varied). So the timeline tags each pose roughly, and the countdown, `wait` and `redo` work per step as before. The time-left bar covers the whole step.
- `groups`: lists of poses. A step takes `"group": "next"` (the groups in turn) or `"any"` (one drawn at random, a different one for each "any" while there are groups left), or names its own `cues`. `"shuffle": false` (gestures) keeps the script's order; `"cycle": false` runs the cues once; `"fixed": true` keeps one step's order.
- The pose sweeps: 3 two-hand sweeps, one per group ([open, fist, point, pinch], [ok, thumbs-up, spread, claw], [count-1 ... count-5]); then a left-hand and a right-hand sweep (the other hand in the lap) on groups drawn from those three, which also turn the wrist as they go, so the wrist angles come for free (the old wrist-turns section is gone).
- **The shuffle, per session.** The groups' order, the "any" draws and the cues' order in each step are shuffled with a seed from the session's id (`session_seed`: the first 8 hex digits of its SHA-256), separately per section (`random.Random("<seed>/<section>")`). The sections' order isn't shuffled (the controller sections need their before and after). session.json records `"shuffle": {"seed", "sweeps": {section: [{"id", "hands", "cues"}]}}`, and `build_plan(script, checklist, seed=...)` gives the same again. `--seed N` overrides it; `--plan` without one shows the script's order.
- The strip has one picture per pose, a single hand: both hands make the same shape, and five pairs wouldn't fit. A left hand's pictures are flipped.
- Gestures are sweeps too, in order and once: tap then drag; grab, cross, overlap; near the face then a screen's distance. Hand size is one step of three held shapes (flat, backs, spread; 5 s each), still the no-hands check's first step.
### Quick round
For more lighting rounds: "Quick round (about 3 min)" on the checklist page, `session.py --quick`. It has the sections marked `quick` (hand size, the pose sweeps without the one-hand ones, touch the dot, no hands), about 2 min recorded in 6 steps. session.json gets `"quick": true`. The checklist page suggests it (and picks it) once a full session has gone to the end (`Backend.hasFullSession`: a session.json with status `done`, not quick, not a dry run).
### Step mode (the default) and auto mode
The first in-headset session (2026-10-02) went too fast: each prompt advanced after 4-8 s, before there was time to read it and find the hand shape. So by default every step waits:
1. **Ready.** The panel shows the step: section title, "step N of M", the instruction, the pose picture, the where-to diagram, and the Next hint ("Ready? Press the button on the right side of the headset", or with a mouse also Space and Next: see Controls). The hand chips show which hands are seen, with no warnings yet. It waits as long as it takes, and nothing records.
2. **Countdown.** Next starts a new recording part and a "ready" event, and the panel counts 3, 2, 1 (big), recorded so the hold is captured from its first frame. In the push sections the bar sits at near meanwhile.
3. **Hold.** The `prompt` event, the section's word ("Hold" or "Go") and the time-left bar for the prompt's seconds (or the bar's sweeps, or the targets). Then a `wait` event and the part stops.
Steps that wait: each prompt, each bar height, and the first touch-the-dot target (the others follow straight on, as each waits for the touch anyway). Before a section, one screen shows the section's intro (with its `before` text, such as putting on the controllers) and waits for Next too; the welcome screen as well. The take starts with the section's first countdown, so a section skipped at its intro leaves no take. A pause in a hold works as before (the part stops; resume starts the next one).
Auto mode ("Advance by itself" on the checklist page, `session.py --auto`) is the old timed flow: the welcome, the between and before screens, the intro (recorded) and each prompt for its seconds, one recording per take. R still works there: it restarts the step running.
Steps are 20 s sweeps, 16-18 s gestures, 10-12 s desk and object steps, the touch targets (6) and the push heights (2, 3 reps of 6 s). The core session (no objects, no controllers) records about 5 min in 15 steps; with 5 s of reading a step that's about 6 min. Everything ticked (four objects, controllers): about 7.3 min recorded in 24 steps. A quick round: about 2 min in 6 steps. The window and `session.py --plan` give these (`plan_summary`); in step mode they leave the reading time out and say so.
The sections, in this order (see the plan):
1. hand size (one step: flat, backs, spread)
2. pose sweeps (above: 3 with both hands, one with each hand)
3. gestures (3 sweeps: pinch taps and drags; grabs, crossing and overlapping; near the face, then pointing at screen distance)
4. desk work (typing or pretend typing; the mouse, with switching to the keyboard when both are there)
5. objects (one prompt per ticked object, own objects included)
6. touch the dot (6 dots spread near and far, left and right, low)
7. controller depth, straps (push out and back at chest and eye level, 3 reps each; then the wrists and fingers with the controllers on). "Out and back" is straight away from the headset and back toward it: the first in-headset session took the left-right bar for sideways. The texts say so, the bar's ends read "At your chest" and "Arm out" (`near_label`, `far_label`, sent as `bar ... At your chest|Arm out`), and the picture is a side view.
8. bridge (one controller on, the bare fingertip on its thumbstick while that hand moves from close to arm's length and back, then swap; then a controller on the desk, touched from the front and above, then from the sides: 4 steps, the controller changes during the ready screens)
9. bare repeat of section 7's pushes, controllers off
10. no hands (10 s)
Before section 7: "Put on both controllers and tighten the straps". Before section 9: "Take the controllers off and put them out of view".
### Feedback while recording
- **Hands seen:** from the hands file. A hand counts as seen if its flags match the side and the file is fresh (publish within 0.3 s). Prompts with `hands` set show the `hands` chips. If an asked-for hand is lost for more than 1.5 s, the note says "I can't see your left hand: bring it into view".
- **Controller tracking:** in sections 8 and 9, `devices` is polled once a second. A result other than 200 for more than 1 s says "The left controller lost tracking: turn your palm slightly toward you". Each such stretch goes into `prompts.jsonl` as `feedback` with `"controller": {...}`.
- **Lighting, measured:** the checklist page measures the light when it opens, starting ft-camd (`frametop-handrec-camd.service`) if nothing runs it; the window stops it again on quit if it started it. The mean of every mono camera's `mean` and `dark_mean` from the ring (`hands/tools/ring.py` layout; struct only, no numpy) is compared with the person's earlier sessions. If it matches an earlier round's within 15%, the window says so before starting.
- **Lighting label:** "Measured by the cameras" is the default. `ambient_ir`, the mono cameras' mean `dark_mean` (the room's infrared), labels the round `daylight` from 6.0 and `indoor` below (`session.classify_lighting`). Lamps and LEDs give off hardly any infrared, so a dim room and a lit one read about the same (1.8 by one lamp, 2.2 in a lamp-lit room) and the cameras can't tell them apart; the person can pick dim, room or daylight instead (`source: "picked"`). The 6.0 threshold is a guess until a daylight round is measured.
### Camera check
On 2026-10-02 a whole session showed "I can't see your hands": after the headset slept, SteamVR had failed to load the colour module's FPGA image, which left the upper cameras and the IR light off (`hands/README.md`, "Camera check"). Two checks keep that from wasting a session:
- **Before the session.** The window runs `hands/camcheck.py` when the checklist page opens ("Tracking cameras:", with the evidence under Details and Check again), and again when Start is pressed; `session.py` runs it first thing, before it makes the session's folder or starts anything (`Session._preflight`). If it finds the cameras degraded, the session doesn't start. The window says: "The headset's upper cameras and IR light are off. SteamVR couldn't start the colour camera module (it happens sometimes after the headset sleeps). Restart SteamVR, or restart the headset if that doesn't fix it." (another `degraded:` reason gets a sentence naming it), and Start stays off. `unknown` (SteamVR not running, the cameras asleep) doesn't stop it: the session's own start fails clearly then. From the command line, `session.py` prints the check and exits with status 3.
- **Restart SteamVR.** The message has a Restart SteamVR button. After a confirmation it runs `systemctl --user restart --no-block steamvr.service` on the host (through `distrobox-host-exec`), then checks the cameras every 3 s, for up to 2 minutes, until a new XRService has opened its cameras. The confirmation says what really happens: every VR app closes, and so does the Frametop desktop with all its windows, this one included, and it doesn't come back by itself (`hands/README.md`, "What a SteamVR restart does to Frametop"). So the check after the restart mostly happens when the recorder is opened again; it re-runs when the checklist page opens. `--no-block` lets the restart finish after the window is gone.
- **No hands in the first step.** The first step of the hand-size section has both hands up, about 40 cm away. During its hold, the session counts the hands file's reads (about 20 a second). If the tracker published in at least half of at least 10 reads and never saw a hand, the step stops: a `wait` and the recording stops as usual, then a `nohands` event and a `redo` over the try. The session runs the camera check and shows "I can't see your hands" with its result (the camera text above when it's the VCINT failure, else "The camera check found nothing wrong"). The state is `nohands`, waiting: Next (the headset button, Space, Try again) or R starts the same step's countdown at once; Stop (Esc) ends the session with `stop_reason` set; S skips the section. One missed step costs a retry, not the session, and every hold of that step is logged ("hands check ...: a hand in N of M reads"). Without a tracker publishing the session can't tell, logs that, and goes on. Only that one step is checked: later steps have their notes ("I can't see your left hand") as before. Auto mode does the same; its recording pauses meanwhile.
### Controls
- The window has Start, a big Next (while a step waits; its hint is the panel's), Pause/Resume, Redo step, Skip section and Stop. While it has focus: Space is Next, P pauses or resumes, R redoes, S skips the section, Esc stops. The panel's bottom line and the window list them. The window also shows the step's picture, diagram, countdown and "Hold".
- **The headset's button.** The Frame has a click button on its right side, for use without controllers: `KEY_SELECT` (353) on the evdev device `gpio-keys`. While a step waits (the welcome, a section's intro, a step's ready screen) a press is Next; during a countdown or hold (and auto mode's timed screens) it pauses; while paused it resumes. The session finds the device in `/proc/bus/input/devices` by name and its KEY bitmap (`event3` on the maintainer's Frame) and reads `input_event` structs with plain `struct` (no python-evdev), from a thread. Only key-downs count (value 1: releases and autorepeat, value 2, don't), and presses closer than 0.3 s count once.
- It's read, never grabbed (`EVIOCGRAB`). Frametop's input relay (`input/input-relay.py`), ft-powerd, SteamVR and gamescope read the same device, and the relay remaps its volume keys (the experimental branch's `docs/hazards.md`). A grab would take the volume keys from the relay.
- `steamos` is in the `input` group, so it needs no sudo. The dev container sees the host's `/dev/input` and `/proc/bus/input/devices`, and the group carries over (checked 2026-10-02), so it works from the window there and from `session.py` on the host. If the device is missing or can't be opened, the session logs it, keeps trying every 5 s, and the hints don't mention the button.
- **Not known yet (needs the headset):** what SteamVR and gamescope do with the same press. They read it too, so it may also click whatever is under the head or gaze pointer in VR, or open something. Check on the first session; if it does, the fix is on their side or a different button, not a grab.
- **The Next hint follows what's there.** No mouse connected: "Ready? Press the button on the right side of the headset" (the window's Next can't be clicked, and Space needs the window focused). A mouse: "Ready? Press Space, click Next, or press the headset button". No button: "Ready? Press Space or click Next". The panel's bottom line leads with "Headset button: next, pause". A mouse is a device in `/proc/bus/input/devices` with EV_REL, REL_X and REL_Y that isn't made in software: uinput devices (Frametop's virtual mouse, frame-voice's keyboard) sit under `/devices/virtual/input` or on the virtual bus (6), and are left out; Bluetooth mice come through uhid, under `/devices/virtual/misc/uhid`, and count. It's looked at again at each step, so a mouse plugged in mid-session counts from the next step.
- **R (redo).** During a step's countdown or hold: that step starts again from its ready screen. At a step's ready screen: the step before it (in this section) goes again. Either way a `redo` event marks the range of the try being redone, so its labels are skipped; the sets stay, to delete in review if wanted.
- A pause stops the take's recording and starts it again on resume as the next part of the same take (`sets-2.bin`, and so on). takes.py reads all parts in order. A pause while a step waits only shows "Paused"; a Next pressed while paused doesn't count.
## Review and export (`takes.py`, the window)
- **Review.** Each session lists its takes: title, duration, status, a thumbnail (the first set's `slam_left`). A viewer shows one frame set (all cameras side by side, 8-bit grey) at a time with a slider. It can mark a range and delete it. Deleted ranges go into `take.json`, and export leaves them out; the files keep everything until export. A whole take or session can be deleted (files removed, after a confirmation).
- **Export.** It writes `exports/<session>/`:
- `manifest.json`: profile fields except `optional.notes` unless kept, session.json (without its `uploads` records), takes, schema, tool version, the consent version.
- `calibration.json` and `device.json`, when the session has them.
- Per take: `prompts.jsonl`, `poses.jsonl`, `take.json`, and `sets.bin.zst` (sets in deleted ranges removed, then zstd -10 with 2 threads).
- The side cameras are named right in every exported set when the session's `sides.swapped` is known: parts that need it get slam_left and slam_right (and their `_dk`) exchanged in the set headers as they're compressed. The exported take.json says `"parts": {"sets.bin": {"names_swapped": <swapped>}}`, and the manifest's take entry `"sides": {"names_swapped", "renamed_sets"}`. Unknown, the names stay as recorded.
- `poses.jsonl` and `prompts.jsonl` without what's in the deleted ranges: no poses and no live-tracker `feedback` there (the prompt timeline stays). With the checklist's controllers at `none`, the controllers' poses are null and `feedback` has no `controller` (`takes.export_jsonl`): controllers left switched on still get tracked, and their poses would pass for the hands' ground truth.
- `SHA256SUMS`.
Compression runs at nice 19. While it runs with the headset worn, the window notes that VR may stutter a little (exports are done in the headset). Worn is judged the way `frame-job` does: `vrcompositor` runs and a `/sys/class/backlight/*/brightness` reads over 0 (SteamVR turns the panel off 5 s after the headset comes off). CPU work while in VR causes stutter. The proximity sensor is no use here: it read 9-43 with the headset sitting unworn.
- **Upload.** The Upload page uploads an export from the window, logging in included: no terminal. Below its steps it shows `UPLOAD.md` ("About uploading"), with the export's path, size and contributor id filled in.
- **`hands/rec/validate.py`** (standard library) checks an export. The window runs it before an upload, and the maintainer runs it on each submission (`validate.py DIR [--json]`, exit status 1 on errors). It checks:
- `SHA256SUMS`: every file listed and matching.
- An allow-list: `manifest.json`, `calibration.json`, `device.json` and `SHA256SUMS` at the top, and `prompts.jsonl`, `poses.jsonl`, `take.json` and `sets.bin.zst` in `takes/<NN>-<section>/`. Anything else is an error, and so is a symlink.
- The manifest's schema, keys and types, and that it matches the files.
- The consent version is present and the contributor confirmed being an adult. The contributor id is a uuid4.
- `calibration.json` has nothing that `session.py`'s `strip_calibration` would still remove.
- `device.json` holds only `cv.cad_from_cal` and `head`, each `plus_x`, `plus_z` and `position` as 3 numbers (plus `cad_from_cal`'s `method`). Without it: a warning.
- Each `sets.bin.zst` decompresses to its end, so a truncated one fails, and every set's FHSET01 header is sane: camera names, sizes, record length. Set counts and raw bytes match the manifest. Pixels aren't decoded.
- Every jsonl line parses.
- `session.sides` is `{"swapped": true|false|null}`, and every take's `sides.names_swapped` equals it (else an error: export again). Without `sides`, or `null`: a warning (the maintainer's check tells).
- The total size: a warning over 15 GB, an error over 40 GB.
Warnings cover notes kept in the export, a home folder path in the manifest, and missing `poses.jsonl` files.
It runs on Linux and on Windows (the maintainer's PC) with Python 3.12 or later. It decompresses with Python 3.14's `compression.zstd`, else the `zstandard` package, else the `zstd` program, and handles several zstd frames in a row.
- **`hands/rec/hub.py`** does the upload. It runs as a child process of the window (Cancel ends it), or from the command line (`hub.py [--base DIR] whoami | login | upload SESSION [--dry-run] [--again] [--json]`). It uses `huggingface_hub` (`python3-huggingface-hub` in the dev container) with the login saved in huggingface_hub's token file.
- **`login`** is huggingface_hub's browser login (OAuth device code), the same as `hf auth login`'s default since huggingface_hub 1.x. It asks Hugging Face for a link (`https://hf.co/oauth/device`) and a short code, prints them (`{"phase": "code", "url", "code", "expires_in"}`), and waits while the person enters the code in their browser and approves. Then it saves the token, which can refresh itself. Nobody types or pastes a token, and the window never sees one. It uses huggingface_hub's own helpers (`request_device_code`, `poll_device_token`, `_save_oauth_token`), as there's no public call that hands back the code. On 2026-10-03 the code lasted 5 minutes and wasn't filled into the link. The consent screen lists the person's organizations: none are needed, as a pull request on a public dataset comes from the person's own account.
An upload goes through these steps: An upload goes through these steps:
1. Validate, and stop on errors.
2. Stop if the same export was uploaded before (same `SHA256SUMS`), unless asked again.
3. Stop while the texts are drafts, unless `FT_HANDREC_ALLOW_UPLOAD=1`.
4. `whoami`: a read-only token is refused.
5. `auth_check` on the dataset: a gated dataset whose terms aren't accepted gives "accept the dataset's terms first", with the link.
6. Open the pull request first: `create_pull_request(HF_DATASET, title, description=...)`, an empty draft. Its link goes to the window right away (`{"phase": "opened", "pr_url"}`), which tells the person to plug the headset in and leave it. Record `{"repo", "pr_url", "pr_num", "started", "export_sha", "status": "started"}` in `uploads` in `session.json`. A retry of the same export goes on in that pull request while it's draft or open.
7. `upload_folder(repo_id=HF_DATASET, repo_type="dataset", folder_path=EXPORT, path_in_repo="contributions/<contributor>/<session>", revision="refs/pr/N", commit_message=..., commit_description=...)`. The description summarizes the manifest: takes, minutes, sets, lighting, objects, controllers, the consent and tool versions, the size, and validate's warnings. Then mark the pull request open if it's still a draft (the maintainer's `list` shows open ones, so drafts are uploads still in progress).
8. Mark the record `"status": "done"` with `uploaded`. `export_sha` is the SHA256 of `SHA256SUMS`. The file keeps its modification time, so the export doesn't count as out of date. Only finished records count as "uploaded before" (records without a status are from before 2026-10-03 and finished).
Errors get a plain explanation: not logged in, a login Hugging Face rejects (401), a login that can't open a pull request (403), terms not accepted, dataset not found, network errors. `--dry-run` does everything except the network calls and the record, and lists what it would upload.
- **The page** has three numbered steps:
1. Choose the export, with its size.
2. Log in to Hugging Face. The page shows whether someone is logged in (`whoami`). Log in runs `hub.py login`, opens the link in the browser, and shows the code large, with Copy code and Cancel. "Use another account" logs in again. A classic read-only token counts as not logged in.
3. Upload, with a note to accept the dataset's terms the first time.
Upload has Cancel, the phase with a progress bar (a share while the export is checked, a sweep while it's sent, as `huggingface_hub` reports no progress), the pull request's link once it's open, with "plug in the headset and leave it plugged in until this says Uploaded", and Uploaded at the end. If this export was uploaded before, the page says so, and uploading it again asks first. A stale export can't be uploaded.
- **Staying awake:** while an export or an upload runs, the window holds a host unit, `frametop-handrec-awake.service`, running `systemd-inhibit --what=sleep:idle --mode=block ... sleep infinity`, and stops it when the last of them ends (or on quit). It's meant to keep Steam from putting the Frame to sleep with the headset off; whether Steam's sleep honours a logind block inhibitor is still to be checked on the device. Exports and uploads are done in the headset: the export page only notes that VR may stutter a little while it compresses.
- **While the texts are drafts**, Upload stays off unless `FT_HANDREC_ALLOW_UPLOAD=1`, so the maintainer can rehearse against a private test repo. `FT_HANDREC_DATASET` overrides `HF_DATASET`. `ft-handrec --hub-dry-run` makes Upload a dry run: no network, so it isn't held back by the drafts.
- **Rehearsal: `hands/rec/rehearse.sh [--repo ID]`** runs it all without the headset, in the dev container, in one `frame-job --local` scope when frame-job is installed. `ft-ringplay` plays 30 s of a recording into a ring in `/run/user/UID`. A tracking ft-hands that's already running is used, or one is started on that ring. `ft-handpanel --no-vr` stands in for the panel. `session.py --no-start --next-after 0.3` records a three-section test script (a prompt, a two-cue sweep, no hands) in step mode, three parts of 6 s (countdown and hold), about 360 MB once exported. Then `takes.py` exports, `validate.py` checks, and `hub.py` uploads: a dry run by default, or for real to `--repo ID` with `FT_HANDREC_ALLOW_UPLOAD=1`. It prints a summary, deletes its temporary folders (camera images of a room) and stops everything it started, Ctrl+C included. The `--no-vr` panel logs no poses, so `poses.jsonl` is missing there (a warning).
## Licensing and consent (texts in `CONSENT.md`)
- The dataset is CC BY-NC 4.0.
- Contributors also grant the maintainer (DeeJanuz) a broad, non-exclusive license to their contribution.
- Contributors confirm they're 18 or older.
- The text explains what's recorded and that nothing uploads automatically, how review works, how to withdraw (by contributor id), and that a withdrawal is purged from the repo's history.
- The texts need a legal review before the dataset launches. Until then they carry a "draft" banner, and the Upload page says contributions aren't open yet.
- The dataset repo: `HF_DATASET` in `hub.py`, `DeeJanuz/frametop-hands` (private until launch).
+9
View File
@@ -0,0 +1,9 @@
### About uploading
- **What's sent:** the export in `@EXPORT_PATH@` (@EXPORT_SIZE@), into `contributions/@CONTRIBUTOR@/@SESSION@` in [@DATASET@](https://huggingface.co/datasets/@DATASET@). Upload first checks that every file is complete and matches its checksum, and that nothing identifying is left in.
- **Your account:** the pull request comes from your Hugging Face account, and anyone can see its username next to your contributor id, `@CONTRIBUTOR@`. The dataset itself credits the contributor id, not your name. The login stays saved on this headset, so you only log in once.
- **The dataset's terms:** the first time, open the dataset's page and accept its terms. Until you have, Upload stops with "accept the dataset's terms first".
- **Once your pull request's link shows, plug in the headset and leave it plugged in until this page says Uploaded.** A round is several gigabytes, so this can take a while. You can take the headset off: the Hand Recorder keeps it awake until the upload is done. Keep the Hand Recorder open, since closing it stops the upload.
- **If it stops partway** (Cancel, or the network drops), press Upload again. It carries on in the same pull request, and files already sent aren't sent twice.
- **The maintainer's review:** they check that the files are complete, and that nobody else and nothing private is in view, before merging. You can follow it and answer questions on the pull request's page. Once it's merged, you can delete the session and its export here to free the space.
- **Withdrawing:** see "Withdrawing" in the consent text. You'll need your contributor id, `@CONTRIBUTOR@`.
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Build the hand recorder's headset panel ft-handpanel in the dev container on the Frame
# (hands/rec/build/; it also runs there). Like gaze/build.sh: the pinned public OpenVR header
# (the DMA-BUF import is newer than the header shipped with SteamVR's samples), stb_truetype
# for the text and stb_image (PNG only) for the pose pictures, at the same stb commit.
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
"$root/scripts/sync.sh" >/dev/null
exec "$root/scripts/frame.sh" -C hands/rec 'set -e; mkdir -p build/include
openvr=v2.15.6
[ -f build/include/openvr-$openvr ] || { curl -fsSL "https://raw.githubusercontent.com/ValveSoftware/openvr/$openvr/headers/openvr.h" -o build/include/openvr.h && touch build/include/openvr-$openvr; }
stb=2c980bb59875b0d32144a71867fbdebb2f77cd20
[ -f build/include/stb-$stb ] || { curl -fsSL "https://raw.githubusercontent.com/nothings/stb/$stb/stb_truetype.h" -o build/include/stb_truetype.h && touch build/include/stb-$stb; }
[ -f build/include/stb_image-$stb ] || { curl -fsSL "https://raw.githubusercontent.com/nothings/stb/$stb/stb_image.h" -o build/include/stb_image.h && touch build/include/stb_image-$stb; }
g++ -std=c++17 -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -Ibuild/include $(pkg-config --cflags gbm libdrm) \
-o build/ft-handpanel panel/ft-handpanel.cpp -L/opt/steamvr/bin/linuxarm64 -lopenvr_api -Wl,-rpath,/opt/steamvr/bin/linuxarm64 \
$(pkg-config --libs gbm libdrm) -lpthread
echo "built build/ft-handpanel"'
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# Launch the Frametop Hand Recorder from a Plasma session on the Frame host.
# The app runs in the dev container (PySide6, Kirigami and zstd come from Fedora there).
# podman needs the real XDG_RUNTIME_DIR and the real user bus (to reach systemd for
# the container's cgroup; the Frametop session runs on a private bus from
# dbus-run-session). The session's Wayland socket and bus go to the app itself.
# Options go to ft_handrec.py: --base DIR, --page NAME, and --dry-run for testing.
here=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
wl=${WAYLAND_DISPLAY:-wayland-0}
case $wl in /*) ;; *) wl="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/$wl" ;; esac
session_bus=${DBUS_SESSION_BUS_ADDRESS:-}
export XDG_RUNTIME_DIR=/run/user/$(id -u)
export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus
# From the home folder: the app's host commands (distrobox-host-exec) run in its folder on the
# host, and a folder only the container has, such as /run/host/tmp, makes them all fail.
cd "$HOME" || exit 1
"$here/../../scripts/container-up.sh"
exec "$HOME/.local/bin/distrobox" enter dev -- env WAYLAND_DISPLAY="$wl" DISPLAY="${DISPLAY:-}" \
XAUTHORITY="${XAUTHORITY:-}" DBUS_SESSION_BUS_ADDRESS="$session_bus" \
QT_QPA_PLATFORM="wayland;xcb" \
python3 "$here/ft_handrec.py" "$@"
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=Frametop Hand Recorder
GenericName=Record your hands for the hand dataset
Comment=Record, review and export hand recordings for Frametop's open hand dataset
Exec=@REPO@/hands/rec/ft-handrec
Icon=camera-video
Categories=Utility;
Keywords=hands;hand tracking;dataset;record;frametop;
+1214
View File
File diff suppressed because it is too large. Load diff
+468
View File
@@ -0,0 +1,468 @@
#!/usr/bin/env python3
"""Upload a hand recorder export to the hand dataset on Hugging Face (DESIGN.md "Upload").
The window runs this as a child process (so Cancel can end it, and huggingface_hub stays out
of the window's process); it also runs from the command line. It uses huggingface_hub (in the
dev container: python3-huggingface-hub, from setup/dev-container.sh) with the login that
`hub.py login` (the window's Log in) or `hf auth login` saved. Nobody types a token anywhere.
`login` is huggingface_hub's browser login (OAuth device code, as `hf auth login` does): it gets a
link and a short code, the person enters the code in their browser and approves, and the token goes
straight from Hugging Face into huggingface_hub's token file. This process saves it; it never
prints it, and the window never sees it.
An upload:
1. checks the export with validate.py, and stops on errors;
2. stops if this export (same SHA256SUMS) was uploaded before, unless --again;
3. stops while CONSENT.md or UPLOAD.md is a draft, unless FT_HANDREC_ALLOW_UPLOAD=1;
4. checks the login (whoami: a read-only token can't open a pull request) and access to the
dataset (auth_check: a gated dataset's terms must be accepted first);
5. opens the pull request first (a draft, empty), so its link can be shown while the files go,
and records it under "uploads" in session.json with "status": "started";
6. upload_folder(..., revision="refs/pr/N") to contributions/<contributor>/<session>; a retry of
the same export goes on in the same pull request while it's still open;
7. marks the record {"repo", "pr_url", "pr_num", "uploaded", "export_sha", "status": "done"}.
--dry-run does all of it except the network calls (4 to 6) and recording (5, 7), and says what
it would upload.
The dataset is HF_DATASET; FT_HANDREC_DATASET overrides it (a test repo, for rehearsals).
usage: hub.py [--base DIR] whoami [--json]
hub.py [--base DIR] login [--json]
hub.py [--base DIR] upload SESSION [--dry-run] [--again] [--json]
With --json, each line of output is one JSON object: {"phase", "text", "fraction"} as it goes,
with {"phase": "opened", "pr_url"} once the pull request exists, then {"done": {...}} or
{"error": {"kind", "text", "link", "errors"}}. login says {"phase": "code", "url", "code",
"expires_in"} once it has the link, then {"done": {"name", "role"}}. Exit status 0: done.
"""
import argparse
import datetime
import hashlib
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import takes # noqa: E402 (next to this file)
# The dataset contributions go to (DESIGN.md "Licensing and consent").
HF_DATASET = "DeeJanuz/frametop-hands"
DATASET_ENV = "FT_HANDREC_DATASET"
ALLOW_ENV = "FT_HANDREC_ALLOW_UPLOAD"
CONSENT_PATH = os.path.join(HERE, "CONSENT.md")
UPLOAD_PATH = os.path.join(HERE, "UPLOAD.md")
REPO_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$")
TOKENS_URL = "https://huggingface.co/settings/tokens"
# Quiet huggingface_hub: no progress bars on stderr, no telemetry or update hints.
HF_ENV = {"HF_HUB_DISABLE_PROGRESS_BARS": "1", "HF_HUB_DISABLE_TELEMETRY": "1", "HF_HUB_DISABLE_UPDATE_CHECK": "1"}
class HubError(Exception):
"""What went wrong, for people: kind (below), text, a link to open, validation errors.
Kinds: missing (no huggingface_hub), login, read-token, terms, not-found, permission,
network, hub, invalid, duplicate, closed, no-export."""
def __init__(self, kind, text, link="", errors=None, extra=None):
super().__init__(text)
self.kind, self.text, self.link = kind, text, link
self.errors = errors or []
self.extra = extra or {}
def as_dict(self):
return dict(self.extra, kind=self.kind, text=self.text, link=self.link, errors=self.errors)
def dataset_id():
"""HF_DATASET, or FT_HANDREC_DATASET when set."""
repo = os.environ.get(DATASET_ENV, "").strip() or HF_DATASET
if not REPO_RE.match(repo):
raise HubError("not-found", f"{DATASET_ENV}={repo!r} isn't a dataset id like owner/name")
return repo
def dataset_url(repo=None):
return "https://huggingface.co/datasets/" + (repo or dataset_id())
def is_draft(path):
try:
with open(path, encoding="utf-8") as f:
return "DRAFT" in f.readline()
except OSError:
return False
def texts_draft():
return is_draft(CONSENT_PATH) or is_draft(UPLOAD_PATH)
def upload_allowed():
"""Real uploads: once the texts aren't drafts, or for the maintainer's rehearsal against a
test repo (FT_HANDREC_ALLOW_UPLOAD=1)."""
return not texts_draft() or os.environ.get(ALLOW_ENV) == "1"
def now_iso():
return datetime.datetime.now().astimezone().isoformat(timespec="seconds")
# ---------------------------------------------------------------- records in session.json
def export_sha(export_dir):
"""The export's identity: the SHA256 of its SHA256SUMS ("" if there's none)."""
try:
with open(os.path.join(export_dir, "SHA256SUMS"), "rb") as f:
return hashlib.sha256(f.read()).hexdigest()
except OSError:
return ""
def uploads(store, session):
meta = takes.read_json(os.path.join(store.session_dir(session), "session.json"))
return [u for u in meta.get("uploads") or [] if isinstance(u, dict)]
def previous_upload(store, session, sha):
"""The latest finished upload of this same export, or None. (Records from before
2026-10-03 have no status: they were written only when an upload finished.)"""
same = [u for u in uploads(store, session) if sha and u.get("export_sha") == sha
and u.get("status", "done") == "done"]
return same[-1] if same else None
def unfinished_upload(store, session, sha, repo):
"""The latest upload of this same export to repo that opened its pull request and didn't
finish, or None."""
same = [u for u in uploads(store, session) if sha and u.get("export_sha") == sha and u.get("repo") == repo
and u.get("status") == "started" and u.get("pr_num")]
return same[-1] if same else None
def record_upload(store, session, record):
"""Add record to session.json's "uploads". The file keeps its time: an upload doesn't
change the recordings, so the export mustn't count as out of date because of it
(takes.Store.sessions compares times)."""
path = os.path.join(store.session_dir(session), "session.json")
try:
st = os.stat(path)
except OSError:
st = None
meta = takes.read_json(path)
records = meta.setdefault("uploads", [])
same = [i for i, u in enumerate(records) if isinstance(u, dict) and record.get("pr_num")
and u.get("pr_num") == record["pr_num"] and u.get("repo") == record.get("repo")]
if same:
records[same[-1]] = record # the same pull request: started, then done
else:
records.append(record)
takes.write_json(path, meta)
if st:
os.utime(path, ns=(st.st_atime_ns, st.st_mtime_ns))
# ---------------------------------------------------------------- the pull request's text
def describe(summary, report, sha, nbytes):
"""(commit message, commit description) from validate's summary of the manifest."""
s = summary
objects = ", ".join(s.get("objects") or []) or "none"
if s.get("own_objects"):
objects += f" (+{s['own_objects']} of their own)"
message = f"Hands: session {s.get('session')} from {s.get('contributor')}"
lines = ["Contribution to the Frametop hand dataset, uploaded from the hand recorder.", "",
f"- Session: {s.get('session')}",
f"- Contributor: {s.get('contributor')}",
f"- Takes: {s.get('takes')} ({s.get('minutes')} minutes, {s.get('sets')} frame sets)",
f"- Lighting: {s.get('lighting') or 'not given'}",
f"- Objects: {objects}",
f"- Controllers: {s.get('controllers') or 'not given'}",
f"- Consent version: {s.get('consent_version')}",
f"- Tool: {s.get('tool')}",
f"- Size: {takes.human_bytes(nbytes)}",
f"- SHA256 of SHA256SUMS: {sha}", "",
"Checked with hands/rec/validate.py: no errors" + (f", {len(report.warnings)} warnings:"
if report.warnings else ".")]
lines += [f"- {w}" for w in report.warnings]
return message, "\n".join(lines) + "\n"
# ---------------------------------------------------------------- talking to the Hub
def _hf():
os.environ.update({k: v for k, v in HF_ENV.items() if k not in os.environ})
try:
import huggingface_hub
except ImportError:
raise HubError("missing", "huggingface_hub isn't installed in the dev container: run setup/dev-container.sh "
"(or: pip install --user huggingface_hub)") from None
return huggingface_hub
def explain(e, repo):
"""A huggingface_hub (or network) exception as a HubError."""
if isinstance(e, HubError):
return e
try:
from huggingface_hub import errors as hf
except ImportError:
hf = None
url = dataset_url(repo)
if hf is not None:
if isinstance(e, hf.LocalTokenNotFoundError):
return HubError("login", "You're not logged in to Hugging Face. Press Log in.")
if isinstance(e, hf.GatedRepoError):
return HubError("terms", f"Accept the dataset's terms first: open {url}, read them and accept them, "
"then try again.", url)
if isinstance(e, hf.RepositoryNotFoundError):
return HubError("not-found", f"The dataset {repo} wasn't found, or it's private and your account has "
"no access to it.", url)
if isinstance(e, hf.HfHubHTTPError):
status = getattr(getattr(e, "response", None), "status_code", None)
first = str(e).strip().splitlines()[0] if str(e).strip() else type(e).__name__
if status == 401:
return HubError("login", "Hugging Face didn't accept your login (it may have expired or been "
"revoked). Log in again.")
if status == 403:
return HubError("permission", "Your login isn't allowed to open a pull request. Log in again, "
"and allow everything the Hugging Face page asks for.")
return HubError("hub", f"Hugging Face refused the upload ({status or 'no status'}): {first}")
try:
import httpx
net = (httpx.TransportError, OSError)
except ImportError:
net = (OSError,)
if isinstance(e, net):
return HubError("network", f"Couldn't reach huggingface.co ({type(e).__name__}: {e}). Check the network "
"and try again: files already sent usually aren't sent twice.")
return HubError("hub", f"{type(e).__name__}: {e}")
def whoami():
"""{"name", "role"} for the saved login; HubError if there's none or it doesn't work.
role: "write", "read", "fineGrained" or ""."""
hf = _hf()
try:
info = hf.HfApi().whoami()
except Exception as e:
raise explain(e, dataset_id()) from None
token = ((info.get("auth") or {}).get("accessToken") or {})
return {"name": info.get("name", ""), "role": token.get("role", "")}
def login(progress=None):
"""The browser login: progress("code", text, url=, code=, expires_in=) once the link is ready,
then wait (up to the code's expiry: 5 minutes on 2026-10-03) for the person to approve it, and save
the token. Returns whoami(). Uses huggingface_hub's own device code helpers (1.x)."""
tell = progress or (lambda phase, text, **extra: None)
_hf()
try:
from huggingface_hub._login import _save_oauth_token
from huggingface_hub.errors import DeviceCodeError
from huggingface_hub.utils._oauth_device import poll_device_token, request_device_code
except ImportError:
raise HubError("missing", "This huggingface_hub has no browser login: update the dev container "
"(setup/dev-container.sh).") from None
try:
info = request_device_code()
tell("code", "Approve the login in your browser", url=info["verification_uri_complete"],
code=info["user_code"], expires_in=info["expires_in"])
_save_oauth_token(poll_device_token(info))
except DeviceCodeError as e:
raise HubError("login", f"The login didn't go through: {e}. Press Log in to try again.") from None
except Exception as e:
raise explain(e, dataset_id()) from None
return whoami()
def upload(store, session, dry_run=False, again=False, progress=None, log=None):
"""Upload exports/<session> (the steps in this file's docstring). progress(phase, text,
fraction or None); log(text) for the dry run's account. Returns the result; raises HubError."""
tell = progress or (lambda phase, text, fraction=None, **extra: None)
say = log or (lambda text: None)
import validate
repo = dataset_id()
try:
export = store.export_dir(session)
except ValueError as e:
raise HubError("no-export", str(e)) from None
if not os.path.isfile(os.path.join(export, "manifest.json")):
raise HubError("no-export", f"No export of session {session}: export it first")
tell("check", "Checking the export", 0.0)
report = validate.validate(export, progress=lambda f, text: tell("check", text, f))
if not report.ok:
raise HubError("invalid", f"The export has {len(report.errors)} problems, so it can't be uploaded. Export "
"the session again; if that doesn't help, report it.", errors=report.errors)
summary = report.summary
contributor = summary.get("contributor", "")
sha = export_sha(export)
before = previous_upload(store, session, sha)
if before and not again:
raise HubError("duplicate", f"This export was uploaded already, on {before.get('uploaded', '?')}: "
f"{before.get('pr_url', '')}", before.get("pr_url", ""), extra={"previous": before})
if not dry_run and not upload_allowed():
raise HubError("closed", "Contributions aren't open yet: the texts are drafts waiting for a legal review. "
f"(For a rehearsal against a test repo: {ALLOW_ENV}=1.)")
path_in_repo = f"contributions/{contributor}/{session}"
message, description = describe(summary, report, sha, report.bytes)
files = []
for root, _, names in os.walk(export):
files += [os.path.relpath(os.path.join(root, n), export) for n in names]
plan = {"repo": repo, "repo_type": "dataset", "folder_path": export, "path_in_repo": path_in_repo,
"create_pr": True, "commit_message": message, "commit_description": description,
"files": len(files), "bytes": report.bytes, "warnings": report.warnings}
if dry_run:
say(f"dry run: would check the login (whoami) and access to {repo} (auth_check)")
say(f"dry run: would upload_folder {len(files)} files, {takes.human_bytes(report.bytes)}, "
f"from {export} to datasets/{repo}/{path_in_repo}, as a pull request")
for rel in sorted(files):
say(f" {rel} {takes.human_bytes(os.path.getsize(os.path.join(export, rel)))}")
say(f"dry run: commit message: {message}")
say("dry run: commit description:\n" + description.rstrip())
record = {"repo": repo, "pr_url": "", "uploaded": now_iso(), "export_sha": sha, "status": "done"}
say(f"dry run: would record in session.json's uploads: {json.dumps(record)}")
tell("done", "Dry run: nothing was uploaded", 1.0)
return dict(plan, dry_run=True, pr_url="", record=record)
hf = _hf()
api = hf.HfApi()
tell("login", "Checking your Hugging Face login", None)
try:
who = api.whoami()
except Exception as e:
raise explain(e, repo) from None
role = ((who.get("auth") or {}).get("accessToken") or {}).get("role", "")
if role == "read":
raise HubError("read-token", "Your saved login is a read-only token, so it can't open a pull request. "
"Log in again.")
tell("access", f"Checking access to {repo}", None)
try:
api.auth_check(repo, repo_type="dataset")
except Exception as e:
raise explain(e, repo) from None
# The pull request first, so its link shows while the files go (and the person can plug the
# headset in and leave it). A retry of this export goes on in its pull request if it's open.
tell("open", "Opening your pull request", None)
pr = None
before = unfinished_upload(store, session, sha, repo)
if before:
try:
d = api.get_discussion_details(repo, int(before["pr_num"]), repo_type="dataset")
if d.is_pull_request and d.status in ("draft", "open"):
pr = d
except Exception:
pr = None
if pr is None:
try:
pr = api.create_pull_request(repo, message, description=description, repo_type="dataset")
except Exception as e:
raise explain(e, repo) from None
pr_url = getattr(pr, "url", "") or f"{dataset_url(repo)}/discussions/{pr.num}"
record = {"repo": repo, "pr_url": pr_url, "pr_num": pr.num, "started": now_iso(), "export_sha": sha,
"status": "started"}
record_upload(store, session, record)
tell("opened", f"Pull request #{pr.num} is open. Uploading {len(files)} files ({takes.human_bytes(report.bytes)})",
None, pr_url=pr_url)
try:
api.upload_folder(repo_id=repo, repo_type="dataset", folder_path=export, path_in_repo=path_in_repo,
revision=f"refs/pr/{pr.num}", commit_message=message, commit_description=description)
except Exception as e:
raise explain(e, repo) from None
try: # a pull request opened through the API stays a draft until it's marked open
if api.get_discussion_details(repo, pr.num, repo_type="dataset").status == "draft":
api.change_discussion_status(repo, pr.num, "open", repo_type="dataset")
except Exception:
pass # the maintainer can open it
record = dict(record, uploaded=now_iso(), status="done")
record_upload(store, session, record)
tell("done", "Uploaded", 1.0)
return dict(plan, dry_run=False, pr_url=pr_url, pr_num=pr.num, user=who.get("name", ""), record=record)
# ---------------------------------------------------------------- the command line
def main():
ap = argparse.ArgumentParser(description="Upload a hand recorder export to the hand dataset on Hugging Face.")
ap.add_argument("--base", default=takes.DEFAULT_BASE)
sub = ap.add_subparsers(dest="cmd", required=True)
w = sub.add_parser("whoami", help="show the saved Hugging Face login")
w.add_argument("--json", action="store_true")
li = sub.add_parser("login", help="log in to Hugging Face in the browser")
li.add_argument("--json", action="store_true")
u = sub.add_parser("upload", help="upload exports/SESSION as a pull request")
u.add_argument("session")
u.add_argument("--dry-run", action="store_true", help="no network: say what would be uploaded")
u.add_argument("--again", action="store_true", help="upload even if this export was uploaded before")
u.add_argument("--json", action="store_true", help="JSON lines, for the window")
a = ap.parse_args()
def emit(obj):
print(json.dumps(obj), flush=True)
try:
if a.cmd == "whoami":
who = whoami()
if a.json:
emit({"done": who})
else:
print(f"logged in as {who['name']} (token role: {who['role'] or 'unknown'})")
return 0
if a.cmd == "login":
def code(phase, text, **extra):
if a.json:
emit(dict(extra, phase=phase, text=text))
else:
print(f"Open {extra['url']} and approve the code {extra['code']}. Waiting...", flush=True)
who = login(code)
if a.json:
emit({"done": who})
else:
print(f"logged in as {who['name']}")
return 0
if a.json:
def progress(phase, text, fraction=None, **extra):
emit(dict(extra, phase=phase, text=text, fraction=fraction))
def log(text):
emit({"log": text})
else:
last = {}
def progress(phase, text, fraction=None, **extra):
if extra.get("pr_url"):
print(f"pull request: {extra['pr_url']}", flush=True)
line = text if fraction is None else f"{fraction * 100:5.1f}% {text}"
if (phase, text) != last.get("key") or fraction in (0.0, 1.0):
print(line, file=sys.stderr, flush=True)
last["key"] = (phase, text)
def log(text):
print(text, flush=True)
if hasattr(os, "setpriority"):
try:
os.setpriority(os.PRIO_PROCESS, 0, 19) # validation reads and hashes everything: stay out of VR's way
except OSError:
pass
result = upload(takes.Store(a.base), a.session, dry_run=a.dry_run, again=a.again, progress=progress, log=log)
if a.json:
emit({"done": result})
elif result["dry_run"]:
print(f"dry run done: {result['files']} files would go to datasets/{result['repo']}/{result['path_in_repo']}")
else:
print(f"uploaded: {result['pr_url']}")
return 0
except HubError as e:
if a.json:
emit({"error": e.as_dict()})
else:
print(f"error ({e.kind}): {e.text}", file=sys.stderr)
for line in e.errors:
print(f" {line}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Install the hand recorder on a Frame that has Frametop (get.sh --experimental): bring the dev
# container's packages up to date, build hand tracking's camera broker and tracker (hands/build.sh:
# the first build fetches and builds ncnn, a few minutes) and the headset panel (hands/rec/build.sh),
# give ft-camd its capabilities (hands/run.sh caps: asks for the password, once per build), and add
# "Frametop Hand Recorder" to the app menu (for Frametop's desktop: it isn't tested from SteamVR's
# "Launch a program", which runs apps outside it; the standalone recorder is for that).
# It doesn't turn on Frametop's live hand tracking (that's hands/run.sh install, still deferred).
# Usage: hands/rec/install.sh install or update
# hands/rec/install.sh uninstall remove the menu entry (recordings stay where they are)
set -euo pipefail
root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
. "$root/scripts/_env.sh"
entry='~/.local/share/applications/frametop-handrec.desktop'
case ${1:-install} in
install)
echo "== 1/4 dev container packages"
"$root/setup/dev-container.sh"
echo "== 2/4 hand tracking: ft-camd and ft-hands"
"$root/hands/build.sh"
echo "== 3/4 the headset panel: ft-handpanel"
"$root/hands/rec/build.sh"
echo "== 4/4 ft-camd's capabilities (asks for your password) and the menu entry"
"$root/hands/run.sh" caps
fill_template "$root/hands/rec/ft-handrec.desktop" |
on_frame "mkdir -p ~/.local/share/applications && cat > $entry"
echo
echo "Installed. On Frametop's desktop, open \"Frametop Hand Recorder\" from the app menu."
echo "Recordings go to ~/.local/share/frametop/hands/contrib."
;;
uninstall)
on_frame "rm -f $entry"
echo "Removed the menu entry. Your recordings are still in ~/.local/share/frametop/hands/contrib:"
echo "delete that folder to remove them."
;;
*) echo "usage: $0 [install|uninstall]" >&2; exit 2 ;;
esac
+1846
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
# Pose images for the hand recorder
Small pictures of each hand pose in `script.json`, shown on the headset panel next to the prompt text.
- `<id>.png`: one image per pose, 512x512 RGBA with a transparent background. Made for a dark panel and still readable at about 250 px.
- `poses.json`: maps each pose id to `{"file", "two_hands", "caption"}`.
- `contact-sheet.png`: every image in a grid with its id, for review. The panel doesn't use it.
- `make_poses.py`: the generator that makes all of the above.
## How the images are drawn
Every image shows a right hand as the wearer sees it from their own eyes. "Palm toward you" shows the palm, with its creases. "Back toward you" shows the back of the hand, with the nails and knuckles. Fingers point up unless the pose says otherwise.
- **Left-hand prompts:** the panel mirrors the image horizontally.
- **"Both" prompts:** the panel shows two copies, one of them mirrored.
- **`two_hands: true`:** the image already shows the whole scene: both hands, or one hand with an object, as in `hold`. Show it once, without mirroring or copying. This applies to `cross`, `overlap`, `near-face`, `typing`, `lift`, `switch`, `hold`, `push`, `push-controller`, `touch-stick` and `touch-stick-desk`.
- **`touch-stick`:** shows the left hand holding the controller while the right index touches its thumbstick. For prompts where the right hand holds the controller (`controllers: ["right"]`), mirror it.
`push` and `push-controller` are side views: the wearer's head with a headset on, one arm out in front with the palm out, a ghost of the hand further out, and a straight double arrow from the headset outward, labelled "near" and "arm out". The labels use Pillow's built-in font.
Other motion poses show the start pose, a faint blue "ghost" of the end pose, and orange arrows. Objects (keyboard, mouse, bottle, bar, controller, screen, head and headset) are plain grey shapes.
Besides the pose ids in `script.json`, these extra ids exist for prompts that need a different picture:
| id | for |
| --- | --- |
| `push` | the bar sections: push straight out from the headset and back, palms out |
| `push-controller` | the same with controllers on |
| `touch-stick-desk` | touching the thumbstick of a controller lying on the desk |
| `no-hands` | the no-hands section: hands down, out of view |
| `open-close` | already used by the bar sections |
`count-5` is the same picture as `spread`.
## Regenerating
You need Python 3 with numpy and Pillow. The script uses about one core-minute per image at the default quality, so don't run it on the headset. Run it on a build machine:
```sh
python3 -m venv venv && venv/bin/pip install numpy pillow
venv/bin/python make_poses.py --jobs 6 # all images, poses.json, contact sheet
venv/bin/python make_poses.py --only fist,ok # just some (poses.json is left alone)
venv/bin/python make_poses.py --ss 1 --jobs 6 # rough and about 8x faster, for trying things
```
`--out DIR` writes somewhere other than this folder.
Each pose is a short entry in the `POSES` table in `make_poses.py`: a caption, the `two_hands` flag, and a function that returns the scene. A scene is the camera, layers of hands and objects (a layer can be a faint ghost), and arrows. Hands are built from joint angles: flexion at each finger's three joints, sideways spread, and four thumb angles. A thumb can also be given a target point, such as "touch the index fingertip", and a small solver finds the angles. The presets near `FLAT`, `FIST` and `OK` are a good place to start a new pose.
## License
MIT, like the rest of the repository. The script draws everything itself. A hand made of a palm slab and tapered capsules is ray-marched as a signed distance field, then shaded and outlined. No photos, downloaded images, scanned or research hand models, or AI image generators are involved, so the images carry no other terms.
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 711 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

+182
View File
@@ -0,0 +1,182 @@
{
"flat": {
"file": "flat.png",
"two_hands": false,
"caption": "Palm toward you, fingers together"
},
"flat-back": {
"file": "flat-back.png",
"two_hands": false,
"caption": "Back of the hand toward you"
},
"spread": {
"file": "spread.png",
"two_hands": false,
"caption": "Fingers spread wide"
},
"open": {
"file": "open.png",
"two_hands": false,
"caption": "Open and relaxed"
},
"fist": {
"file": "fist.png",
"two_hands": false,
"caption": "A fist"
},
"point": {
"file": "point.png",
"two_hands": false,
"caption": "Point with your index finger"
},
"pinch": {
"file": "pinch.png",
"two_hands": false,
"caption": "Thumb and index tips touching"
},
"ok": {
"file": "ok.png",
"two_hands": false,
"caption": "OK sign: a ring, three fingers up"
},
"thumbs-up": {
"file": "thumbs-up.png",
"two_hands": false,
"caption": "Thumbs up"
},
"claw": {
"file": "claw.png",
"two_hands": false,
"caption": "Fingers curled like a claw"
},
"count-1": {
"file": "count-1.png",
"two_hands": false,
"caption": "One: index finger"
},
"count-2": {
"file": "count-2.png",
"two_hands": false,
"caption": "Two: index and middle"
},
"count-3": {
"file": "count-3.png",
"two_hands": false,
"caption": "Three: index, middle, ring"
},
"count-4": {
"file": "count-4.png",
"two_hands": false,
"caption": "Four: thumb folded in"
},
"count-5": {
"file": "count-5.png",
"two_hands": false,
"caption": "Five: all fingers spread"
},
"turn-in-out": {
"file": "turn-in-out.png",
"two_hands": false,
"caption": "Turn your wrist: palm in, palm out"
},
"turn-up-down": {
"file": "turn-up-down.png",
"two_hands": false,
"caption": "Palm down, turn it up, then back"
},
"bend": {
"file": "bend.png",
"two_hands": false,
"caption": "Bend your wrist up, down, side to side"
},
"pinch-tap": {
"file": "pinch-tap.png",
"two_hands": false,
"caption": "Tap thumb and index together"
},
"pinch-drag": {
"file": "pinch-drag.png",
"two_hands": false,
"caption": "Pinch, move to the side, let go"
},
"grab": {
"file": "grab.png",
"two_hands": false,
"caption": "Close your hand around a bar, open it"
},
"open-close": {
"file": "open-close.png",
"two_hands": false,
"caption": "Open and close your hand"
},
"cross": {
"file": "cross.png",
"two_hands": true,
"caption": "Cross your hands, then uncross"
},
"overlap": {
"file": "overlap.png",
"two_hands": true,
"caption": "One hand over the other, slide around"
},
"near-face": {
"file": "near-face.png",
"two_hands": true,
"caption": "Hands near your face, not touching"
},
"screen-point": {
"file": "screen-point.png",
"two_hands": false,
"caption": "Point at a screen at arm's length"
},
"typing": {
"file": "typing.png",
"two_hands": true,
"caption": "Type on the keyboard"
},
"lift": {
"file": "lift.png",
"two_hands": true,
"caption": "Lift your hands off the keyboard, put them back"
},
"mouse": {
"file": "mouse.png",
"two_hands": false,
"caption": "Hand on the mouse, move and click"
},
"switch": {
"file": "switch.png",
"two_hands": true,
"caption": "Switch between keyboard and mouse"
},
"hold": {
"file": "hold.png",
"two_hands": true,
"caption": "Pick it up, use it, put it down"
},
"push": {
"file": "push.png",
"two_hands": true,
"caption": "Push straight out, away from the headset, and back"
},
"push-controller": {
"file": "push-controller.png",
"two_hands": true,
"caption": "Controllers on: push straight out from the headset, and back"
},
"touch-stick": {
"file": "touch-stick.png",
"two_hands": true,
"caption": "Touch the thumbstick with your other index"
},
"touch-stick-desk": {
"file": "touch-stick-desk.png",
"two_hands": true,
"caption": "Touch the thumbstick of the controller on the desk"
},
"no-hands": {
"file": "no-hands.png",
"two_hands": false,
"caption": "Hands down, out of view"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

+211
View File
@@ -0,0 +1,211 @@
#!/usr/bin/env bash
# The hand recorder end to end, without the headset (DESIGN.md "Upload"): a short stretch of
# an ft-hands recording plays into a camera ring (ft-ringplay), a session records it with a
# short test script (session.py, the panel as ft-handpanel --no-vr, a tracking ft-hands),
# takes.py exports it, validate.py checks the export, and hub.py uploads it: a dry run by
# default, or for real to a (test) dataset with --repo.
#
# hands/rec/rehearse.sh [--repo ID] [--capture DIR] [--from S] [--prompt-seconds N] [--keep]
#
# --repo ID upload for real to this dataset, as a pull request. While the texts are
# drafts that also needs FT_HANDREC_ALLOW_UPLOAD=1 in the environment.
# --capture DIR the recording to play (default the frame-hands capture
# rec-20260930-103803-lit); --from S: start this far into it (60)
# --prompt-seconds N each test step's length (3): a prompt, a two-cue sweep, no hands. The
# session runs in step mode, Next pressed by itself (--next-after): each
# step is a recording part of its own, with its 3 s countdown, so about
# 18 s are recorded in all, a few hundred MB before compression
# --keep keep the temporary folders (camera images of a room: delete them after)
#
# It runs in the dev container (where ft-hands, ft-handpanel, zstd and huggingface_hub are),
# and in one frame-job scope when frame-job is installed, so it stays capped while the headset
# is worn. Everything goes in temporary folders that are deleted at the end, and every process
# it started is stopped, also on Ctrl+C. A tracking ft-hands that's already running is used as
# it is; otherwise one is started for the rehearsal (it publishes the usual hands file).
set -euo pipefail
here=$(cd "$(dirname "$(readlink -f "$0")")" && pwd)
root=$(cd "$here/../.." && pwd)
uid=$(id -u)
if [ ! -e /run/.containerenv ]; then
"$root/scripts/container-up.sh"
# Ctrl+C and kill don't reach through distrobox: the rehearsal inside writes its PID to this
# file, and a signal here is passed on to it, so it still cleans up.
pidfile=$(mktemp "/run/user/$uid/ft-handrec-rehearse-pid.XXXXXX")
# The real user bus, so frame-job's systemd-run reaches the host's user manager.
"$HOME/.local/bin/distrobox" enter dev -- env DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$uid/bus" \
XDG_RUNTIME_DIR="/run/user/$uid" FT_REHEARSE_PIDFILE="$pidfile" bash "$here/rehearse.sh" "$@" </dev/null &
child=$! stopping=0 status=0
pass_on() { [ -s "$pidfile" ] && kill -TERM "$(cat "$pidfile")" 2>/dev/null; return 0; }
trap 'stopping=1; pass_on' INT TERM HUP
while kill -0 "$child" 2>/dev/null; do
wait "$child" && status=0 || status=$? # (set -e would end this on a signal)
[ "$stopping" = 0 ] || pass_on
done
rm -f "$pidfile"
exit "$status"
fi
if [ -z "${FT_REHEARSE_SCOPE:-}" ] && command -v frame-job >/dev/null; then
export FT_REHEARSE_SCOPE=1
cd /tmp # no .frame-job up from here: it runs locally, capped
exec frame-job --local -- bash "$here/rehearse.sh" "$@"
fi
[ -z "${FT_REHEARSE_PIDFILE:-}" ] || echo $$ >"$FT_REHEARSE_PIDFILE"
repo="" capture="$HOME/Desktop/Projects/frame-hands/captures/rec-20260930-103803-lit" from=60 prompt_s=3 keep=0
while [ $# -gt 0 ]; do
case $1 in
--repo) repo=$2; shift 2 ;;
--capture) capture=$2; shift 2 ;;
--from) from=$2; shift 2 ;;
--prompt-seconds) prompt_s=$2; shift 2 ;;
--keep) keep=1; shift ;;
-h|--help) sed -n '2,/^set -euo/p' "$0" | sed '$d; s/^# \{0,1\}//'; exit 0 ;;
*) echo "rehearse: unknown option $1" >&2; exit 2 ;;
esac
done
ringplay=$root/hands/build/ft-ringplay
hands=$root/hands/build/ft-hands
panel=$here/build/ft-handpanel
for b in "$ringplay" "$hands"; do
[ -x "$b" ] || { echo "rehearse: $b isn't built: hands/build.sh --tools" >&2; exit 1; }
done
[ -x "$panel" ] || { echo "rehearse: $panel isn't built: hands/rec/build.sh" >&2; exit 1; }
[ -f "$capture/sets.bin" ] || { echo "rehearse: no recording in $capture" >&2; exit 1; }
if pgrep -x ft-handpanel >/dev/null; then
echo "rehearse: an ft-handpanel is running (a real session?): try again when it's done" >&2
exit 1
fi
if [ -n "$repo" ]; then
if python3 -c "import sys; sys.path.insert(0, '$here'); import hub; sys.exit(0 if hub.upload_allowed() else 1)"; then :; else
echo "rehearse: the texts are drafts: a real upload needs FT_HANDREC_ALLOW_UPLOAD=1 as well as --repo" >&2
exit 1
fi
python3 -c "import huggingface_hub" 2>/dev/null || {
echo "rehearse: huggingface_hub isn't installed: setup/dev-container.sh" >&2; exit 1; }
fi
# The data: the ring in the runtime folder (memory), the rest in /tmp. Both go at the end.
work=$(mktemp -d "${TMPDIR:-/tmp}/ft-handrec-rehearse.XXXXXX")
ringdir=$(mktemp -d "/run/user/$uid/ft-handrec-rehearse.XXXXXX")
base=$work/base ring=$ringdir/cam-ring logs=$work/logs
mkdir -p "$base" "$logs"
pids=()
cleanup() {
local code=$?
# Finish even if more signals come: frame-job stops its scope with SIGTERM to every process
# in it when it's interrupted.
trap '' INT TERM HUP
trap - EXIT
for p in "${pids[@]}"; do kill "$p" 2>/dev/null || true; done
for p in "${pids[@]}"; do wait "$p" 2>/dev/null || true; done
if [ "$keep" = 1 ]; then
echo "kept: $work and $ringdir (camera images of a room: delete them when done)"
else
rm -rf "$work" "$ringdir"
fi
exit "$code"
}
trap cleanup EXIT
trap 'exit 130' INT TERM
t0=$(date +%s)
step() { echo; echo "== $*"; }
# Long steps run in the background and are waited for: a signal then ends the wait at once,
# and cleanup stops them (bash runs traps only after a foreground command ends).
run() { "$@" & local p=$!; pids+=("$p"); wait "$p"; }
indent() { sed 's/^/ /'; }
step "1. Playing ${capture##*/} from ${from} s into $ring"
"$ringplay" "$capture" --ring "$ring" --from "$from" --to "$((from + 30))" --loop >"$logs/ringplay.log" 2>&1 &
pids+=($!)
for _ in $(seq 100); do
python3 -c "import sys; sys.path.insert(0, '$here'); import session
r = session.Ring('$ring'); sys.exit(0 if r.alive() else 1)" 2>/dev/null && break
sleep 0.2
done
python3 -c "import sys; sys.path.insert(0, '$here'); import session
r = session.Ring('$ring'); print(' cameras:', ', '.join('%s %dx%d' % (c['name'], c['width'], c['height']) for c in r.cams))
sys.exit(0 if r.alive() else 1)" || { echo "rehearse: ft-ringplay doesn't publish: $(tail -3 "$logs/ringplay.log")" >&2; exit 1; }
step "2. Session (test script, panel --no-vr)"
tracker=existing
if ! python3 -c "import sys; sys.path.insert(0, '$here'); import session; sys.exit(0 if session.tracker_running() else 1)"; then
"$hands" --ring "$ring" --no-gestures --status 0 >"$logs/tracker.log" 2>&1 &
pids+=($!)
tracker=started
fi
echo " tracker: $tracker"
"$panel" --no-vr >"$logs/panel.log" 2>&1 &
pids+=($!)
python3 - "$here" "$base" "$prompt_s" "$work/script.json" <<'EOF'
import json, os, re, sys, uuid
here, base, secs, out = sys.argv[1], sys.argv[2], float(sys.argv[3]), sys.argv[4]
consent = re.search(r"^Version:\s*(\S+)", open(os.path.join(here, "CONSENT.md")).read(), re.M).group(1)
json.dump({"schema": 1, "contributor": str(uuid.uuid4()),
"consent": {"version": consent, "accepted": "2026-10-02T00:00:00+00:00", "adult": True},
"optional": {"handedness": "", "notes": ""}}, open(os.path.join(base, "profile.json"), "w"))
json.dump({"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Rehearsal", "seconds": 1, "text": "A rehearsal of the hand recorder."},
"done": {"title": "Done", "seconds": 1, "text": "Rehearsal done."},
"stopped": {"title": "Stopped", "seconds": 1, "text": "Rehearsal stopped."},
"sections": [
{"id": "hand-size", "title": "Hand size", "intro": "Rehearsal: hands.",
"prompts": [{"text": "Both hands flat, palms toward you.", "seconds": secs, "hands": "both",
"pose": "flat", "distance": "mid"}]},
{"id": "pose-sweeps", "title": "Hand poses", "kind": "sweep", "intro": "", "cue_s": secs / 2,
"groups": [["open", "fist"]], "sweeps": [{"hands": "both", "group": "next", "text": "Keep moving."}]},
{"id": "no-hands", "title": "No hands", "intro": "",
"prompts": [{"text": "Hands out of view.", "seconds": secs, "hands": "none"}]}]},
open(out, "w"))
EOF
for _ in $(seq 50); do
python3 -c "import sys; sys.path.insert(0, '$here'); import session
sys.exit(0 if session.Panel().cmd('ping', reply=True) else 1)" 2>/dev/null && break
sleep 0.2
done
run python3 "$here/session.py" --ring "$ring" --no-start --base "$base" --script "$work/script.json" --lighting room \
--next-after 0.3 \
</dev/null > >(indent)
sid=$(ls "$base/sessions" | tail -1)
[ -n "$sid" ] || { echo "rehearse: the session left nothing" >&2; exit 1; }
python3 "$here/takes.py" --base "$base" takes "$sid" | sed 's/^/ /'
echo " panel pictures: $(grep -c '^--- picture' "$logs/panel.log" || true)"
step "3. Export"
run python3 "$here/takes.py" --base "$base" export "$sid" >"$logs/export.log"
tr '\r' '\n' <"$logs/export.log" | tail -1 | indent
export_dir=$base/exports/$sid
step "4. Validate"
valid=1
run python3 "$here/validate.py" "$export_dir" --json >"$work/validate.json" || valid=0
python3 -c "import json, sys; v = json.load(open(sys.argv[1]))
for k in ('errors', 'warnings'):
for line in v[k]: print(' %s: %s' % (k[:-1], line))
print(' OK' if v['ok'] else ' %d errors' % len(v['errors']))" "$work/validate.json"
[ "$valid" = 1 ] || { echo "rehearse: the export didn't validate" >&2; exit 1; }
if [ -n "$repo" ]; then
step "5. Upload to $repo (for real)"
run env FT_HANDREC_DATASET="$repo" python3 "$here/hub.py" --base "$base" upload "$sid" >"$logs/hub.log"
indent <"$logs/hub.log"
else
step "5. Upload (dry run: --repo ID uploads for real)"
run python3 "$here/hub.py" --base "$base" upload "$sid" --dry-run >"$logs/hub.log"
indent <"$logs/hub.log"
fi
step "Summary"
python3 - "$work/validate.json" "$logs/hub.log" "$tracker" "$(( $(date +%s) - t0 ))" <<'EOF'
import json, sys
v = json.load(open(sys.argv[1]))
s = v["summary"]
hub = open(sys.argv[2]).read().strip().splitlines()
print(f" session {s['session']}: {s['takes']} takes, {s['sets']} sets, {s['minutes']} min recorded")
print(f" export: {v['bytes'] / 1e6:.1f} MB, {len(v['errors'])} errors, {len(v['warnings'])} warnings")
for w in v["warnings"]:
print(f" warning: {w}")
print(f" hub: {hub[-1] if hub else '-'}")
print(f" tracker: {sys.argv[3]}; took {sys.argv[4]} s")
EOF
+118
View File
@@ -0,0 +1,118 @@
{
"version": 1,
"intro_s": 4,
"between_s": 3,
"welcome": {"title": "Hand recorder", "seconds": 7,
"text": "Follow the steps on this panel. Each one shows what to do with your hands, and where. A bar shows the time left.|The button on the right side of the headset goes on when a step waits for you, and pauses while recording."},
"done": {"title": "All done", "seconds": 6,
"text": "Thank you! You can take off the headset.|Review your recordings in the Hand recorder window."},
"stopped": {"title": "Stopped", "seconds": 4,
"text": "What was recorded so far is saved. Review it in the Hand recorder window."},
"cue_names": {"flat": "Flat", "flat-back": "Backs", "spread": "Spread", "open": "Open", "fist": "Fist",
"point": "Point", "pinch": "Pinch", "ok": "OK", "thumbs-up": "Thumbs up", "claw": "Claw", "count-1": "1",
"count-2": "2", "count-3": "3", "count-4": "4", "count-5": "5", "pinch-tap": "Tap", "pinch-drag": "Drag",
"grab": "Grab", "cross": "Cross", "overlap": "Overlap", "near-face": "Face", "screen-point": "Screen",
"mouse": "Mouse", "switch": "Switch"},
"objects": {"pencil": "pencil or pen", "phone": "phone", "cup": "cup", "keyboard": "keyboard",
"mouse": "mouse", "gamepad": "gamepad", "small": "small thing"},
"sections": [
{"id": "hand-size", "title": "Hand size", "requires": [], "go": "Hold", "quick": true,
"intro": "First, your hand size. Hold each shape still while its picture is lit.",
"defaults": {"hands": "both", "distance": "mid", "position": "centre"},
"prompts": [
{"text": "Both hands about 40 cm away, still. Make each lit shape: flat with palms toward you, then the backs toward you, then fingers spread wide.",
"cues": ["flat", "flat-back", "spread"], "cue_s": 5}
]},
{"id": "pose-sweeps", "title": "Hand poses", "kind": "sweep", "requires": [], "quick": true,
"intro": "Now keep your hands moving slowly while they change shape. A picture lights up every few seconds: make that shape wherever your hands are. Close, far, high, low: all of it helps.",
"cue_s": 4, "step_s": 20,
"groups": [["open", "fist", "point", "pinch"], ["ok", "thumbs-up", "spread", "claw"],
["count-1", "count-2", "count-3", "count-4", "count-5"]],
"sweeps": [
{"hands": "both", "group": "next", "text": "Both hands: move them slowly and keep going, from close to you out to arm's length and all around in front of you. Change shape with the lit picture."},
{"hands": "both", "group": "next", "text": "Both hands again: slowly near and far, high and low, left and right. Change shape with the lit picture."},
{"hands": "both", "group": "next", "text": "Both hands, still moving slowly all around in front of you. Change shape with the lit picture."},
{"hands": "left", "group": "any", "quick": false, "text": "Left hand only, the right one in your lap. Move it slowly near and far and all around, change shape with the lit picture, and turn your wrist as you go: palm toward you, then away."},
{"hands": "right", "group": "any", "quick": false, "text": "Right hand only, the left one in your lap. Move it slowly near and far and all around, change shape with the lit picture, and turn your wrist as you go: palm toward you, then away."}
]},
{"id": "gestures", "title": "Gestures", "kind": "sweep", "requires": [], "shuffle": false, "cycle": false,
"intro": "Now some movements, at a calm, normal pace. Follow the lit picture.",
"defaults": {"hands": "both"},
"sweeps": [
{"id": "pinch", "cues": ["pinch-tap", "pinch-drag"], "cue_s": 8,
"text": "Both hands: tap thumb and index finger together a few times. Then pinch, drag slowly to the side and let go, again and again."},
{"id": "grab-cross", "cues": ["grab", "cross", "overlap"], "cue_s": 6,
"text": "Grab as if holding a bar and open again. Then cross your hands and uncross them. Then hold one over the other and slide them around."},
{"id": "face-screen", "cues": ["near-face", "screen-point"], "cue_s": 8,
"text": "Move your hands close around your face, without touching the headset. Then reach out to where a screen would be and point at things on it."}
]},
{"id": "desk-work", "title": "Desk work", "requires": [],
"intro": "Now your desk. Look down at your hands while you work.",
"defaults": {"hands": "both", "position": "down"},
"prompts": [
{"when": "objects:keyboard", "text": "Type on your keyboard the way you normally do. Any text is fine.", "seconds": 10, "pose": "typing", "object": "keyboard"},
{"when": "!objects:keyboard", "text": "Rest your hands on the desk and pretend to type.", "seconds": 10, "pose": "typing"},
{"when": ["objects:mouse", "objects:keyboard"], "text": "Use your mouse: move it and click. When the picture changes, switch between the mouse and the keyboard a few times.", "cues": ["mouse", "switch"], "cue_s": 6, "object": "mouse"},
{"when": ["objects:mouse", "!objects:keyboard"], "text": "Use your mouse: move it around and click a few times.", "seconds": 10, "hands": "right", "pose": "mouse", "object": "mouse"},
{"when": "!objects:mouse", "text": "Put one hand flat on the desk and slide it around, as if using a mouse.", "seconds": 10, "hands": "right", "pose": "mouse"}
]},
{"id": "objects", "title": "Things you hold", "requires": ["objects"], "for_each": "object",
"skip_objects": ["keyboard", "mouse"],
"intro": "Now the things you set out. Use each one the way you normally would.",
"defaults": {"hands": "both"},
"prompts": [
{"text": "Pick up the {object}, use it for a moment, then put it down.", "seconds": 12, "pose": "hold", "object": "{object}"}
]},
{"id": "touch", "title": "Touch the dot", "kind": "targets", "requires": [], "quick": true,
"intro": "A small dot will appear. Touch it with your index fingertip and hold still until it turns green.",
"defaults": {"hands": "any", "pose": "point"},
"hold_s": 1.0, "timeout_s": 8,
"text": "Touch the dot with your index fingertip and hold still.",
"targets": [[0.00, -0.20, -0.25], [-0.20, -0.10, -0.40], [0.20, -0.10, -0.40], [-0.15, -0.25, -0.35],
[0.25, -0.05, -0.50], [0.05, -0.10, -0.55]]},
{"id": "controller-push", "title": "Depth with controllers", "kind": "bar", "requires": ["controllers"],
"before": {"text": "Put on both controllers and tighten the straps. Take your time.", "seconds": 25},
"intro": "Push both hands straight out in front of you, away from the headset, then pull them back toward it. Only nearer and farther, not sideways. Follow the hollow circle on the bar: right is arm out, left is at your chest. The blue dot is the current hand tracking's guess at how far your hands are. It's only an approximation and often wrong, so ignore it.",
"defaults": {"hands": "both", "pose": "open", "picture": "push-controller", "controller": true, "controllers": ["left", "right"]},
"near_m": 0.2, "far_m": 0.6, "near_label": "At your chest", "far_label": "Arm out", "period_s": 6, "lead_s": 3, "reps": 3,
"heights": [
{"id": "chest", "text": "Chest height, palms out like a stop sign. Push straight out, away from the headset, then pull back to your chest. Follow the hollow circle, not the blue dot."},
{"id": "eye", "text": "Now at eye level, palms out. Push straight out, away from the headset, then pull back toward it. Follow the hollow circle, not the blue dot."}
],
"prompts": [
{"text": "Controllers on: slowly turn your wrists, and open and close your hands, a few times.", "seconds": 10, "pose": "open-close", "distance": "mid"}
]},
{"id": "bridge", "title": "Controller and fingertip", "requires": ["controllers"],
"intro": "Now one controller on and one hand bare. The thumbstick is the point to touch.",
"defaults": {"controller": true},
"prompts": [
{"text": "Left controller on, the right one off on the desk. Touch the left thumbstick with your right index fingertip, and keep touching it while you move your left hand slowly from close to you out to arm's length and back.", "seconds": 12, "hands": "both", "pose": "touch-stick", "controllers": ["left"]},
{"text": "Swap: right controller on, the left one off. Touch the right thumbstick with your left index fingertip, and keep touching it while you move your right hand slowly from close to you out to arm's length and back.", "seconds": 12, "hands": "both", "pose": "touch-stick", "picture_mirror": true, "controllers": ["right"]},
{"text": "Put the right controller on the desk in front of you. Touch its thumbstick with your index fingertip from the front, then from above.", "seconds": 8, "hands": "any", "pose": "touch-stick", "picture": "touch-stick-desk", "position": "down"},
{"text": "Now touch it reaching from the left, then from the right.", "seconds": 8, "hands": "any", "pose": "touch-stick", "picture": "touch-stick-desk", "position": "down"}
]},
{"id": "bare-push", "title": "Depth, bare hands", "kind": "bar", "requires": [],
"before": {"when": "controllers", "text": "Take the controllers off and put them out of view.", "seconds": 15},
"intro": "Push both hands straight out in front of you, away from the headset, then pull them back toward it. Only nearer and farther, not sideways. Follow the hollow circle on the bar: right is arm out, left is at your chest. The blue dot is the current hand tracking's guess at how far your hands are. It's only an approximation and often wrong, so ignore it.",
"defaults": {"hands": "both", "pose": "open", "picture": "push"},
"near_m": 0.2, "far_m": 0.6, "near_label": "At your chest", "far_label": "Arm out", "period_s": 6, "lead_s": 3, "reps": 3,
"heights": [
{"id": "chest", "text": "Chest height, palms out like a stop sign. Push straight out, away from the headset, then pull back to your chest. Follow the hollow circle, not the blue dot."},
{"id": "eye", "text": "Now at eye level, palms out. Push straight out, away from the headset, then pull back toward it. Follow the hollow circle, not the blue dot."}
]},
{"id": "no-hands", "title": "No hands", "requires": [], "quick": true,
"intro": "Last one: put your hands down, out of view.",
"prompts": [
{"text": "Keep your hands out of view and look slowly around the room.", "seconds": 10, "hands": "none", "picture": "no-hands"}
]}
]
}
+2587
View File
File diff suppressed because it is too large. Load diff
+128
View File
@@ -0,0 +1,128 @@
"""Which side camera is which, in recordings: the rules every reader shares.
ft-camd tells slam_left's buffers from slam_right's by the order XRService allocated them, and
some XRService starts reverse it: then each side camera's images carry the other's name. A
tracking ft-hands tells from the hands (hands/track/sides.h, HANDS_SWAP_SIDES=auto) and publishes
what it found in /run/user/UID/frametop-hands/sides.json (read_live). Two things are recorded:
swapped whether ft-camd's naming was backwards during the recording (the truth);
None while nobody knows. A hand recorder session has it in session.json
"sides": {"swapped", "decided_by", "evidence", ...}; an ft-hands --record
recording in DIR/sides.json.
names_swapped per recording file: whether the side cameras' names in it were exchanged from
ft-camd's (ft-hands --sides 1). A session's take.json "parts": {"sets.bin":
{"names_swapped": false}, "sets-2.bin": {...}}; DIR/sides.json "names_swapped":
[[first set, bool], ...] (it can change inside a recording when ft-hands decides).
A file's names are right when names_swapped == swapped. Readers rename slam_left <-> slam_right
(and their _dk dark frames) where they differ (needs_rename). Exports always carry the right
names, with names_swapped = swapped written next to them, so applying the rule again is harmless.
Standard library only (the window, validate.py on Windows, the maintainer's tools).
"""
import json
import os
import struct
import time
HDR = struct.Struct("<8sII") # fh_set_hdr_t (hands/track/record.h)
CAM = struct.Struct("<16sIIQQ") # fh_set_cam_t: name, width, height, capture_ns, dqbuf_ns
SIDES = {"slam_left": "slam_right", "slam_right": "slam_left",
"slam_left_dk": "slam_right_dk", "slam_right_dk": "slam_left_dk"}
LIVE_FRESH_S = 6.0 # ft-hands rewrites its sides.json at least every 2 s
def other_name(name):
"""slam_left <-> slam_right (and their dark frames); other names as they are."""
return SIDES.get(name, name)
def needs_rename(swapped, names_swapped):
"""True when a file's side cameras carry each other's names. Unknown truth: leave them."""
if swapped is None:
return False
return bool(names_swapped) != bool(swapped)
def rename_record(record):
"""One FHSET01 record (bytes) with slam_left and slam_right's names exchanged (and their
dark frames'). Only the 16-byte name fields change; pixels and lengths stay."""
out = bytearray(record)
ncams = HDR.unpack_from(out, 0)[1]
for k in range(ncams):
off = HDR.size + k * CAM.size
raw = bytes(out[off:off + 16])
name = raw.split(b"\0", 1)[0].decode(errors="replace")
new = other_name(name)
if new != name:
out[off:off + 16] = new.encode().ljust(16, b"\0")
return bytes(out)
# ------------------------------------------------------------------ sessions and recordings
def session_sides(session_json):
"""A session.json's "sides" (a dict), or {"swapped": None} when it has none."""
s = (session_json or {}).get("sides")
return s if isinstance(s, dict) else {"swapped": None}
def part_names_swapped(take_json, part):
"""Whether a take's part file (e.g. "sets-2.bin") was recorded with exchanged names."""
parts = (take_json or {}).get("parts")
entry = parts.get(part) if isinstance(parts, dict) else None
return bool(entry.get("names_swapped")) if isinstance(entry, dict) else False
def part_rename(session_json, take_json, part):
"""Should a session take's part file have its side cameras renamed when read?"""
return needs_rename(session_sides(session_json).get("swapped"), part_names_swapped(take_json, part))
def recording_runs(rec_dir):
"""An ft-hands --record recording (DIR/sets.bin + DIR/sides.json): [(first set, rename)],
or [(0, False)] when it has no sides.json (recorded before there was one)."""
try:
with open(os.path.join(rec_dir, "sides.json")) as f:
s = json.load(f)
except (OSError, ValueError):
return [(0, False)]
runs = s.get("names_swapped") or [[0, False]]
return [(int(first), needs_rename(s.get("swapped"), sw)) for first, sw in runs]
def rename_at(runs, i):
"""recording_runs()'s answer for set i."""
out = False
for first, rename in runs:
if i >= first:
out = rename
return out
# ------------------------------------------------------------------ the live decision
def run_dir():
return "/run/user/%d/frametop-hands" % os.getuid()
def read_live(path=None, ring_path=None, now_ns=None):
"""The tracking ft-hands' sides.json, or None if there's none or it's stale (ft-hands
rewrites it every 2 s and removes it when it exits). With ring_path, also None when it
was written for another ft-camd run than the ring there now."""
path = path or os.path.join(run_dir(), "sides.json")
try:
with open(path) as f:
s = json.load(f)
except (OSError, ValueError):
return None
now = time.clock_gettime_ns(time.CLOCK_MONOTONIC) if now_ns is None else now_ns
if not isinstance(s, dict) or (now - int(s.get("updated_ns", 0))) / 1e9 > LIVE_FRESH_S:
return None
if ring_path:
try:
if os.stat(ring_path).st_ino != s.get("ring_ino"):
return None
except OSError:
return None
return s
+647
View File
@@ -0,0 +1,647 @@
#!/usr/bin/env python3
"""The hand recorder's sessions and takes on disk: listing, review, deleting, export.
Standard library only (no Qt, no NumPy), so the window and the command line share it.
The layout is hands/rec/DESIGN.md's "Files":
BASE/profile.json
BASE/sessions/<YYYYMMDD-HHMMSS>/session.json, calibration.json
BASE/sessions/<id>/takes/<NN>-<section>/sets.bin (sets-2.bin, ... after pauses),
prompts.jsonl, poses.jsonl, take.json
BASE/exports/<session>/
A take's recording is one or more FHSET01 files (hands/track/record.h): per set a header
(magic, ncams, bytes), one fh_set_cam_t per camera, then each camera's 8-bit pixels.
Deleted ranges live in take.json ("deleted": [[from_ns, to_ns], ...], CLOCK_MONOTONIC, the
clock of dqbuf_ns); the files keep every set until export leaves them out.
Side cameras (sides.py): a part recorded before the live tracker decided which side camera is
which may carry slam_left's and slam_right's names the wrong way round. TakeIndex renames them as
it reads (session.json "sides" against take.json "parts"), so review and export see the right
names, and export writes them so: an export's files are always named right, its take.json says
"parts": {"sets.bin": {"names_swapped": <the session's swapped>}}, and its manifest has each
take's "sides". `takes.py sides SESSION` shows the decision; --set swapped|named records one by
hand (e.g. from tools/check_sides.py on a session no live tracker decided).
usage: takes.py [--base DIR] list | takes SESSION | export SESSION | sides SESSION [--set swapped|named]
"""
import argparse
import datetime
import hashlib
import json
import os
import re
import shutil
import struct
import subprocess
import sys
import threading
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import sides # noqa: E402 (hands/rec/sides.py, next to this file)
DEFAULT_BASE = os.path.expanduser("~/.local/share/frametop/hands/contrib")
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MAGIC = b"FHSET01"
HDR = struct.Struct("<8sII") # fh_set_hdr_t: magic, ncams, bytes (the whole record)
CAM = struct.Struct("<16sIIQQ") # fh_set_cam_t: name, width, height, capture_ns, dqbuf_ns
MAX_CAMS = 16 # SetReader's limit
PART_RE = re.compile(r"^sets(?:-(\d+))?\.bin$")
SESSION_RE = re.compile(r"^\d{8}-\d{6}(?:-\d+)?$") # session.py adds -2, -3 to a second one in a second
EXPORT_SCHEMA = 1
# zstd as DESIGN.md has it: level 10, two threads, at the lowest CPU priority (CPU work while
# someone is in VR makes the headset stutter).
ZSTD_ARGS = ["-10", "-T2", "-q", "-c"]
ZSTD_PATHS = ("/usr/bin/zstd", "/usr/local/bin/zstd", "/run/host/usr/bin/zstd")
CHUNK = 1 << 20
class Cancelled(Exception):
pass
def read_json(path, default=None):
try:
with open(path) as f:
return json.load(f)
except (OSError, ValueError):
return {} if default is None else default
def write_json(path, obj):
"""Write through a temporary file, so a crash never leaves half a file."""
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(obj, f, indent=2)
f.write("\n")
os.replace(tmp, path)
def find_zstd():
"""The zstd binary, or None. The dev container gets it from setup/dev-container.sh."""
found = shutil.which("zstd")
if found:
return found
return next((p for p in ZSTD_PATHS if os.access(p, os.X_OK)), None)
def tool_version():
"""ft-handrec plus the checkout's git describe, for session.json and the manifest."""
try:
out = subprocess.run(["git", "-C", REPO, "describe", "--always", "--dirty", "--tags"],
capture_output=True, text=True, timeout=5)
described = out.stdout.strip()
except (OSError, subprocess.TimeoutExpired):
described = ""
return "ft-handrec " + (described or "unknown")
def free_bytes(path):
"""Free space on the file system that holds path (or its nearest existing parent)."""
while path and not os.path.exists(path):
path = os.path.dirname(path)
try:
return shutil.disk_usage(path or "/").free
except OSError:
return 0
def tree_stat(path):
"""(bytes, newest mtime) of the files under path."""
total, newest = 0, 0.0
for root, _, files in os.walk(path):
for name in files:
try:
st = os.lstat(os.path.join(root, name))
except OSError:
continue
total += st.st_size
newest = max(newest, st.st_mtime)
return total, newest
def tree_bytes(path):
return tree_stat(path)[0]
def in_ranges(t, ranges):
return any(a <= t <= b for a, b in ranges)
def export_jsonl(src, dst, ranges, keep_controllers):
"""Copy a take's poses.jsonl or prompts.jsonl for export:
- poses in the deleted ranges are left out, and the live tracker's feedback there (the
prompt timeline stays: it says what was asked, and shows nothing);
- without controllers (the checklist's "none"), the controllers' poses are null and feedback
carries no controller state: controllers lying about still get logged, and those poses
would read as hands' ground truth.
Lines that don't parse are copied as they are (validate.py reports them)."""
poses = os.path.basename(src) == "poses.jsonl"
with open(src, encoding="utf-8") as f, open(dst, "w", encoding="utf-8", newline="\n") as out:
for line in f:
try:
obj = json.loads(line)
except ValueError:
out.write(line)
continue
if not isinstance(obj, dict):
out.write(line)
continue
t = obj.get("t")
gone = isinstance(t, int) and in_ranges(t, ranges)
if poses:
if gone:
continue
if not keep_controllers:
obj["left"] = obj["right"] = None
elif obj.get("event") == "feedback":
if gone:
continue
if not keep_controllers:
obj.pop("controller", None)
out.write(json.dumps(obj, separators=(", ", ": ")) + "\n")
def merge_ranges(ranges):
"""Sorted, with overlapping or touching ranges joined."""
out = []
for a, b in sorted((min(a, b), max(a, b)) for a, b in ranges):
if out and a <= out[-1][1] + 1:
out[-1][1] = max(out[-1][1], b)
else:
out.append([a, b])
return out
# ---------------------------------------------------------------- one take's recording
class TakeIndex:
"""Where each set of a take's recording is, without reading pixels. Sets are numbered
across the parts (sets.bin, sets-2.bin, ...) in order."""
def __init__(self, take_dir):
self.dir = take_dir
self.parts = self._parts(take_dir)
self.sets = [] # (part, offset, bytes, time_ns): time_ns is the cameras' earliest dqbuf_ns
self.part_starts = [] # index of each part's first set
self.cams = [] # the first set's [{name, width, height}], side cameras named right
# per part: are its side cameras named the wrong way round (sides.py)? read_set and
# read_raw rename them.
session = read_json(os.path.join(os.path.dirname(os.path.dirname(take_dir)), "session.json"))
take = read_json(os.path.join(take_dir, "take.json"))
self.swapped = sides.session_sides(session).get("swapped")
self.names_swapped = [sides.part_names_swapped(take, os.path.basename(p)) for p in self.parts]
self.rename = [sides.needs_rename(self.swapped, n) for n in self.names_swapped]
for p, path in enumerate(self.parts):
self.part_starts.append(len(self.sets))
self._index(p, path)
@staticmethod
def _parts(take_dir):
found = []
try:
names = os.listdir(take_dir)
except OSError:
return []
for name in names:
m = PART_RE.match(name)
if m:
found.append((int(m.group(1) or 1), os.path.join(take_dir, name)))
return [path for _, path in sorted(found)]
def _index(self, p, path):
try:
size = os.path.getsize(path)
f = open(path, "rb")
except OSError:
return
with f:
off = 0
while off + HDR.size <= size:
f.seek(off)
head = f.read(HDR.size)
if len(head) < HDR.size:
break
magic, ncams, nbytes = HDR.unpack(head)
# A truncated last set (the recorder was killed mid-write) ends the part.
if magic[:7] != MAGIC or not 0 < ncams <= MAX_CAMS or nbytes < HDR.size or off + nbytes > size:
break
cams = f.read(CAM.size * ncams)
if len(cams) < CAM.size * ncams:
break
fields = [CAM.unpack_from(cams, i * CAM.size) for i in range(ncams)]
if not self.cams:
self.cams = [{"name": self._name(p, n), "width": w, "height": h} for n, w, h, _, _ in fields]
self.sets.append((p, off, nbytes, min(c[4] for c in fields)))
off += nbytes
def _name(self, p, raw):
name = raw.split(b"\0", 1)[0].decode(errors="replace")
return sides.other_name(name) if self.rename[p] else name
def renamed_sets(self, keep=None):
"""How many of the sets (all, or the indices in keep) read renamed."""
return sum(1 for i in (range(len(self.sets)) if keep is None else keep) if self.rename[self.sets[i][0]])
def __len__(self):
return len(self.sets)
def time_ns(self, i):
return self.sets[i][3]
def duration_s(self):
"""Recorded time: each part's first to last set, so pauses don't count."""
total = 0
ends = self.part_starts[1:] + [len(self.sets)]
for start, end in zip(self.part_starts, ends):
if end > start:
total += self.sets[end - 1][3] - self.sets[start][3]
return total / 1e9
def bytes(self):
return sum(s[2] for s in self.sets)
def read_set(self, i, only=None):
"""Set i's cameras: [{name, width, height, capture_ns, dqbuf_ns, pixels}], pixels as raw
8-bit grey bytes (width x height, packed). only: a camera name, to read just that one."""
p, off, nbytes, _ = self.sets[i]
with open(self.parts[p], "rb") as f:
f.seek(off)
ncams = HDR.unpack(f.read(HDR.size))[1]
heads = f.read(CAM.size * ncams)
out = []
px_off = off + HDR.size + CAM.size * ncams
for k in range(ncams):
name, w, h, capture_ns, dqbuf_ns = CAM.unpack_from(heads, k * CAM.size)
name = self._name(p, name)
if only is None or name == only:
f.seek(px_off)
out.append({"name": name, "width": w, "height": h, "capture_ns": capture_ns,
"dqbuf_ns": dqbuf_ns, "pixels": f.read(w * h)})
px_off += w * h
return out
def read_raw(self, i):
"""Set i's whole record, as it is in the file but with the side cameras named right."""
p, off, nbytes, _ = self.sets[i]
with open(self.parts[p], "rb") as f:
f.seek(off)
record = f.read(nbytes)
return sides.rename_record(record) if self.rename[p] else record
_index_cache = {}
_index_lock = threading.Lock()
def take_index(take_dir):
"""A TakeIndex, cached until one of the take's recording files, its take.json or its
session.json (the side cameras' decision) changes size or time."""
key_parts = []
meta = [os.path.join(take_dir, "take.json"), os.path.join(os.path.dirname(os.path.dirname(take_dir)), "session.json")]
for path in TakeIndex._parts(take_dir) + meta:
try:
st = os.stat(path)
key_parts.append((path, st.st_size, st.st_mtime_ns))
except OSError:
pass
key = tuple(key_parts)
with _index_lock:
cached = _index_cache.get(take_dir)
if cached and cached[0] == key:
return cached[1]
index = TakeIndex(take_dir)
with _index_lock:
_index_cache[take_dir] = (key, index)
return index
# ---------------------------------------------------------------- the store
class Store:
def __init__(self, base=DEFAULT_BASE):
self.base = os.path.abspath(os.path.expanduser(base))
self.sessions_dir = os.path.join(self.base, "sessions")
self.exports_dir = os.path.join(self.base, "exports")
self.profile_path = os.path.join(self.base, "profile.json")
# --- paths, checked: ids come from the window, so nothing may climb out of the base
def session_dir(self, session):
if not SESSION_RE.match(session or ""):
raise ValueError(f"not a session id: {session!r}")
return os.path.join(self.sessions_dir, session)
def take_dir(self, session, take):
if not take or "/" in take or take.startswith("."):
raise ValueError(f"not a take id: {take!r}")
return os.path.join(self.session_dir(session), "takes", take)
def export_dir(self, session):
self.session_dir(session) # checks the id
return os.path.join(self.exports_dir, session)
def profile(self):
return read_json(self.profile_path)
# --- listing
def sessions(self):
"""Newest first: [{id, started, takes, bytes, lighting, status, dry_run, contributor, exported,
export_stale (changed since), export_bytes}]."""
out = []
try:
names = os.listdir(self.sessions_dir)
except OSError:
return out
for sid in names:
path = os.path.join(self.sessions_dir, sid)
if not SESSION_RE.match(sid) or not os.path.isdir(path):
continue
meta = read_json(os.path.join(path, "session.json"))
size, changed = tree_stat(path)
manifest = os.path.join(self.export_dir(sid), "manifest.json")
exported = os.path.getmtime(manifest) if os.path.isfile(manifest) else 0.0
out.append({"id": sid, "started": meta.get("started", ""), "takes": len(self.take_ids(sid)),
"bytes": size, "contributor": meta.get("contributor", ""),
"lighting": (meta.get("lighting") or {}).get("chosen", ""),
"status": meta.get("status", ""), "dry_run": bool(meta.get("dry_run")),
"exported": bool(exported), "export_stale": bool(exported) and changed > exported,
"export_bytes": tree_bytes(self.export_dir(sid)) if exported else 0})
return sorted(out, key=lambda s: s["id"], reverse=True)
def take_ids(self, session):
try:
names = os.listdir(os.path.join(self.session_dir(session), "takes"))
except OSError:
return []
return sorted(n for n in names if not n.startswith(".")
and os.path.isdir(os.path.join(self.session_dir(session), "takes", n)))
def takes(self, session):
"""[{id, section, title, status, sets, deleted_sets, ranges, duration_s, bytes, cams}]."""
out = []
for tid in self.take_ids(session):
path = self.take_dir(session, tid)
meta = read_json(os.path.join(path, "take.json"))
index = take_index(path)
ranges = merge_ranges(meta.get("deleted") or [])
out.append({"id": tid, "section": meta.get("section", tid.split("-", 1)[-1]),
"title": meta.get("title") or tid, "status": meta.get("status", "recording"),
"sets": len(index), "parts": len(index.parts),
"deleted_sets": sum(1 for s in index.sets if in_ranges(s[3], ranges)),
"ranges": ranges, "duration_s": index.duration_s(), "bytes": index.bytes(),
"cams": [c["name"] for c in index.cams]})
return out
def take_meta(self, session, take):
return read_json(os.path.join(self.take_dir(session, take), "take.json"))
# --- deleted ranges
def ranges(self, session, take):
return merge_ranges(self.take_meta(session, take).get("deleted") or [])
def _set_ranges(self, session, take, ranges):
path = os.path.join(self.take_dir(session, take), "take.json")
meta = read_json(path)
meta["deleted"] = merge_ranges(ranges)
write_json(path, meta)
return meta["deleted"]
def delete_range(self, session, take, from_ns, to_ns):
"""Leave sets from from_ns to to_ns (dqbuf_ns, inclusive) out of the export."""
return self._set_ranges(session, take, self.ranges(session, take) + [[int(from_ns), int(to_ns)]])
def restore_range(self, session, take, i):
"""Take deleted range i (in ranges()' order) back."""
ranges = self.ranges(session, take)
if 0 <= i < len(ranges):
del ranges[i]
return self._set_ranges(session, take, ranges)
# --- deleting files
def delete_take(self, session, take):
path = self.take_dir(session, take)
if os.path.isdir(path):
shutil.rmtree(path)
meta_path = os.path.join(self.session_dir(session), "session.json")
meta = read_json(meta_path)
if take in (meta.get("takes") or []):
meta["takes"] = [t for t in meta["takes"] if t != take]
meta.setdefault("deleted_takes", []).append(take)
write_json(meta_path, meta)
def delete_session(self, session):
"""The session and its export, if any."""
for path in (self.session_dir(session), self.export_dir(session)):
if os.path.isdir(path):
shutil.rmtree(path)
def delete_export(self, session):
path = self.export_dir(session)
if os.path.isdir(path):
shutil.rmtree(path)
# --- export
def sides(self, session, swapped=None):
"""session.json's side camera decision (sides.py) plus each take's parts; with swapped
(True/False), record that by hand first ("decided_by": "manual"). No set is rewritten:
reading and export rename."""
path = os.path.join(self.session_dir(session), "session.json")
meta = read_json(path)
if not meta:
raise RuntimeError(f"no session {session}")
if swapped is not None:
old = sides.session_sides(meta)
new = {"swapped": bool(swapped), "decided_by": "manual",
"decided_at": datetime.datetime.now().astimezone().isoformat(timespec="seconds")}
if old.get("swapped") is not None:
new["replaced"] = old
meta["sides"] = new
write_json(path, meta)
out = {"sides": sides.session_sides(meta), "takes": {}}
for tid in self.take_ids(session):
index = take_index(self.take_dir(session, tid))
out["takes"][tid] = {os.path.basename(p): {"names_swapped": n, "renamed_when_read": r}
for p, n, r in zip(index.parts, index.names_swapped, index.rename)}
return out
def export(self, session, progress=None, cancel=None, keep_notes=False, low_priority=True):
"""Write exports/<session>/ (DESIGN.md "Export"): manifest.json, calibration.json, per
take prompts.jsonl, poses.jsonl, take.json and sets.bin.zst (sets in deleted ranges
left out), then SHA256SUMS. progress(fraction 0..1, text) is called as it goes;
cancel() (or cancel.is_set()) returning true stops it, raising Cancelled. Nothing is
left behind on failure or cancel. Returns the export's path.
low_priority: run this thread at nice 19 as well as zstd (Linux nice is per thread)."""
zstd = find_zstd()
if not zstd:
raise RuntimeError("zstd isn't installed (in the dev container: sudo dnf install zstd)")
cancelled = getattr(cancel, "is_set", cancel) or (lambda: False)
report = progress or (lambda fraction, text: None)
src = self.session_dir(session)
if not os.path.isdir(src):
raise RuntimeError(f"no session {session}")
if low_priority:
try:
os.setpriority(os.PRIO_PROCESS, threading.get_native_id(), 19)
except OSError:
pass
final = self.export_dir(session)
work = final + ".partial"
if os.path.isdir(work):
shutil.rmtree(work)
os.makedirs(work)
try:
self._export(session, src, work, zstd, report, cancelled, keep_notes)
if os.path.isdir(final):
shutil.rmtree(final)
os.replace(work, final)
except BaseException:
shutil.rmtree(work, ignore_errors=True)
raise
report(1.0, "Done")
return final
def _export(self, session, src, work, zstd, report, cancelled, keep_notes):
profile = self.profile()
meta = read_json(os.path.join(src, "session.json"))
meta.pop("uploads", None) # earlier uploads' records (hub.py) aren't part of the contribution
takes = self.takes(session)
total = sum(t["bytes"] for t in takes) or 1
done = 0
take_entries = []
keep_controllers = (meta.get("checklist") or {}).get("controllers") == "straps"
for t in takes:
if cancelled():
raise Cancelled()
tdir = self.take_dir(session, t["id"])
out = os.path.join(work, "takes", t["id"])
os.makedirs(out)
ranges = t["ranges"]
for name in ("prompts.jsonl", "poses.jsonl"):
if os.path.isfile(os.path.join(tdir, name)):
export_jsonl(os.path.join(tdir, name), os.path.join(out, name), ranges, keep_controllers)
index = take_index(tdir)
keep = [i for i in range(len(index)) if not in_ranges(index.time_ns(i), ranges)]
# one file, named right where the decision is known (sides.py): its names_swapped is
# then the session's swapped; unknown, it's the parts' own (None if they differ)
if index.swapped is not None:
names_swapped = bool(index.swapped)
else:
names_swapped = index.names_swapped[0] if len(set(index.names_swapped)) == 1 else None
take_meta = read_json(os.path.join(tdir, "take.json"))
if take_meta:
take_meta["parts"] = {"sets.bin": {"names_swapped": names_swapped}}
write_json(os.path.join(out, "take.json"), take_meta)
entry = {"id": t["id"], "section": t["section"], "title": t["title"], "status": t["status"],
"sets": len(keep), "sets_deleted": len(index) - len(keep), "cameras": index.cams,
"duration_s": round(t["duration_s"], 2), "file": None,
"sides": {"names_swapped": names_swapped, "renamed_sets": index.renamed_sets(keep)}}
done += index.bytes() - sum(index.sets[i][2] for i in keep) # deleted sets count as done
if keep:
entry["file"] = "takes/%s/sets.bin.zst" % t["id"]
def step(nbytes, title=t["title"]):
nonlocal done
done += nbytes
report(min(done / total, 0.99), f"Compressing {title}")
entry["raw_bytes"] = self._compress(index, keep, zstd, os.path.join(out, "sets.bin.zst"),
step, cancelled)
take_entries.append(entry)
if cancelled():
raise Cancelled()
for name in ("calibration.json", "device.json"):
if os.path.isfile(os.path.join(src, name)):
shutil.copyfile(os.path.join(src, name), os.path.join(work, name))
shown_profile = json.loads(json.dumps(profile))
if not keep_notes and isinstance(shown_profile.get("optional"), dict):
shown_profile["optional"].pop("notes", None)
manifest = {"schema": EXPORT_SCHEMA, "tool": tool_version(),
"exported": datetime.datetime.now().astimezone().isoformat(timespec="seconds"),
"session_id": session, "contributor": profile.get("contributor", meta.get("contributor", "")),
"consent_version": (profile.get("consent") or {}).get("version", ""),
"profile": shown_profile, "session": meta, "takes": take_entries}
write_json(os.path.join(work, "manifest.json"), manifest)
report(0.995, "Writing checksums")
sums = []
for root, _, files in os.walk(work):
for name in files:
path = os.path.join(root, name)
sums.append((os.path.relpath(path, work), sha256_file(path, cancelled)))
with open(os.path.join(work, "SHA256SUMS"), "w") as f:
for rel, digest in sorted(sums):
f.write(f"{digest} {rel}\n")
@staticmethod
def _compress(index, keep, zstd, dest, step, cancelled):
"""Stream the kept sets through zstd into dest. Returns the uncompressed size."""
raw = 0
with open(dest, "wb") as out:
proc = subprocess.Popen(["nice", "-n", "19", zstd] + ZSTD_ARGS, stdin=subprocess.PIPE, stdout=out,
stderr=subprocess.PIPE)
try:
for i in keep:
if cancelled():
raise Cancelled()
record = index.read_raw(i)
proc.stdin.write(record)
raw += len(record)
step(len(record))
proc.stdin.close()
err = proc.stderr.read().decode(errors="replace").strip()
if proc.wait() != 0:
raise RuntimeError(f"zstd failed: {err or proc.returncode}")
except BaseException:
proc.kill()
proc.wait()
raise
finally:
proc.stderr.close()
return raw
def sha256_file(path, cancelled=lambda: False):
h = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(CHUNK):
if cancelled():
raise Cancelled()
h.update(chunk)
return h.hexdigest()
def human_bytes(n):
for unit in ("B", "KB", "MB", "GB"):
if n < 1000 or unit == "GB":
return f"{n:.0f} {unit}" if unit == "B" else f"{n:.1f} {unit}"
n /= 1000
return f"{n:.1f} TB"
def main():
ap = argparse.ArgumentParser(description="List, check and export hand recorder sessions.")
ap.add_argument("--base", default=DEFAULT_BASE)
sub = ap.add_subparsers(dest="cmd", required=True)
sub.add_parser("list")
sub.add_parser("takes").add_argument("session")
sub.add_parser("export").add_argument("session")
sp = sub.add_parser("sides", help="show (or record) which way round the side cameras were")
sp.add_argument("session")
sp.add_argument("--set", choices=("swapped", "named"),
help="record the decision by hand (e.g. from tools/check_sides.py on a take)")
a = ap.parse_args()
store = Store(a.base)
if a.cmd == "list":
for s in store.sessions():
print(f"{s['id']} {s['takes']} takes {human_bytes(s['bytes'])} {s['lighting'] or '-'}"
+ (" exported" if s["exported"] else ""))
elif a.cmd == "takes":
for t in store.takes(a.session):
print(f"{t['id']} {t['status']} {t['sets']} sets ({t['deleted_sets']} deleted) "
f"{t['duration_s']:.1f} s {human_bytes(t['bytes'])}")
elif a.cmd == "sides":
print(json.dumps(store.sides(a.session, None if a.set is None else a.set == "swapped"), indent=1))
else:
path = store.export(a.session, progress=lambda f, text: print(f"\r{f * 100:5.1f}% {text:40.40}", end="",
flush=True))
print(f"\n{path} {human_bytes(tree_bytes(path))}")
if __name__ == "__main__":
main()
+228
View File
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""Tests for the session's camera check: the preflight that keeps a session from starting
with the upper cameras off, and the early no-hands stop in the hand-size section's first step
(dry runs with a made-up hands file; no processes, no real cameras).
python3 hands/rec/tests/test_nohands.py
"""
import json
import os
import sys
import threading
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
sys.path.insert(0, HERE)
import session # noqa: E402
import camcheck # noqa: E402 (session.py put hands/ on the path)
from test_session import SessionBase # noqa: E402
SCRIPT = {
"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Test", "seconds": 1, "text": "A test."},
"done": {"title": "Done", "seconds": 0, "text": "Done."},
"stopped": {"title": "Stopped", "seconds": 0, "text": "Stopped."},
"sections": [
{"id": "hand-size", "title": "Hand size", "intro": "Hand size.", "go": "Hold",
"defaults": {"hands": "both"},
"prompts": [{"text": "Both hands flat.", "seconds": 6, "pose": "flat"},
{"text": "Backs.", "seconds": 2, "pose": "flat-back"}]}]}
HAND = {"palm": [0.0, 0.0, -0.4], "palm_m": 0.4, "tip": [0.0, 0.05, -0.45]}
DEGRADED = {"status": "degraded", "reason": camcheck.VCINT_REASON, "summary": camcheck.DEGRADED_VCINT,
"evidence": ["17:02:47 Failed to load VCINT FPGA image when passthrough cameras are connected"]}
OK = {"status": "ok", "reason": "4 tracking cameras running", "summary": "ok", "evidence": []}
class FakeHands:
"""Stands in for the hands file: what read() gives can change mid-session."""
def __init__(self, value):
self.value = value
self.lock = threading.Lock()
def set(self, value):
with self.lock:
self.value = value
def read(self):
with self.lock:
return None if self.value is None else dict(self.value)
class NoHandsTest(SessionBase):
def setUp(self):
super().setUp()
with open(self.script, "w") as f:
json.dump(SCRIPT, f)
def events(self, s):
with open(os.path.join(s.session_dir, "takes", "01-hand-size", "prompts.jsonl")) as f:
# feedback lines (twice a second, as the tracker publishes) aren't what's tested here
return [e for e in map(json.loads, f) if e["event"] != "feedback"]
def run_to_first_hold(self, hands, camera=DEGRADED, **kw):
s = self.session(hands_reader=hands, speed=3, **kw)
s.camera_check_fn = lambda: camera
s.start()
self.waiting(s, "starting")
s.next_step()
self.waiting(s, "intro")
s.next_step()
self.waiting(s, "ready", "Both hands flat.")
s.next_step()
return s
def session_json(self, s):
with open(os.path.join(s.session_dir, "session.json")) as f:
return json.load(f)
def log(self, s):
with open(os.path.join(s.session_dir, "session.log")) as f:
return f.read()
def test_no_hands_then_redo(self):
hands = FakeHands({"left": None, "right": None}) # the tracker publishes, sees nothing
s = self.run_to_first_hold(hands)
st = self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
self.assertTrue(st["nohands"])
self.assertTrue(st["can_redo"])
self.assertEqual(st["camera"]["status"], "degraded")
self.assertIn(camcheck.USER_TEXT, st["prompt"])
self.assertIn("panel: title " + session.NO_HANDS_TITLE, self.panel)
hands.set({"left": HAND, "right": HAND})
s.next_step() # try again: straight to the countdown, no second ready wait
self.wait_for(s, lambda st: st["state"] == "countdown", "the countdown again")
self.waiting(s, "ready", "Backs.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
names = [e["event"] for e in ev]
self.assertEqual(names, ["take", "ready", "prompt", "wait", "nohands", "redo",
"ready", "prompt", "wait", "ready", "prompt", "wait", "end"])
nohands, redo = ev[4], ev[5]
self.assertGreaterEqual(nohands["reads"], session.HANDS_CHECK_MIN_READS)
self.assertEqual(redo["from"], ev[1]["t"]) # the failed try gets no labels
self.assertTrue(ev[2]["t"] < redo["to"])
# the retry wasn't stopped: a hand was seen
self.assertRegex(self.log(s), r"hands check hand-size/flat/both: a hand in [1-9][0-9]* of")
self.assertNotIn("stop_reason", self.session_json(s))
def test_no_hands_then_stop(self):
s = self.run_to_first_hold(FakeHands({"left": None, "right": None}))
self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
s.stop(wait=10)
self.assertEqual(s.state, "stopped")
sj = self.session_json(s)
self.assertIn("no hands were seen", sj["stop_reason"])
self.assertIn(camcheck.DEGRADED_VCINT, sj["stop_reason"])
self.assertIn(camcheck.USER_TEXT, s._status["prompt"])
self.assertIn("camera check: " + camcheck.DEGRADED_VCINT, self.log(s))
def test_redo_key_and_skip(self):
hands = FakeHands({"left": None, "right": None})
s = self.run_to_first_hold(hands, camera=OK)
st = self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
self.assertIn("The camera check found nothing wrong", st["prompt"])
s.redo() # R is the same as Next there
self.wait_for(s, lambda st: st["state"] == "countdown", "the countdown again")
self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "no hands again")
s.skip() # S skips the section; the no-hands note doesn't stick
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("stop_reason", self.session_json(s))
self.assertEqual([e["event"] for e in self.events(s)].count("nohands"), 2)
def test_hand_seen_sometimes(self):
hands = FakeHands({"left": None, "right": None})
s = self.run_to_first_hold(hands)
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
hands.set({"left": HAND, "right": None}) # one hand, for part of the hold: fine
self.waiting(s, "ready", "Backs.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("nohands", [e["event"] for e in self.events(s)])
def test_no_tracker_cant_tell(self):
s = self.run_to_first_hold(FakeHands(None)) # nothing published: can't tell, go on
self.waiting(s, "ready", "Backs.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("nohands", [e["event"] for e in self.events(s)])
self.assertIn("can't tell", self.log(s))
def test_only_the_first_step(self):
hands = FakeHands({"left": HAND, "right": HAND})
s = self.run_to_first_hold(hands)
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
self.waiting(s, "ready", "Backs.")
hands.set({"left": None, "right": None}) # gone in step 2: notes, but no stop
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
self.assertNotIn("nohands", [e["event"] for e in self.events(s)])
def test_auto_mode(self):
hands = FakeHands({"left": None, "right": None})
s = self.session(hands_reader=hands, speed=3, auto=True)
s.camera_check_fn = lambda: DEGRADED
s.start()
self.wait_for(s, lambda st: st["state"] == "nohands" and st["waiting"], "the no-hands stop")
hands.set({"left": HAND, "right": HAND})
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "prompt", "prompt", "pause", "nohands", "redo", "resume", "prompt",
"prompt", "end"])
class PreflightTest(SessionBase):
def test_degraded_stops_before_anything(self):
s = self.session()
s.dry_run = False # as a real session; the check is the only step run
s.camera_check_fn = lambda: DEGRADED
self.assertTrue(s._preflight())
self.assertEqual(s.state, "error")
self.assertEqual(s._status["error"], camcheck.USER_TEXT)
self.assertEqual(s.session_dir, "") # no session folder made
self.assertFalse(os.path.exists(os.path.join(self.tmp, "base", "sessions")))
def test_other_degraded_text(self):
r = dict(DEGRADED, reason="only 3 of 4 tracking cameras running")
self.assertIn("only 3 of 4", session.camera_text(r))
self.assertEqual(session.camera_text(OK), "")
self.assertEqual(session.camera_text({"status": "unknown"}), "")
self.assertEqual(session.camera_text(None), "")
def test_ok_unknown_ignored(self):
for result in (OK, {"status": "unknown", "summary": "unknown: x", "evidence": []}):
s = self.session()
s.dry_run = False
s.camera_check_fn = lambda: result
self.assertFalse(s._preflight())
s = self.session(check_cameras=False)
s.dry_run = False
s.camera_check_fn = lambda: DEGRADED
self.assertFalse(s._preflight()) # --ignore-cameras
s = self.session(ring="/tmp/some-ring")
s.dry_run = False
s.camera_check_fn = lambda: DEGRADED
self.assertFalse(s._preflight()) # ft-ringplay's frames: no headset cameras involved
def test_camera_check_never_raises(self):
orig = camcheck.check
try:
camcheck.check = lambda: 1 / 0
r = session.camera_check()
finally:
camcheck.check = orig
self.assertEqual(r["status"], "unknown")
if __name__ == "__main__":
unittest.main()
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""main.qml against ft_handrec.Backend: every backend.name(...) the window calls is a slot, and
every backend.name it reads is a property or a slot. A method that lost its @Slot shows up in
QML only as "is not a function" when its button is pressed (2026-10-03: Export did nothing).
Needs PySide6 (the dev container); skipped without it.
python3 hands/rec/tests/test_qml_backend.py
"""
import os
import re
import sys
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
REC = os.path.dirname(HERE)
sys.path.insert(0, REC)
class QmlBackendTest(unittest.TestCase):
def setUp(self):
try:
import ft_handrec
except ImportError as e:
self.skipTest(f"no PySide6: {e}")
meta = self.meta = ft_handrec.Backend.staticMetaObject
self.slots = {bytes(meta.method(i).name()).decode() for i in range(meta.methodCount())}
self.props = {meta.property(i).name() for i in range(meta.propertyCount())}
with open(os.path.join(REC, "main.qml")) as f:
self.qml = f.read()
def test_calls_are_slots(self):
called = set(re.findall(r"\bbackend\.(\w+)\s*\(", self.qml))
self.assertTrue(called)
self.assertEqual(sorted(called - self.slots), [], "called from main.qml but not a slot")
def test_call_arity(self):
"""Each backend.name(a, b) call passes as many arguments as some slot of that name takes
(a decorator left at the old count fails only when the button is pressed)."""
arity = {}
meta = self.meta
for i in range(meta.methodCount()):
mm = meta.method(i)
arity.setdefault(bytes(mm.name()).decode(), set()).add(mm.parameterCount())
bad = []
for m in re.finditer(r"\bbackend\.(\w+)\s*\(", self.qml):
depth, args, k, seen = 1, 0, m.end(), False
while depth and k < len(self.qml):
c = self.qml[k]
if c in "([{":
depth += 1
elif c in ")]}":
depth -= 1
elif c == "," and depth == 1:
args += 1
elif not c.isspace() and depth >= 1:
seen = True
k += 1
n = args + 1 if seen else 0
if m.group(1) in arity and n not in arity[m.group(1)]:
bad.append("%s: %d arguments, slots take %s" % (m.group(1), n, sorted(arity[m.group(1)])))
self.assertEqual(bad, [])
def test_reads_exist(self):
read = set(re.findall(r"\bbackend\.(\w+)\b(?!\s*\()", self.qml))
self.assertTrue(read)
self.assertEqual(sorted(read - self.props - self.slots), [], "read in main.qml but not on Backend")
if __name__ == "__main__":
unittest.main()
+634
View File
@@ -0,0 +1,634 @@
#!/usr/bin/env python3
"""Tests for session.py's step mode (dry runs, no processes): the ready, countdown and hold
timeline in prompts.jsonl, R (redo), the timed flow (--auto), the pose pictures' display rule,
the length estimates, and a take recorded in many parts through review, export and validate.
python3 hands/rec/tests/test_session.py
"""
import json
import os
import shutil
import sys
import tempfile
import struct
import time
import unittest
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import session # noqa: E402
import takes # noqa: E402
import validate # noqa: E402
from test_validate import fhset, make_session, SESSION # noqa: E402
SCRIPT = {
"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Test", "seconds": 1, "text": "A test."},
"done": {"title": "Done", "seconds": 0, "text": "Done."},
"stopped": {"title": "Stopped", "seconds": 0, "text": "Stopped."},
"sections": [
{"id": "poses", "title": "Poses", "intro": "Some poses.", "go": "Hold",
"prompts": [{"text": "Fist.", "seconds": 4, "hands": "left", "pose": "fist", "distance": "near",
"position": "left"},
{"text": "Open.", "seconds": 4, "hands": "both", "pose": "open"}]}]}
class SessionBase(unittest.TestCase):
"""Dry-run sessions of SCRIPT, steered from the test."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-session-test-")
self.script = os.path.join(self.tmp, "script.json")
with open(self.script, "w") as f:
json.dump(SCRIPT, f)
self.panel = []
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def session(self, **kw):
kw.setdefault("speed", 10)
s = session.Session(os.path.join(self.tmp, "base"), {}, {}, "room", self.script, dry_run=True,
poses_dir=os.path.join(self.tmp, "no-poses"), **kw)
s.print = self.panel.append
return s
def wait_for(self, s, pred, what, timeout=10):
end = time.monotonic() + timeout
while time.monotonic() < end:
st = dict(s._status)
if pred(st):
return st
time.sleep(0.005)
self.fail("timed out waiting for %s: %s" % (what, s._status))
def waiting(self, s, state, prompt=None):
return self.wait_for(s, lambda st: st["state"] == state and st["waiting"]
and (prompt is None or st["prompt"] == prompt), "%s %s" % (state, prompt or ""))
def events(self, s):
with open(os.path.join(s.session_dir, "takes", "01-poses", "prompts.jsonl")) as f:
return [json.loads(line) for line in f]
class SessionTest(SessionBase):
def test_step_flow(self):
s = self.session(next_after=0.0)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
self.assertEqual([e["event"] for e in ev],
["take", "ready", "prompt", "wait", "ready", "prompt", "wait", "end"])
self.assertEqual(ev[1]["id"], ev[2]["id"])
self.assertEqual(ev[1]["seconds"], session.COUNTDOWN_S)
self.assertTrue(ev[1]["t"] < ev[2]["t"] < ev[3]["t"] < ev[4]["t"])
# the countdown is recorded (3 s at 10x speed), and the hold after it
self.assertGreater(ev[2]["t"] - ev[1]["t"], 0.25e9)
with open(os.path.join(s.session_dir, "session.json")) as f:
self.assertEqual(json.load(f)["mode"], "step")
# a clock sample as each part starts (2 steps: 2 parts), for capture_ns (RAW) -> MONOTONIC
with open(os.path.join(s.session_dir, "takes", "01-poses", "take.json")) as f:
clock = json.load(f)["clock"]
self.assertEqual(len(clock), 2)
self.assertTrue(all(len(c) == 2 and all(isinstance(v, int) for v in c) for c in clock))
self.assertLess(clock[0][0], clock[1][0])
# the panel: Ready?, then the countdown, then the section's word for the hold, the diagram
self.assertIn("panel: action " + session.READY_TEXT, self.panel)
self.assertLess(self.panel.index("panel: big 3"), self.panel.index("panel: big 1"))
self.assertIn("panel: big Hold", self.panel)
self.assertIn("panel: where left near", self.panel)
self.assertIn("panel: rec on", self.panel)
def test_redo(self):
s = self.session()
s.start()
self.waiting(s, "starting")
s.next_step()
self.waiting(s, "intro")
s.redo() # nothing to do again yet: dropped
s.next_step()
st = self.waiting(s, "ready", "Fist.")
self.assertFalse(st["can_redo"])
s.next_step()
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
s.redo() # during the hold: it starts again
self.waiting(s, "ready", "Fist.")
s.next_step()
st = self.waiting(s, "ready", "Open.")
self.assertTrue(st["can_redo"])
s.redo() # at the next step's ready screen: the one before goes again
self.waiting(s, "ready", "Fist.")
s.next_step()
self.waiting(s, "ready", "Open.")
s.next_step()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
names = [e["event"] for e in ev]
self.assertEqual(names, ["take", "ready", "prompt", "redo", "wait", "ready", "prompt", "wait", "redo",
"ready", "prompt", "wait", "ready", "prompt", "wait", "end"])
first, second = ev[3], ev[8]
self.assertEqual(first["id"], "poses/fist/left/near/left")
self.assertEqual(first["from"], ev[1]["t"]) # from its countdown
self.assertTrue(ev[2]["t"] < first["to"] <= ev[4]["t"])
self.assertEqual((second["from"], second["id"]), (ev[5]["t"], first["id"]))
self.assertTrue(ev[6]["t"] < second["to"] <= ev[7]["t"])
# what labels keep: prompts outside every redo range
kept = [e["id"] for e in ev if e["event"] == "prompt"
and not any(r["from"] <= e["t"] <= r["to"] for r in ev if r["event"] == "redo")]
self.assertEqual(kept, ["poses/fist/left/near/left", "poses/open/both"])
def test_pause_while_waiting(self):
s = self.session()
s.start()
self.waiting(s, "starting")
s.next_step()
self.waiting(s, "intro")
s.next_step()
self.waiting(s, "ready", "Fist.")
s.pause()
self.wait_for(s, lambda st: st["state"] == "paused", "paused")
s.next_step() # ignored while paused
s.resume()
st = self.waiting(s, "ready", "Fist.")
s.stop(wait=10)
self.assertEqual(s.state, "stopped")
# nothing recorded: no take
self.assertEqual(os.listdir(os.path.join(s.session_dir, "takes")), [])
def test_auto(self):
s = self.session(auto=True, speed=20)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
self.assertEqual([e["event"] for e in ev], ["take", "prompt", "prompt", "prompt", "end"])
self.assertEqual(ev[1]["id"], "poses/intro")
def test_auto_redo_after_pause(self):
s = self.session(auto=True)
s.start()
self.wait_for(s, lambda st: st["state"] == "running" and st["prompt"] == "Fist.", "the first prompt")
s.pause()
self.wait_for(s, lambda st: st["state"] == "paused", "paused")
s.redo() # ends the pause; the prompt starts again, recording again
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "prompt", "prompt", "pause", "redo", "resume", "prompt", "prompt", "end"])
def test_pose_view(self):
d = os.path.join(self.tmp, "poses")
os.makedirs(d)
for name in ("fist.png", "cross.png"):
open(os.path.join(d, name), "wb").close()
with open(os.path.join(d, "poses.json"), "w") as f:
json.dump({"fist": {"file": "fist.png", "two_hands": False, "caption": "A fist"},
"cross": {"file": "../cross.png", "two_hands": True, "caption": ""},
"ok": {"file": "ok.png", "two_hands": False}}, f)
poses = session.load_poses(d)
fist = os.path.join(d, "fist.png")
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "right"}), (fist, "", "A fist"))
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "left"})[1], "mirror")
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "both"})[1], "both")
self.assertEqual(session.pose_view(poses, {"pose": "fist", "hands": "any"})[1], "")
# two hands drawn already; the file stays in the folder
self.assertEqual(session.pose_view(poses, {"pose": "cross", "hands": "both"})[:2],
(os.path.join(d, "cross.png"), ""))
self.assertEqual(session.pose_view(poses, {"pose": "ok", "hands": "both"}), ("", "", "")) # no file
self.assertEqual(session.pose_view(poses, {"pose": "claw", "hands": "both"}), ("", "", ""))
self.assertEqual(session.load_poses(os.path.join(self.tmp, "none")), {})
def test_plan(self):
plan, _ = session.build_plan(SCRIPT, {})
self.assertEqual(session.plan_steps(plan), 2)
self.assertEqual(session.plan_seconds(SCRIPT, plan, auto=False), 2 * session.COUNTDOWN_S + 8)
self.assertEqual(session.plan_seconds(SCRIPT, plan, auto=True), 1 + 1 + 8)
self.assertIn("2 steps", session.plan_summary(SCRIPT, plan))
SWEEP_SCRIPT = {
"version": 1, "intro_s": 1, "between_s": 1,
"welcome": {"title": "Test", "seconds": 1, "text": "A test."},
"done": {"title": "Done", "seconds": 0, "text": "Done."},
"stopped": {"title": "Stopped", "seconds": 0, "text": "Stopped."},
"cue_names": {"thumbs-up": "Thumbs up"},
"sections": [
{"id": "sweeps", "title": "Poses", "kind": "sweep", "intro": "Keep moving.", "quick": True,
"cue_s": 2, "step_s": 6,
"groups": [["open", "fist"], ["ok", "thumbs-up", "claw"]],
"sweeps": [{"hands": "both", "group": "next", "text": "Both hands."},
{"hands": "left", "group": "any", "quick": False, "text": "Left hand."}]}]}
class SweepTest(SessionBase):
def setUp(self):
super().setUp()
with open(self.script, "w") as f:
json.dump(SWEEP_SCRIPT, f)
def events(self, s):
with open(os.path.join(s.session_dir, "takes", "01-sweeps", "prompts.jsonl")) as f:
return [json.loads(line) for line in f]
def test_sweep_flow(self):
s = self.session(next_after=0.0, speed=10, seed=1)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
ev = self.events(s)
names = [e["event"] for e in ev]
self.assertEqual(names, ["take", "ready", "prompt", "prompt", "prompt", "wait",
"ready", "prompt", "prompt", "prompt", "wait", "end"])
plan = {p["id"]: p["cues"] for p in s.plan[0]["prompts"]}
for step, first in (("sweeps/both-1", 2), ("sweeps/left-1", 7)):
cues = [e for e in ev[first:first + 3]]
self.assertEqual([e["pose"] for e in cues], plan[step]) # one prompt per cue, in order
self.assertTrue(all(e["cue"] and e["step"] == step for e in cues))
self.assertTrue(all(e["distance"] == e["position"] == "" for e in cues))
self.assertEqual(ev[first - 1], dict(ev[first - 1], event="ready", id=step))
gaps = [(b["t"] - a["t"]) / 1e9 for a, b in zip(cues, cues[1:])]
self.assertTrue(all(0.15 < g < 0.4 for g in gaps), gaps) # cue_s 2 at 10x speed
# a cue repeated within a step (6 s of 2 s cues from a group of 2) gets its own id
both = [e["id"] for e in ev[2:5]]
self.assertEqual(len(set(both)), 3)
# the strip: every picture of the step, the cue lit
strips = [c for c in self.panel if c.startswith("panel: strip ")]
self.assertIn("panel: strip off", strips)
self.assertTrue(any(c.startswith("panel: strip 1 ") for c in strips))
with open(os.path.join(s.session_dir, "session.json")) as f:
meta = json.load(f)
self.assertEqual(meta["shuffle"]["seed"], 1)
self.assertEqual({x["id"]: x["cues"] for x in meta["shuffle"]["sweeps"]["sweeps"]}, plan)
self.assertFalse(meta["quick"])
def test_seed_from_session_id(self):
s = self.session(next_after=0.0, speed=20)
s.start()
s.join(20)
with open(os.path.join(s.session_dir, "session.json")) as f:
meta = json.load(f)
sid = os.path.basename(s.session_dir)
self.assertEqual(meta["shuffle"]["seed"], session.session_seed(sid))
again, _ = session.build_plan(SWEEP_SCRIPT, {}, seed=meta["shuffle"]["seed"]) # reproducible
self.assertEqual(session.plan_record(again), meta["shuffle"]["sweeps"])
def test_quick_session(self):
s = self.session(next_after=0.0, speed=20, quick=True)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
self.assertEqual([e["event"] for e in self.events(s)].count("ready"), 1) # the left sweep left out
with open(os.path.join(s.session_dir, "session.json")) as f:
self.assertTrue(json.load(f)["quick"])
def test_auto(self):
s = self.session(auto=True, speed=20)
s.start()
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "prompt"] + ["prompt"] * 6 + ["end"]) # intro, 3 cues a step
class ShuffleTest(unittest.TestCase):
def setUp(self):
self.script = session.load_script(session.SCRIPT_PATH)
def cues(self, seed, quick=False, checklist=None):
plan, _ = session.build_plan(self.script, checklist or {}, seed=seed, quick=quick)
return session.plan_record(plan)
def test_deterministic(self):
self.assertEqual(self.cues(42), self.cues(42))
self.assertNotEqual(self.cues(42)["pose-sweeps"], self.cues(43)["pose-sweeps"])
self.assertEqual(session.session_seed("20261002-202734"), session.session_seed("20261002-202734"))
self.assertNotEqual(session.session_seed("20261002-202734"), session.session_seed("20261002-202735"))
def test_groups(self):
groups = [sorted(g) for g in self.script["sections"][1]["groups"]]
for seed in range(20):
steps = self.cues(seed)["pose-sweeps"]
self.assertEqual([x["hands"] for x in steps], ["both", "both", "both", "left", "right"])
used = [sorted(set(x["cues"])) for x in steps]
self.assertEqual(sorted(used[:3]), sorted(groups)) # each group once with both hands
self.assertTrue(all(u in groups for u in used[3:]))
self.assertNotEqual(used[3], used[4]) # the one-hand sweeps differ
self.assertTrue(all(len(x["cues"]) == 5 for x in steps)) # 20 s of 4 s cues
# unshuffled: the script's order
steps = self.cues(None)["pose-sweeps"]
self.assertEqual(steps[0]["cues"], ["open", "fist", "point", "pinch", "open"])
# gestures and hand size keep their order
for seed in (1, 2, 3):
self.assertEqual([x["cues"] for x in self.cues(seed)["gestures"]],
[["pinch-tap", "pinch-drag"], ["grab", "cross", "overlap"], ["near-face", "screen-point"]])
self.assertEqual(self.cues(seed)["hand-size"][0]["cues"], ["flat", "flat-back", "spread"])
def test_plans(self):
full, skipped = session.build_plan(self.script, {}, seed=5)
self.assertEqual([s["id"] for s in full],
["hand-size", "pose-sweeps", "gestures", "desk-work", "touch", "bare-push", "no-hands"])
self.assertEqual(session.plan_steps(full), 15)
self.assertLess(session.plan_seconds(self.script, full, auto=False), 6 * 60)
everything, _ = session.build_plan(self.script, {"objects": ["pencil", "keyboard", "mouse"],
"controllers": "straps"}, seed=5)
self.assertEqual(len(everything), 10)
quick, skipped = session.build_plan(self.script, {"objects": ["pencil"], "controllers": "straps"},
seed=5, quick=True)
self.assertEqual([s["id"] for s in quick], ["hand-size", "pose-sweeps", "touch", "no-hands"])
self.assertEqual([p["hands"] for p in quick[1]["prompts"]], ["both"] * 3)
self.assertEqual(len(quick[2]["targets"]), 6)
self.assertLess(session.plan_seconds(self.script, quick, auto=False), 150)
self.assertIn({"section": "objects", "reason": "not in a quick round"}, skipped)
# desk work: the mouse-and-keyboard step only with both ticked
desk = [s for s in everything if s["id"] == "desk-work"][0]["prompts"]
self.assertEqual([p.get("cues") for p in desk], [None, ["mouse", "switch"]])
class StripPanelTest(unittest.TestCase):
"""The panel's strip command on ft-handpanel --no-vr (skipped if it isn't built)."""
def test_strip(self):
import subprocess
binary = session.PANEL_BIN
if not os.access(binary, os.X_OK):
self.skipTest("ft-handpanel isn't built")
name = "hrtest-strip-%d" % os.getpid()
proc = subprocess.Popen([binary, "--no-vr", "--socket", name], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True)
try:
panel = session.Panel(name=name)
for _ in range(50):
if panel.cmd("ping", reply=True, timeout=0.1):
break
if proc.poll() is not None:
self.skipTest("ft-handpanel doesn't run here: " + proc.stderr.read().strip()[-200:])
time.sleep(0.1)
else:
self.fail("ft-handpanel --no-vr doesn't answer")
poses = session.POSES_DIR
ok = panel.cmd("strip 1 %s/fist.png|mirror|Fist;-|-|No picture;%s/ok.png|-|OK" % (poses, poses), reply=True)
bad = panel.cmd("strip 1", reply=True)
missing = panel.cmd("strip 0 /nonexistent.png|-|Gone", reply=True)
panel.cmd("show", reply=True)
panel.cmd("strip off", reply=True)
panel.close()
finally:
proc.terminate()
out = proc.communicate(timeout=5)[0]
self.assertEqual(ok, "ok")
self.assertTrue(bad.startswith("error usage: strip"))
self.assertTrue(missing.startswith("error can't read"))
self.assertIn("strip: cue 0: Gone(/nonexistent.png)", out)
self.assertIn("strip: off", out)
# /proc/bus/input/devices as the Frame has it (2026-10-02), trimmed, plus a USB mouse.
DEVICES = """I: Bus=0019 Vendor=0001 Product=0001 Version=0100
N: Name="gpio-keys"
P: Phys=gpio-keys/input0
S: Sysfs=/devices/platform/gpio-keys/input/input3
U: Uniq=
H: Handlers=kbd kbd event3 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=3
B: KEY=100000000000 0 0 0 0 200000000 0 0 0 0 0
I: Bus=0006 Vendor=4d44 Product=0001 Version=0001
N: Name="frametop virtual mouse"
P: Phys=
S: Sysfs=/devices/virtual/input/input4
U: Uniq=
H: Handlers=event4 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=7
B: KEY=ffffff 0 0 0 0
B: REL=ffff
I: Bus=0003 Vendor=0001 Product=0001 Version=0001
N: Name="frame-voice keyboard"
P: Phys=py-evdev-uinput
S: Sysfs=/devices/virtual/input/input7
U: Uniq=
H: Handlers=kbd sysrq kbd event7 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=200003
B: KEY=1ffffffffffffff ffffffffffffffff ffffffffffffffff fffffffffffffffe
I: Bus=0005 Vendor=214e Product=0035 Version=0001
N: Name="Z3 Keyboard"
P: Phys=90:82:c3:5f:4a:a7
S: Sysfs=/devices/virtual/misc/uhid/0005:214E:0035.0005/input/input27
U: Uniq=da:ef:2f:d2:be:e2
H: Handlers=kbd sysrq kbd event9 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=10001f
B: KEY=300000000000 33eff 0 0 483ffff17aff32d bfd4444600000000 1 130ff38b17c007 ffff7bfad9415fff feb2ffdfffefffff fffffffffffffffe
B: REL=1040
B: MSC=10
"""
BT_MOUSE = """
I: Bus=0005 Vendor=214e Product=0035 Version=0001
N: Name="Z3 Mouse"
P: Phys=90:82:c3:5f:4a:a7
S: Sysfs=/devices/virtual/misc/uhid/0005:214E:0035.0005/input/input26
U: Uniq=da:ef:2f:d2:be:e2
H: Handlers=event8 qcom_pon_combo_timer_listener
B: PROP=0
B: EV=17
B: KEY=ffff0000 0 0 0 0
B: REL=1943
B: MSC=10
"""
USB_MOUSE = """
I: Bus=0003 Vendor=046d Product=c077 Version=0111
N: Name="Logitech USB Optical Mouse"
P: Phys=usb-xhci-hcd.1.auto-1/input0
S: Sysfs=/devices/platform/soc@0/a600000.usb/xhci-hcd.1.auto/usb1/1-1/1-1:1.0/0003:046D:C077.0001/input/input40
U: Uniq=
H: Handlers=mouse0 event13
B: PROP=0
B: EV=17
B: KEY=70000 0 0 0 0
B: REL=903
B: MSC=10
"""
def event(etype, code, value):
return session.INPUT_EVENT.pack(1, 2, etype, code, value)
PRESS = event(session.EV_KEY, session.KEY_SELECT, 1) + event(0, 0, 0)
RELEASE = event(session.EV_KEY, session.KEY_SELECT, 0) + event(0, 0, 0)
class InputTest(unittest.TestCase):
def test_devices(self):
devs = session.parse_input_devices(DEVICES)
self.assertEqual([d["name"] for d in devs], ["gpio-keys", "frametop virtual mouse", "frame-voice keyboard",
"Z3 Keyboard"])
self.assertEqual(session.find_button(devs), "/dev/input/event3")
self.assertFalse(any(session.real_mouse(d) for d in devs)) # the virtual mouse, keyboards with wheels
for extra, name in ((BT_MOUSE, "Z3 Mouse"), (USB_MOUSE, "Logitech USB Optical Mouse")):
mice = [d["name"] for d in session.parse_input_devices(DEVICES + extra) if session.real_mouse(d)]
self.assertEqual(mice, [name])
# another gpio-keys without KEY_SELECT isn't the button
self.assertIsNone(session.find_button(session.parse_input_devices(DEVICES.replace("200000000", "0"))))
def test_presses(self):
data = (PRESS + event(session.EV_KEY, session.KEY_SELECT, 2) * 3 # autorepeat: not presses
+ RELEASE + event(session.EV_KEY, 115, 1) + PRESS) # another key
self.assertEqual(session.button_presses(data), (2, b""))
n, rest = session.button_presses(PRESS + PRESS[:10])
self.assertEqual((n, rest), (1, PRESS[:10])) # half an event waits for the rest
self.assertEqual(session.button_presses(rest + PRESS[10:])[0], 1)
def test_reader_fifo(self):
tmp = tempfile.mkdtemp(prefix="handrec-button-test-")
try:
fifo = os.path.join(tmp, "button")
os.mkfifo(fifo)
presses = []
reader = session.ButtonReader(fifo, lambda: presses.append(time.monotonic()), debounce_s=0.3).start()
with open(fifo, "wb", buffering=0) as w:
w.write(PRESS + RELEASE)
w.write(PRESS[:7]) # a press split across writes, a bounce
time.sleep(0.05)
w.write(PRESS[7:] + RELEASE)
time.sleep(0.4)
w.write(PRESS + RELEASE)
time.sleep(0.2)
with open(fifo, "wb", buffering=0) as w: # the writer comes back: read again
time.sleep(0.4)
w.write(PRESS)
time.sleep(0.3)
reader.stop()
self.assertEqual(len(presses), 3)
self.assertTrue(reader.ok)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def test_missing_device(self):
logs = []
reader = session.ButtonReader("/nonexistent/event99", lambda: None, log=logs.append).start()
time.sleep(0.1)
reader.stop()
self.assertFalse(reader.ok)
self.assertIn("can't open", logs[0])
class ButtonSessionTest(SessionBase):
"""A dry run steered with a simulated headset button (a FIFO), with no mouse, then one."""
def test_button(self):
fifo = os.path.join(self.tmp, "button")
os.mkfifo(fifo)
procfile = os.path.join(self.tmp, "devices")
with open(procfile, "w") as f:
f.write(DEVICES)
writer = os.open(fifo, os.O_RDWR) # kept open, so the reader never sees the end
press = lambda: os.write(writer, PRESS + RELEASE)
try:
with mock.patch.object(session, "BUTTON_DEBOUNCE_S", 0.0):
s = self.session(speed=4, button_device=fifo)
s.input_devices = procfile
s.start()
st = self.waiting(s, "starting")
self.assertEqual((st["button"], st["mouse"], st["ready_text"]), (True, False, session.READY_BUTTON))
self.assertIn("panel: action " + session.READY_BUTTON, self.panel)
self.assertIn("panel: keys " + session.KEYS_STEP_BUTTON, self.panel)
press()
self.waiting(s, "intro")
press()
self.waiting(s, "ready", "Fist.")
press() # Next
self.wait_for(s, lambda st: st["state"] == "running", "the hold")
press() # pause
self.wait_for(s, lambda st: st["state"] == "paused", "paused")
with open(procfile, "a") as f: # a mouse arrives
f.write(BT_MOUSE)
press() # resume
st = self.waiting(s, "ready", "Open.")
self.assertEqual((st["mouse"], st["ready_text"]), (True, session.READY_BUTTON_MOUSE))
press()
s.join(20)
self.assertEqual(s.state, "done")
names = [e["event"] for e in self.events(s)]
self.assertEqual(names, ["take", "ready", "prompt", "pause", "resume", "wait", "ready", "prompt", "wait",
"end"])
finally:
os.close(writer)
def test_no_button(self):
s = self.session(next_after=0.0, button=False, button_device="/nonexistent")
s.start()
s.join(20)
self.assertEqual(s.state, "done")
self.assertIn("panel: action " + session.READY_TEXT, self.panel)
self.assertIn("panel: keys " + session.KEYS_STEP, self.panel)
class LightingTest(unittest.TestCase):
"""The measured lighting label: the mono cameras' ambient infrared."""
def ring(self, slam, upper):
return {"slam_left": {"mean": 70.0, "dark_mean": slam}, "slam_right": {"mean": 80.0, "dark_mean": slam},
"upper_left": {"mean": 50.0, "dark_mean": upper}, "upper_right": {"mean": 20.0, "dark_mean": upper}}
def test_indoor_and_daylight(self):
self.assertEqual(session.classify_lighting(self.ring(3.0, 0.5)), "indoor") # one lamp, 2026-10-02
self.assertEqual(session.classify_lighting(self.ring(3.7, 0.7)), "indoor") # a lamp-lit room
self.assertEqual(session.classify_lighting(self.ring(20.0, 8.0)), "daylight")
self.assertEqual(session.classify_lighting(self.ring(0.0, 0.0)), "") # no dark frames yet
self.assertEqual(session.classify_lighting(None), "")
self.assertEqual(session.ambient_ir(self.ring(3.0, 0.5)), 1.75)
def test_record(self):
rec = session.lighting_record("auto", self.ring(3.0, 0.5))
self.assertEqual((rec["chosen"], rec["source"], rec["measured"]), ("indoor", "measured", "indoor"))
rec = session.lighting_record("dim", self.ring(3.0, 0.5))
self.assertEqual((rec["chosen"], rec["source"], rec["measured"]), ("dim", "picked", "indoor"))
rec = session.lighting_record("auto", None)
self.assertEqual((rec["chosen"], rec["source"], rec["ring"]), ("", "measured", {}))
class ManyPartsTest(unittest.TestCase):
"""A take recorded in 40 parts (step mode stops the recording between steps): review reads
them in order, export makes one stream, validate passes."""
def setUp(self):
if not takes.find_zstd():
self.skipTest("no zstd")
self.tmp = tempfile.mkdtemp(prefix="handrec-parts-test-")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_parts(self):
make_session(self.tmp)
tdir = os.path.join(self.tmp, "sessions", SESSION, "takes", "01-hand-size")
t0 = 5 * 10 ** 12
for part in range(1, 41):
name = "sets.bin" if part == 1 else "sets-%d.bin" % part
with open(os.path.join(tdir, name), "wb") as f:
for i in range(3): # 3 sets a part, 10 s apart between parts
f.write(fhset(t0 + part * 10 ** 10 + i * 10 ** 8, part))
store = takes.Store(self.tmp)
index = takes.take_index(tdir)
self.assertEqual(len(index.parts), 40)
self.assertEqual(len(index), 120)
times = [index.time_ns(i) for i in range(len(index))]
self.assertEqual(times, sorted(times)) # sets-10.bin after sets-9.bin
self.assertAlmostEqual(index.duration_s(), 40 * 0.2) # the gaps between parts don't count
path = store.export(SESSION, low_priority=False)
r = validate.validate(path)
self.assertEqual(r.errors, [])
self.assertEqual(r.summary["sets"], 120 + 30)
if __name__ == "__main__":
unittest.main()
+269
View File
@@ -0,0 +1,269 @@
#!/usr/bin/env python3
"""Tests for the side cameras' naming in recordings (sides.py) and its readers: takes.py's
review and export, validate.py, and session.py's live decision and recording parts.
python3 hands/rec/tests/test_sides.py
"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import session # noqa: E402
import sides # noqa: E402
import takes # noqa: E402
import validate # noqa: E402
from test_validate import fhset, make_session, SESSION # noqa: E402
def names(record):
ncams = sides.HDR.unpack_from(record, 0)[1]
return [sides.CAM.unpack_from(record, sides.HDR.size + k * sides.CAM.size)[0].split(b"\0")[0].decode()
for k in range(ncams)]
class RulesTest(unittest.TestCase):
def test_rename_record(self):
rec = fhset(10 ** 9, 3)
out = sides.rename_record(rec)
self.assertEqual(names(rec), ["slam_left", "slam_right"])
self.assertEqual(names(out), ["slam_right", "slam_left"])
self.assertEqual(len(out), len(rec))
head = sides.HDR.size + 2 * sides.CAM.size
self.assertEqual(out[head:], rec[head:]) # pixels untouched
self.assertEqual(sides.rename_record(out), rec)
def test_other_name(self):
self.assertEqual(sides.other_name("slam_left_dk"), "slam_right_dk")
self.assertEqual(sides.other_name("upper_left"), "upper_left")
def test_needs_rename(self):
self.assertTrue(sides.needs_rename(True, False))
self.assertFalse(sides.needs_rename(True, True))
self.assertTrue(sides.needs_rename(False, True))
self.assertFalse(sides.needs_rename(None, True)) # unknown: leave the names
def test_part_rename(self):
sess = {"sides": {"swapped": True}}
take = {"parts": {"sets.bin": {"names_swapped": False}, "sets-2.bin": {"names_swapped": True}}}
self.assertTrue(sides.part_rename(sess, take, "sets.bin"))
self.assertFalse(sides.part_rename(sess, take, "sets-2.bin"))
self.assertTrue(sides.part_rename(sess, {}, "sets-3.bin")) # no record: as ft-camd named them
self.assertFalse(sides.part_rename({}, take, "sets.bin")) # no decision
def test_recording_runs(self):
d = tempfile.mkdtemp()
try:
self.assertEqual(sides.recording_runs(d), [(0, False)])
with open(os.path.join(d, "sides.json"), "w") as f:
json.dump({"swapped": True, "decided_by": "auto", "names_swapped": [[0, False], [37, True]]}, f)
runs = sides.recording_runs(d)
self.assertEqual(runs, [(0, True), (37, False)])
self.assertTrue(sides.rename_at(runs, 36))
self.assertFalse(sides.rename_at(runs, 37))
finally:
shutil.rmtree(d)
def test_read_live(self):
d = tempfile.mkdtemp()
try:
path, ring = os.path.join(d, "sides.json"), os.path.join(d, "cam-ring")
open(ring, "w").close()
now = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
live = {"pid": 1, "ring_ino": os.stat(ring).st_ino, "swapped": True, "decided_by": "auto",
"state": "decided", "updated_ns": now}
with open(path, "w") as f:
json.dump(live, f)
self.assertEqual(sides.read_live(path, ring)["swapped"], True)
self.assertIsNone(sides.read_live(path, ring, now_ns=now + 10 * 10 ** 9)) # stale
os.remove(ring)
open(ring, "w").close() # a new ft-camd: a new ring file
if os.stat(ring).st_ino != live["ring_ino"]:
self.assertIsNone(sides.read_live(path, ring))
self.assertIsNone(sides.read_live(os.path.join(d, "none.json")))
finally:
shutil.rmtree(d)
class TakesTest(unittest.TestCase):
"""A swapped session: one take's parts recorded before the decision (ft-camd's names) and
after it (named right)."""
def setUp(self):
if not takes.find_zstd():
self.skipTest("no zstd")
self.tmp = tempfile.mkdtemp(prefix="handrec-sides-test-")
make_session(self.tmp)
self.sdir = os.path.join(self.tmp, "sessions", SESSION)
meta = takes.read_json(os.path.join(self.sdir, "session.json"))
meta["sides"] = {"swapped": True, "decided_by": "auto", "state": "confirmed"}
takes.write_json(os.path.join(self.sdir, "session.json"), meta)
self.tdir = os.path.join(self.sdir, "takes", "01-hand-size")
with open(os.path.join(self.tdir, "sets-2.bin"), "wb") as f: # after the decision: --sides 1
for i in range(5):
f.write(sides.rename_record(fhset(9 * 10 ** 12 + i * 10 ** 8, i)))
tj = takes.read_json(os.path.join(self.tdir, "take.json"))
tj["parts"] = {"sets.bin": {"names_swapped": False}, "sets-2.bin": {"names_swapped": True}}
takes.write_json(os.path.join(self.tdir, "take.json"), tj)
self.store = takes.Store(self.tmp)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_review_reads_right_names(self):
index = takes.take_index(self.tdir)
self.assertEqual(index.rename, [True, False])
self.assertEqual([c["name"] for c in index.cams], ["slam_right", "slam_left"])
self.assertEqual([c["name"] for c in index.read_set(0)], ["slam_right", "slam_left"])
self.assertEqual([c["name"] for c in index.read_set(len(index) - 1)], ["slam_right", "slam_left"])
# the same pixels under the other name
raw = takes.TakeIndex(self.tdir).read_set(0, only="slam_right")[0]["pixels"]
self.assertEqual(raw, fhset(10 ** 12, 0)[sides.HDR.size + 2 * sides.CAM.size:][:32 * 24])
self.assertEqual(index.renamed_sets(), 30)
# the other take has no parts record: recorded as ft-camd named them, renamed too
other = takes.take_index(os.path.join(self.sdir, "takes", "02-no-hands"))
self.assertEqual(other.rename, [True])
def test_export_writes_right_names(self):
path = self.store.export(SESSION, low_priority=False)
r = validate.validate(path)
self.assertEqual(r.errors, [])
self.assertEqual(r.warnings, [])
m = takes.read_json(os.path.join(path, "manifest.json"))
t = m["takes"][0]
self.assertEqual(t["sides"], {"names_swapped": True, "renamed_sets": 30})
self.assertEqual(m["session"]["sides"]["swapped"], True)
self.assertEqual(takes.read_json(os.path.join(path, "takes", t["id"], "take.json"))["parts"],
{"sets.bin": {"names_swapped": True}})
# every exported set: right names (the rule applied again changes nothing)
data = subprocess.run([takes.find_zstd(), "-dc", os.path.join(path, t["file"])],
capture_output=True, check=True).stdout
off, seen = 0, 0
while off < len(data):
nbytes = sides.HDR.unpack_from(data, off)[2]
self.assertEqual(names(data[off:off + nbytes]), ["slam_right", "slam_left"])
off, seen = off + nbytes, seen + 1
self.assertEqual(seen, 35)
def test_validate_catches_wrong_names(self):
path = self.store.export(SESSION, low_priority=False)
mpath = os.path.join(path, "manifest.json")
m = takes.read_json(mpath)
m["takes"][0]["sides"]["names_swapped"] = False
takes.write_json(mpath, m)
report = validate.Report(path)
validate.check_manifest(m, report, path)
self.assertTrue(any("aren't named right" in e for e in report.errors), report.errors)
def test_undecided_warns(self):
meta = takes.read_json(os.path.join(self.sdir, "session.json"))
meta["sides"] = {"swapped": None}
takes.write_json(os.path.join(self.sdir, "session.json"), meta)
path = self.store.export(SESSION, low_priority=False)
r = validate.validate(path)
self.assertEqual(r.errors, [])
self.assertTrue(any("wasn't decided" in w for w in r.warnings), r.warnings)
m = takes.read_json(os.path.join(path, "manifest.json"))
self.assertIsNone(m["takes"][0]["sides"]["names_swapped"]) # the parts differ
self.assertEqual(m["takes"][0]["sides"]["renamed_sets"], 0)
def test_sides_command(self):
out = self.store.sides(SESSION)
self.assertTrue(out["sides"]["swapped"])
self.assertEqual(out["takes"]["01-hand-size"]["sets-2.bin"], {"names_swapped": True, "renamed_when_read": False})
out = self.store.sides(SESSION, False)
self.assertEqual(out["sides"]["decided_by"], "manual")
self.assertTrue(out["sides"]["replaced"]["swapped"])
self.assertTrue(out["takes"]["01-hand-size"]["sets-2.bin"]["renamed_when_read"])
self.assertEqual(takes.take_index(self.tdir).rename, [False, True]) # the cache saw session.json change
class SessionSidesTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-sides-session-")
self.script = os.path.join(self.tmp, "script.json")
with open(self.script, "w") as f:
json.dump({"version": 1, "sections": [{"id": "a", "title": "A", "prompts": [{"text": "x", "seconds": 1}]}]},
f)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def live(self, **kw):
d = dict(pid=1, ring_ino=0, mode="auto", state="decided", swapped=True, decided_by="auto",
evidence={"as_named": 0, "swapped": 10}, updated_ns=time.clock_gettime_ns(time.CLOCK_MONOTONIC))
d.update(kw)
with open(os.path.join(self.tmp, "sides.json"), "w") as f:
json.dump(d, f)
def test_read_sides(self):
s = session.Session(os.path.join(self.tmp, "base"), {}, {}, "room", self.script, dry_run=True,
hands_dir=self.tmp)
s.session_dir = self.tmp
s._session_json = {"sides": {"swapped": None}}
s._read_sides(force=True)
self.assertIsNone(s._sides_swapped()) # no file
self.live(swapped=None, state="deciding", decided_by=None)
s._read_sides(force=True)
self.assertIsNone(s._sides_swapped())
self.live()
s._read_sides(force=True)
self.assertTrue(s._sides_swapped())
self.assertEqual(s._session_json["sides"]["evidence"]["swapped"], 10)
self.live(state="confirmed")
s._read_sides(force=True)
self.assertEqual(s._session_json["sides"]["state"], "confirmed")
self.live(swapped=False, state="decided, reversed")
s._read_sides(force=True)
self.assertFalse(s._sides_swapped())
self.assertTrue(s._session_json["sides"]["reversed_from"]["swapped"])
self.assertFalse(takes.read_json(os.path.join(self.tmp, "session.json"))["sides"]["swapped"])
def test_recorder_parts(self):
calls = []
class FakeProc:
returncode = 0
def __init__(self, argv, **kw):
calls.append(argv)
def poll(self):
return 0
take = os.path.join(self.tmp, "take")
os.makedirs(take)
with mock.patch.object(session.subprocess, "Popen", FakeProc):
r1 = session.Recorder(take, 1, 10, None, None)
r2 = session.Recorder(take, 2, 10, None, None, swap=True)
r3 = session.Recorder(take, 3, 10, None, None, swap=False)
argv = [c[c.index("--sides") + 1] for c in calls]
self.assertEqual(argv, ["auto", "1", "0"])
# ft-hands' DIR/sides.json goes into names_swapped and away
os.makedirs(r2.dir, exist_ok=True)
with open(os.path.join(r2.dir, "sets.bin"), "wb") as f:
f.write(fhset(10 ** 9, 0))
with open(os.path.join(r2.dir, "sides.json"), "w") as f:
json.dump({"swapped": None, "names_swapped": [[0, True]]}, f)
r2.stop()
self.assertTrue(r2.names_swapped)
self.assertEqual(r2.file, "sets-2.bin")
self.assertTrue(os.path.isfile(os.path.join(take, "sets-2.bin")))
self.assertFalse(os.path.exists(r2.dir))
with open(os.path.join(take, "sides.json"), "w") as f:
json.dump({"swapped": None, "names_swapped": [[0, False]]}, f)
r1.stop()
self.assertFalse(r1.names_swapped)
self.assertFalse(os.path.exists(os.path.join(take, "sides.json")))
self.assertFalse(r3.names_swapped)
if __name__ == "__main__":
unittest.main()
+556
View File
@@ -0,0 +1,556 @@
#!/usr/bin/env python3
"""Tests for validate.py and hub.py (no network): a good export, and broken ones.
python3 hands/rec/tests/test_validate.py (in the dev container, or anywhere with zstd)
"""
import hashlib
import json
import os
import shutil
import struct
import sys
import tempfile
import unittest
import uuid
from unittest import mock
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import hub # noqa: E402
import session # noqa: E402
import takes # noqa: E402
import validate # noqa: E402
SESSION = "20261002-101500"
DEVICE = {"cv": {"cad_from_cal": {"method": "FrontAndUpperCamPositions", "plus_x": [0.63, -0.77, 0.02],
"plus_z": [-0.45, -0.35, 0.82], "position": [-0.05, -0.02, 0.04]}},
"head": {"plus_x": [-1, 0, 0], "plus_z": [0, 0, -1], "position": [0, 0, 0]}}
CAMS = [("slam_left", 32, 24), ("slam_right", 32, 24)]
def fhset(t_ns, seed):
"""One FHSET01 record: header, camera headers, pixels."""
pixels = b"".join(bytes((seed + i) % 256 for i in range(w * h)) for _, w, h in CAMS)
size = validate.HDR.size + validate.CAM.size * len(CAMS) + len(pixels)
out = validate.HDR.pack(b"FHSET01\0", len(CAMS), size)
for name, w, h in CAMS:
out += validate.CAM.pack(name.encode(), w, h, t_ns - 1000, t_ns)
return out + pixels
def write_sums(export):
sums = []
for root, _, files in os.walk(export):
for name in files:
rel = os.path.relpath(os.path.join(root, name), export)
if rel != "SHA256SUMS":
with open(os.path.join(root, name), "rb") as f:
sums.append((rel, hashlib.sha256(f.read()).hexdigest()))
with open(os.path.join(export, "SHA256SUMS"), "w") as f:
for rel, digest in sorted(sums):
f.write(f"{digest} {rel}\n")
def make_session(base, contributor=None, sid=None, device=True):
"""A small recorded session in base, as session.py leaves it."""
contributor = contributor or str(uuid.uuid4())
os.makedirs(base, exist_ok=True)
takes.write_json(os.path.join(base, "profile.json"), {
"schema": 1, "contributor": contributor,
"consent": {"version": "2026-10-02", "accepted": "2026-10-02T10:00:00+00:00", "adult": True},
"optional": {"handedness": "right", "notes": ""}})
sdir = os.path.join(base, "sessions", sid or SESSION)
os.makedirs(os.path.join(sdir, "takes"))
takes.write_json(os.path.join(sdir, "session.json"), {
"schema": 1, "tool": "ft-handrec test", "started": "2026-10-02T10:15:00+0000", "contributor": contributor,
"lighting": {"chosen": "room", "ring": {}},
"checklist": {"objects": ["pencil"], "own_objects": ["stapler"], "controllers": "none", "sleeves": "",
"rings": False, "watch": False, "notes": ""},
"device": {"steamos": "3.8", "steamvr": "r25358740+28b72a4f-1", "cameras": [{"name": n, "width": w, "height": h}
for n, w, h in CAMS]},
"calibration_removed": ["serial"], "takes": ["01-hand-size", "02-no-hands"], "status": "done",
"sides": {"swapped": False, "decided_by": "auto", "state": "confirmed"}})
takes.write_json(os.path.join(sdir, "calibration.json"),
{"cameras": [{"name": "slam_left", "intrinsics": [1.0, 2.0, 3.0]}]})
if device:
takes.write_json(os.path.join(sdir, "device.json"), DEVICE)
for k, tid in enumerate(("01-hand-size", "02-no-hands")):
tdir = os.path.join(sdir, "takes", tid)
os.makedirs(tdir)
t0 = 10 ** 12 * (k + 1)
with open(os.path.join(tdir, "sets.bin"), "wb") as f:
for i in range(30):
f.write(fhset(t0 + i * 100_000_000, i))
with open(os.path.join(tdir, "prompts.jsonl"), "w") as f:
f.write(json.dumps({"t": t0, "event": "take", "section": tid[3:], "take": tid}) + "\n")
f.write(json.dumps({"t": t0 + 5, "event": "end", "status": "complete"}) + "\n")
with open(os.path.join(tdir, "poses.jsonl"), "w") as f:
for i in range(10):
f.write(json.dumps({"t": t0 + i, "hmd": {"m": [0.0] * 12, "r": 200, "ok": True},
"left": None, "right": None}) + "\n")
takes.write_json(os.path.join(tdir, "take.json"), {"section": tid[3:], "title": tid, "started_ns": t0,
"ended_ns": t0 + 3 * 10 ** 9, "status": "complete",
"deleted": [], "notes": ""})
return contributor
class ValidateTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not takes.find_zstd():
raise unittest.SkipTest("no zstd")
cls.tmp = tempfile.mkdtemp(prefix="handrec-validate-test-")
cls.base = os.path.join(cls.tmp, "base")
cls.contributor = make_session(cls.base)
cls.store = takes.Store(cls.base)
# One deleted range, so the export leaves sets out.
index = takes.take_index(cls.store.take_dir(SESSION, "01-hand-size"))
cls.store.delete_range(SESSION, "01-hand-size", index.time_ns(3), index.time_ns(5))
cls.export = cls.store.export(SESSION, low_priority=False)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def copy(self):
d = tempfile.mkdtemp(dir=self.tmp)
dest = os.path.join(d, SESSION)
shutil.copytree(self.export, dest)
return dest
def assertError(self, report, text):
self.assertTrue(any(text in e for e in report.errors), f"no error with {text!r}: {report.errors}")
def test_good(self):
r = validate.validate(self.export)
self.assertEqual(r.errors, [])
self.assertEqual(r.warnings, [])
self.assertTrue(os.path.isfile(os.path.join(self.export, "device.json")))
self.assertEqual(r.summary["takes"], 2)
self.assertEqual(r.summary["sets"], 57)
self.assertEqual(r.summary["consent_version"], "2026-10-02")
self.assertEqual(r.summary["contributor"], self.contributor)
def test_extra_file(self):
d = self.copy()
with open(os.path.join(d, "notes.txt"), "w") as f:
f.write("hello\n")
os.makedirs(os.path.join(d, "takes", "01-hand-size", "extra"))
r = validate.validate(d)
self.assertError(r, "notes.txt: not an allowed file")
self.assertError(r, "not in SHA256SUMS: notes.txt")
self.assertError(r, "extra/: not an allowed folder")
def test_symlink(self):
d = self.copy()
os.symlink("/etc/hostname", os.path.join(d, "takes", "01-hand-size", "take.json.link"))
self.assertError(validate.validate(d), "a symlink")
def test_bad_checksum(self):
d = self.copy()
path = os.path.join(d, "takes", "02-no-hands", "poses.jsonl")
with open(path, "r+b") as f:
f.seek(5)
f.write(b"9") # "t": 2... becomes "t": 9...: still valid JSON
r = validate.validate(d)
self.assertError(r, "checksum mismatch: takes/02-no-hands/poses.jsonl")
self.assertEqual(len(r.errors), 1, r.errors)
def test_calibration_serial(self):
d = self.copy()
takes.write_json(os.path.join(d, "calibration.json"),
{"cameras": [{"name": "slam_left", "serial": "X", "label": "unit 4H2K19A7731"}]})
write_sums(d)
r = validate.validate(d)
self.assertError(r, "calibration.json: identifying fields left in")
self.assertIn("cameras[0].serial", r.errors[0])
self.assertIn("cameras[0].label", r.errors[0])
self.assertEqual(len(r.errors), 1, r.errors)
def test_truncated_zst(self):
d = self.copy()
path = os.path.join(d, "takes", "01-hand-size", "sets.bin.zst")
os.truncate(path, os.path.getsize(path) // 2)
write_sums(d)
r = validate.validate(d)
self.assertTrue(any("sets.bin.zst" in e and ("cut short" in e or "set " in e or "decompress" in e)
for e in r.errors), r.errors)
def test_truncated_zst_command(self):
"""The same with the zstd program (Python before 3.14)."""
d = self.copy()
path = os.path.join(d, "takes", "01-hand-size", "sets.bin.zst")
os.truncate(path, os.path.getsize(path) // 2)
with mock.patch.object(validate, "_zstd", None):
r = validate.validate(d)
self.assertTrue(any("sets.bin.zst" in e and "checksum" not in e for e in r.errors), r.errors)
self.assertEqual(validate.validate(self.export).errors, [])
def test_garbage_records(self):
d = self.copy()
rec = bytearray(fhset(10 ** 9, 0))
rec[validate.HDR.size:validate.HDR.size + 16] = b"slam left!\0\0\0\0\0\0"
zst = os.path.join(d, "takes", "02-no-hands", "sets.bin.zst")
with open(zst + ".raw", "wb") as f:
f.write(bytes(rec))
os.system(f"zstd -q -f {zst}.raw -o {zst} && rm {zst}.raw")
write_sums(d)
self.assertError(validate.validate(d), "a camera name that isn't one")
def test_manifest(self):
d = self.copy()
path = os.path.join(d, "manifest.json")
with open(path) as f:
m = json.load(f)
m["contributor"] = m["profile"]["contributor"] = str(uuid.uuid1())
m["consent_version"] = ""
m["profile"]["consent"]["version"] = ""
m["takes"][0]["sets"] += 1
m["session"]["dry_run"] = True
m["session"]["device"]["serial_number"] = "x"
del m["exported"]
takes.write_json(path, m)
with open(os.path.join(d, "takes", "02-no-hands", "prompts.jsonl"), "a") as f:
f.write("{not json\n")
write_sums(d)
r = validate.validate(d)
self.assertError(r, "isn't a random uuid4")
self.assertError(r, "the consent version is empty")
self.assertError(r, "27 sets, the manifest says 28")
self.assertError(r, "dry-run session")
self.assertError(r, "identifying fields: session.device.serial_number")
self.assertError(r, "exported is missing")
self.assertError(r, "prompts.jsonl line 3: not valid JSON")
def test_region(self):
"""From consent 2026-10-03, the residency confirmation must be there."""
d = self.copy()
path = os.path.join(d, "manifest.json")
with open(path) as f:
m = json.load(f)
m["consent_version"] = m["profile"]["consent"]["version"] = "2026-10-03"
takes.write_json(path, m)
write_sums(d)
self.assertError(validate.validate(d), "Illinois, Texas or Washington")
m["profile"]["consent"]["region_ok"] = True
takes.write_json(path, m)
write_sums(d)
self.assertEqual(validate.validate(d).errors, [])
def test_device(self):
d = self.copy()
bad = json.loads(json.dumps(DEVICE))
bad["device_serial_number"] = "X"
bad["head"]["position"] = [0, 0]
takes.write_json(os.path.join(d, "device.json"), bad)
write_sums(d)
r = validate.validate(d)
self.assertError(r, "expected cv and head only")
self.assertError(r, "head.position isn't 3 numbers")
self.assertError(r, "device.json: identifying fields: device_serial_number")
def test_no_device(self):
"""Sessions from before device.json still pass, with a warning."""
d = self.copy()
os.remove(os.path.join(d, "device.json"))
write_sums(d)
r = validate.validate(d)
self.assertEqual(r.errors, [])
self.assertTrue(any("no device.json" in w for w in r.warnings), r.warnings)
def test_zstandard(self):
"""The zstandard package's path (the maintainer's Windows PC), good and truncated."""
if validate._zstandard is None:
self.skipTest("no zstandard")
with mock.patch.object(validate, "_zstd", None):
self.assertEqual(validate.validate(self.export).errors, [])
d = self.copy()
path = os.path.join(d, "takes", "01-hand-size", "sets.bin.zst")
os.truncate(path, os.path.getsize(path) // 2)
write_sums(d)
self.assertError(validate.validate(d), "sets.bin.zst: the zstd stream is cut short")
def test_frames(self):
"""Several zstd frames one after another (zstd -T2 can write them) read as one stream."""
if validate._zstd is None and validate._zstandard is None:
self.skipTest("no compression.zstd or zstandard")
d = self.copy()
zst = os.path.join(d, "takes", "02-no-hands", "sets.bin.zst")
with open(zst, "rb") as f:
one = f.read()
with open(zst, "ab") as f:
f.write(one)
with open(os.path.join(d, "manifest.json")) as f:
m = json.load(f)
m["takes"][1]["sets"] *= 2
m["takes"][1]["raw_bytes"] *= 2
takes.write_json(os.path.join(d, "manifest.json"), m)
write_sums(d)
r = validate.validate(d)
self.assertEqual([e for e in r.errors if "go back" not in e], [])
def test_cli(self):
self.assertEqual(os.system(f"{sys.executable} {validate.__file__} {self.export} --json >/dev/null"), 0)
d = self.copy()
os.remove(os.path.join(d, "manifest.json"))
self.assertNotEqual(os.system(f"{sys.executable} {validate.__file__} {d} >/dev/null"), 0)
class ExportJsonlTest(unittest.TestCase):
"""takes.export_jsonl: deleted ranges and the controllers when the checklist says none."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-jsonl-test-")
ctrl = {"m": [0.0] * 12, "r": 200, "ok": True}
with open(os.path.join(self.tmp, "poses.jsonl"), "w") as f:
for t in range(10):
f.write(json.dumps({"t": t, "hmd": ctrl, "left": ctrl, "right": ctrl}) + "\n")
with open(os.path.join(self.tmp, "prompts.jsonl"), "w") as f:
for e in ({"t": 1, "event": "prompt", "id": "a"}, {"t": 4, "event": "feedback", "left": True},
{"t": 7, "event": "feedback", "left": True, "controller": {"left": "ok"}}):
f.write(json.dumps(e) + "\n")
os.makedirs(os.path.join(self.tmp, "out"))
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def run_export(self, name, keep):
out = os.path.join(self.tmp, "out", name)
takes.export_jsonl(os.path.join(self.tmp, name), out, [[3, 5]], keep)
with open(out) as f:
return [json.loads(line) for line in f]
def test_no_controllers(self):
poses = self.run_export("poses.jsonl", False)
self.assertEqual([p["t"] for p in poses], [0, 1, 2, 6, 7, 8, 9]) # 3-5 deleted
self.assertTrue(all(p["left"] is None and p["right"] is None and p["hmd"] for p in poses))
prompts = self.run_export("prompts.jsonl", False)
self.assertEqual([e["t"] for e in prompts], [1, 7]) # the feedback at 4 was in a deleted range
self.assertNotIn("controller", prompts[1])
def test_with_controllers(self):
poses = self.run_export("poses.jsonl", True)
self.assertTrue(all(p["left"] and p["right"] for p in poses))
self.assertIn("controller", self.run_export("prompts.jsonl", True)[1])
class SessionFilesTest(unittest.TestCase):
"""session.py's device.json, and session ids with a suffix."""
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="handrec-session-test-")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_write_device(self):
full = dict(json.loads(json.dumps(DEVICE)), device_serial_number="ABC12345678", display_edid="00ff",
model_number="Frame")
src = os.path.join(self.tmp, "device_config.json")
takes.write_json(src, full)
s = session.Session.__new__(session.Session)
s.session_dir, s._log = self.tmp, lambda text: None
with mock.patch.object(session, "host_path", lambda p: src if p.endswith("device_config.json") else None):
self.assertEqual(s._write_device(), [])
with open(os.path.join(self.tmp, "device.json")) as f:
self.assertEqual(json.load(f), DEVICE)
with mock.patch.object(session, "host_path", lambda p: None):
self.assertEqual(s._write_device(), [])
def test_suffix_id(self):
if not takes.find_zstd():
self.skipTest("no zstd")
sid = SESSION + "-2"
make_session(self.tmp, sid=sid)
store = takes.Store(self.tmp)
self.assertEqual([x["id"] for x in store.sessions()], [sid])
path = store.export(sid, low_priority=False)
self.assertEqual(validate.validate(path).errors, [])
class LoginTest(unittest.TestCase):
"""hub.login: the link and code go out first, the token is saved by huggingface_hub and never
passed on, and a refused login is a "login" error. huggingface_hub's helpers are faked."""
def setUp(self):
try:
import huggingface_hub._login
import huggingface_hub.utils._oauth_device
except ImportError as e:
self.skipTest(f"no huggingface_hub browser login: {e}")
self.login_mod = huggingface_hub._login
self.device = huggingface_hub.utils._oauth_device
def test_code_then_saved(self):
told, saved = [], []
info = {"verification_uri_complete": "https://hf.co/oauth/device", "user_code": "ABCD-1234", "expires_in": 300}
with mock.patch.object(self.device, "request_device_code", return_value=info), \
mock.patch.object(self.device, "poll_device_token", return_value={"access_token": "secret"}), \
mock.patch.object(self.login_mod, "_save_oauth_token", side_effect=saved.append), \
mock.patch.object(hub, "whoami", return_value={"name": "someone", "role": ""}):
who = hub.login(lambda phase, text, **extra: told.append(dict(extra, phase=phase)))
self.assertEqual(told, [{"phase": "code", "url": info["verification_uri_complete"], "code": "ABCD-1234",
"expires_in": 300}])
self.assertEqual(saved, [{"access_token": "secret"}])
self.assertEqual(who["name"], "someone")
self.assertNotIn("secret", json.dumps(told) + json.dumps(who))
def test_refused(self):
from huggingface_hub.errors import DeviceCodeError
info = {"verification_uri_complete": "u", "user_code": "c", "expires_in": 300}
with mock.patch.object(self.device, "request_device_code", return_value=info), \
mock.patch.object(self.device, "poll_device_token", side_effect=DeviceCodeError("access_denied")):
with self.assertRaises(hub.HubError) as cm:
hub.login()
self.assertEqual(cm.exception.kind, "login")
class HubTest(unittest.TestCase):
"""hub.py without the network: the dry run, the draft gate, upload records."""
def setUp(self):
if not takes.find_zstd():
self.skipTest("no zstd")
self.tmp = tempfile.mkdtemp(prefix="handrec-hub-test-")
self.contributor = make_session(self.tmp)
self.store = takes.Store(self.tmp)
self.store.export(SESSION, low_priority=False)
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_dry_run(self):
logged = []
with mock.patch.dict(os.environ, {hub.DATASET_ENV: "someone/test-hands"}):
result = hub.upload(self.store, SESSION, dry_run=True, log=logged.append)
self.assertTrue(result["dry_run"])
self.assertEqual(result["repo"], "someone/test-hands")
self.assertEqual(result["path_in_repo"], f"contributions/{self.contributor}/{SESSION}")
self.assertIn("- Takes: 2", result["commit_description"])
self.assertIn("- Consent version: 2026-10-02", result["commit_description"])
self.assertIn("- Objects: pencil (+1 of their own)", result["commit_description"])
self.assertTrue(any("manifest.json" in line for line in logged))
self.assertEqual(hub.uploads(self.store, SESSION), []) # a dry run records nothing
def test_dataset_env(self):
self.assertEqual(hub.dataset_id(), hub.HF_DATASET)
with mock.patch.dict(os.environ, {hub.DATASET_ENV: "not a repo"}):
self.assertRaises(hub.HubError, hub.dataset_id)
def test_draft_gate(self):
with mock.patch.object(hub, "texts_draft", return_value=True), \
mock.patch.dict(os.environ, {hub.ALLOW_ENV: ""}):
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION)
self.assertEqual(cm.exception.kind, "closed")
self.assertFalse(hub.upload_allowed())
with mock.patch.object(hub, "texts_draft", return_value=True), \
mock.patch.dict(os.environ, {hub.ALLOW_ENV: "1"}):
self.assertTrue(hub.upload_allowed())
def test_invalid_blocks(self):
with open(os.path.join(self.store.export_dir(SESSION), "extra.bin"), "w") as f:
f.write("x")
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION, dry_run=True)
self.assertEqual(cm.exception.kind, "invalid")
self.assertTrue(cm.exception.errors)
def test_record_and_duplicate(self):
export = self.store.export_dir(SESSION)
sha = hub.export_sha(export)
self.assertEqual(len(sha), 64)
hub.record_upload(self.store, SESSION, {"repo": "a/b", "pr_url": "https://huggingface.co/datasets/a/b/discussions/1",
"uploaded": hub.now_iso(), "export_sha": sha})
# The upload record doesn't make the export look out of date...
self.assertFalse(self.store.sessions()[0]["export_stale"])
# ...and the next upload of the same export stops, unless asked again.
with self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION, dry_run=True)
self.assertEqual(cm.exception.kind, "duplicate")
self.assertTrue(hub.upload(self.store, SESSION, dry_run=True, again=True)["dry_run"])
# A new export leaves the records out of its manifest.
self.store.export(SESSION, low_priority=False)
with open(os.path.join(export, "manifest.json")) as f:
self.assertNotIn("uploads", json.load(f)["session"])
def test_pull_request_first(self):
"""The pull request opens before the files go; a retry goes on in it."""
calls = []
class Pr:
def __init__(self, num, status="draft"):
self.num, self.status, self.is_pull_request = num, status, True
self.url = f"https://huggingface.co/datasets/a/b/discussions/{num}"
class Api:
fail = True
status = "draft"
def whoami(self):
return {"name": "someone", "auth": {"accessToken": {"role": "write"}}}
def auth_check(self, repo, repo_type=None):
pass
def create_pull_request(self, repo, title, description=None, repo_type=None):
calls.append("create")
return Pr(7)
def get_discussion_details(self, repo, num, repo_type=None):
return Pr(num, Api.status)
def upload_folder(self, **kw):
calls.append(("upload", kw["revision"], kw.get("create_pr")))
if Api.fail:
raise ConnectionResetError("reset")
def change_discussion_status(self, repo, num, status, repo_type=None):
calls.append(("status", num, status))
fake = mock.Mock(HfApi=Api)
seen = []
env = {hub.DATASET_ENV: "a/b", hub.ALLOW_ENV: "1"}
with mock.patch.dict(os.environ, env), mock.patch.object(hub, "_hf", return_value=fake):
with self.assertRaises(hub.HubError):
hub.upload(self.store, SESSION, progress=lambda phase, text, fraction=None, **extra: seen.append(
(phase, extra.get("pr_url"))))
self.assertIn(("opened", "https://huggingface.co/datasets/a/b/discussions/7"), seen)
[rec] = hub.uploads(self.store, SESSION)
self.assertEqual((rec["status"], rec["pr_num"]), ("started", 7))
self.assertIsNone(hub.previous_upload(self.store, SESSION, rec["export_sha"])) # not a duplicate
Api.fail = False
result = hub.upload(self.store, SESSION)
self.assertEqual(calls, ["create", ("upload", "refs/pr/7", None), ("upload", "refs/pr/7", None),
("status", 7, "open")]) # the retry reused #7
self.assertEqual(result["pr_url"], "https://huggingface.co/datasets/a/b/discussions/7")
[rec] = hub.uploads(self.store, SESSION)
self.assertEqual(rec["status"], "done")
with mock.patch.dict(os.environ, env), self.assertRaises(hub.HubError) as cm:
hub.upload(self.store, SESSION, dry_run=True)
self.assertEqual(cm.exception.kind, "duplicate")
def test_explain(self):
try:
import httpx
from huggingface_hub import errors as hf
except ImportError:
self.skipTest("no huggingface_hub")
def response(code):
return httpx.Response(code, request=httpx.Request("POST", "https://huggingface.co/api/x"))
cases = [(hf.GatedRepoError("gated", response=response(403)), "terms"),
(hf.RepositoryNotFoundError("nope", response=response(404)), "not-found"),
(hf.HfHubHTTPError("no", response=response(403)), "permission"),
(hf.HfHubHTTPError("bad token", response=response(401)), "login"),
(hf.LocalTokenNotFoundError("none"), "login"),
(httpx.ConnectError("down"), "network"),
(ConnectionResetError("reset"), "network")]
for exc, kind in cases:
e = hub.explain(exc, "a/b")
self.assertEqual(e.kind, kind, exc)
self.assertIn("https://huggingface.co/datasets/a/b", hub.explain(cases[0][0], "a/b").link)
if __name__ == "__main__":
unittest.main()
+768
View File
@@ -0,0 +1,768 @@
#!/usr/bin/env python3
"""Check a hand recorder export before it's uploaded, or when it's received (DESIGN.md "Upload").
The window runs it before an upload and refuses on errors; the maintainer runs it on each
submission. Standard library only. Given an export folder (takes.py's exports/<session>/), it
checks:
- SHA256SUMS: every file listed and matching, nothing missing from it;
- an allow-list of files: anything else (or a symlink) is an error;
- manifest.json: the schema, required keys and types, and that it agrees with the files;
- the consent version is there, the contributor id is a random uuid4, the contributor is an adult;
- calibration.json has nothing session.py's strip_calibration would still remove;
- device.json (the rig's pose in the CAD frame) holds only cv.cad_from_cal and head, as
plus_x, plus_z and position; sessions recorded before it existed get a warning;
- each sets.bin.zst decompresses to the end (so a truncated one fails) and parses as FHSET01:
every set's header is checked (camera names, sizes, record length) and counted against the
manifest; the pixels themselves aren't looked at;
- every .jsonl line parses, and take.json does;
- the side cameras (sides.py): the session's "sides" decision, and each take's files named
right by it (a warning when it wasn't decided: the maintainer's check tells then);
- the total size.
It runs on Linux and Windows, with Python 3.12 or later. It reports errors (don't upload or accept this) and warnings (look at it).
usage: validate.py DIR [--json] exit status 0: no errors, 1: errors, 2: not an export
"""
import argparse
import hashlib
import json
import math
import os
import re
import shutil
import struct
import subprocess
import sys
import uuid
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from session import _key_identifies, strip_calibration # noqa: E402 (standard library only, next to this file)
# Decompression, the first that's there: Python 3.14's compression.zstd, the zstandard package
# (pip install zstandard: the maintainer's Windows PC), the zstd program.
try:
from compression import zstd as _zstd
except ImportError:
_zstd = None
try:
import zstandard as _zstandard
except ImportError:
_zstandard = None
EXPORT_SCHEMA = 1
TOP_FILES = {"manifest.json", "calibration.json", "device.json", "SHA256SUMS"}
REGION_CONSENT = "2026-10-03" # the consent version that added the residency confirmation
TAKE_FILES = {"prompts.jsonl", "poses.jsonl", "take.json", "sets.bin.zst"}
TAKE_RE = re.compile(r"^\d{2}-[a-z0-9][a-z0-9-]*$")
SESSION_RE = re.compile(r"^\d{8}-\d{6}(?:-\d+)?$")
SUM_RE = re.compile(r"^([0-9a-f]{64}) (\S.*)$")
CAM_NAME_RE = re.compile(r"^[a-z][a-z0-9_]{0,15}$")
TAKE_STATUSES = ("complete", "stopped", "skipped")
HDR = struct.Struct("<8sII") # fh_set_hdr_t: magic, ncams, bytes (hands/track/record.h)
CAM = struct.Struct("<16sIIQQ") # fh_set_cam_t: name, width, height, capture_ns, dqbuf_ns
MAX_CAMS = 16
MIN_SIDE, MAX_SIDE = 16, 4096
# One round is about 10 GB before compression (ft_handrec.ROUND_BYTES), a few GB after it.
WARN_BYTES = 15 * 1000 ** 3
MAX_BYTES = 40 * 1000 ** 3
CHUNK = 1 << 20
OUT_CHUNK = 8 << 20
# zstandard's decompressobj has no output limit: it gets the input this much at a time, so even a
# stream made to inflate hugely gives out a few hundred MB at most per call.
ZSTANDARD_PIECE = 8 << 10
MAX_LISTED = 10 # removed calibration paths and the like: list this many, then "and N more"
class Cancelled(Exception):
pass
class Report:
def __init__(self, path):
self.path = path
self.errors = []
self.warnings = []
self.summary = {}
self.bytes = 0
def error(self, text):
self.errors.append(text)
def warn(self, text):
self.warnings.append(text)
@property
def ok(self):
return not self.errors
def as_dict(self):
return {"path": self.path, "ok": self.ok, "errors": self.errors, "warnings": self.warnings,
"summary": self.summary, "bytes": self.bytes}
def listed(items):
items = list(items)
more = len(items) - MAX_LISTED
return ", ".join(items[:MAX_LISTED]) + (f" and {more} more" if more > 0 else "")
def is_uuid4(s):
try:
u = uuid.UUID(s)
except (TypeError, ValueError, AttributeError):
return False
return u.version == 4 and str(u) == s
def sha256_file(path, step=None, cancelled=lambda: False):
h = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(CHUNK):
if cancelled():
raise Cancelled()
h.update(chunk)
if step:
step(len(chunk))
return h.hexdigest()
# ---------------------------------------------------------------- the files
def walk_files(root, report):
"""The export's files as relative paths, and allow-list errors on the way."""
files = []
for dirpath, dirnames, filenames in os.walk(root):
rel_dir = os.path.relpath(dirpath, root).replace(os.sep, "/")
rel_dir = "" if rel_dir == "." else rel_dir
depth = 0 if not rel_dir else rel_dir.count("/") + 1
for d in list(dirnames):
rel = f"{rel_dir}/{d}" if rel_dir else d
ok = (depth == 0 and d == "takes") or (depth == 1 and rel_dir == "takes" and TAKE_RE.match(d))
if os.path.islink(os.path.join(dirpath, d)):
report.error(f"{rel}: a symlink, not allowed in an export")
dirnames.remove(d)
elif not ok:
report.error(f"{rel}/: not an allowed folder")
dirnames.remove(d)
for name in filenames:
rel = f"{rel_dir}/{name}" if rel_dir else name
full = os.path.join(dirpath, name)
if os.path.islink(full) or not os.path.isfile(full):
report.error(f"{rel}: a symlink or special file, not allowed in an export")
continue
if not ((depth == 0 and name in TOP_FILES) or (depth == 2 and name in TAKE_FILES)):
report.error(f"{rel}: not an allowed file")
files.append(rel)
return sorted(files)
def check_sums(root, files, report, step, cancelled):
path = os.path.join(root, "SHA256SUMS")
if not os.path.isfile(path):
report.error("SHA256SUMS is missing")
return
sums = {}
with open(path, encoding="utf-8", errors="replace") as f:
for n, line in enumerate(f, 1):
line = line.rstrip("\n")
m = SUM_RE.match(line)
if not m:
report.error(f"SHA256SUMS line {n}: not \"<sha256> <path>\"")
continue
digest, rel = m.groups()
if rel.startswith("/") or ".." in rel.split("/") or rel == "SHA256SUMS":
report.error(f"SHA256SUMS line {n}: a path that doesn't belong: {rel}")
continue
if rel in sums:
report.error(f"SHA256SUMS lists {rel} twice")
sums[rel] = digest
present = set(files) - {"SHA256SUMS"}
missing = sorted(set(sums) - present)
if missing:
report.error(f"in SHA256SUMS but missing: {listed(missing)}")
unlisted = sorted(present - set(sums))
if unlisted:
report.error(f"not in SHA256SUMS: {listed(unlisted)}")
bad = []
for rel in sorted(set(sums) & present):
if sha256_file(os.path.join(root, rel), step, cancelled) != sums[rel]:
bad.append(rel)
if bad:
report.error(f"checksum mismatch: {listed(bad)}")
def read_json_file(path, rel, report):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except OSError as e:
report.error(f"{rel}: can't read it: {e.strerror or e}")
except ValueError as e:
report.error(f"{rel}: not valid JSON: {e}")
return None
def check_jsonl(path, rel, report, cancelled):
"""Every line a JSON object with a time "t"."""
try:
with open(path, encoding="utf-8") as f:
for n, line in enumerate(f, 1):
if n % 50000 == 0 and cancelled():
raise Cancelled()
if not line.strip():
continue
try:
obj = json.loads(line)
except ValueError as e:
report.error(f"{rel} line {n}: not valid JSON: {e}")
return
if not isinstance(obj, dict) or not isinstance(obj.get("t"), int):
report.error(f"{rel} line {n}: not an object with a time \"t\"")
return
except UnicodeDecodeError:
report.error(f"{rel}: not UTF-8 text")
except OSError as e:
report.error(f"{rel}: can't read it: {e.strerror or e}")
# ---------------------------------------------------------------- FHSET01 inside the zstd stream
class SetParser:
"""Feed it the decompressed stream in pieces: it checks each set's header and skips the
pixels. problem holds the first thing wrong (parsing stops there)."""
def __init__(self):
self.buf = bytearray()
self.skip = 0 # pixel bytes of the current set still to pass over
self.sets = 0
self.raw = 0
self.cams = {} # name -> (width, height), every camera seen
self.first = None # the first set's cameras, [{name, width, height}]
self.last_t = 0
self.backwards = 0 # sets whose earliest dqbuf_ns went back in time
self.problem = ""
def feed(self, data):
if self.problem:
return
self.raw += len(data)
view = memoryview(data)
while len(view) and not self.problem:
if self.skip:
n = min(self.skip, len(view))
self.skip -= n
view = view[n:]
continue
self.buf += view
view = view[len(view):]
self._parse()
def _parse(self):
while not self.problem and not self.skip:
if len(self.buf) < HDR.size:
return
magic, ncams, nbytes = HDR.unpack_from(self.buf, 0)
where = f"set {self.sets + 1}"
if magic != b"FHSET01\0":
self.problem = f"{where}: not an FHSET01 record"
return
if not 0 < ncams <= MAX_CAMS:
self.problem = f"{where}: {ncams} cameras"
return
head = HDR.size + CAM.size * ncams
if len(self.buf) < head:
return
pixels, cams, times = 0, [], []
for k in range(ncams):
raw_name, w, h, _, dqbuf_ns = CAM.unpack_from(self.buf, HDR.size + k * CAM.size)
name_bytes, _, pad = raw_name.partition(b"\0")
name = name_bytes.decode("ascii", errors="replace")
if pad.strip(b"\0") or not CAM_NAME_RE.match(name):
self.problem = f"{where}: a camera name that isn't one: {raw_name!r}"
return
if not (MIN_SIDE <= w <= MAX_SIDE and MIN_SIDE <= h <= MAX_SIDE):
self.problem = f"{where}: camera {name} is {w}x{h}"
return
if self.cams.setdefault(name, (w, h)) != (w, h):
self.problem = f"{where}: camera {name} changed size to {w}x{h}"
return
pixels += w * h
cams.append({"name": name, "width": w, "height": h})
times.append(dqbuf_ns)
if nbytes != head + pixels:
self.problem = f"{where}: {nbytes} bytes, but its cameras need {head + pixels}"
return
if self.first is None:
self.first = cams
t = min(times)
if t < self.last_t:
self.backwards += 1
self.last_t = t
self.sets += 1
rest = len(self.buf) - head
if rest >= pixels:
del self.buf[:head + pixels]
else:
self.skip = pixels - rest
self.buf.clear()
def finish(self):
"""After the stream's end: a set cut short is a problem."""
if not self.problem and (self.skip or self.buf):
self.problem = f"the stream ends inside set {self.sets + 1}"
def find_zstd():
found = shutil.which("zstd")
if found:
return found
return next((p for p in ("/usr/bin/zstd", "/run/host/usr/bin/zstd") if os.access(p, os.X_OK)), None)
class Frames:
"""A zstd stream, decompressed piece by piece with compression.zstd or zstandard, frame after
frame (zstd -T2 may write several). feed(data) yields the output; complete is false while a
frame is unfinished, which at the end of the input means the stream was cut short."""
def __init__(self):
self.dec = self._new()
self.fed = False # the current decompressor has had input
@staticmethod
def _new():
return _zstd.ZstdDecompressor() if _zstd is not None else _zstandard.ZstdDecompressor().decompressobj()
@property
def complete(self):
return self.dec.eof or not self.fed
def feed(self, data):
while data:
if self.dec.eof: # another frame follows the one that ended
self.dec, self.fed = self._new(), False
if _zstd is not None:
out = self.dec.decompress(data, max_length=OUT_CHUNK)
data = b""
self.fed = True
yield out
# More output may wait without more input.
while not self.dec.eof and not self.dec.needs_input:
yield self.dec.decompress(b"", max_length=OUT_CHUNK)
else:
piece, data = data[:ZSTANDARD_PIECE], data[ZSTANDARD_PIECE:]
self.fed = True
out = self.dec.decompress(piece)
if out:
yield out
if self.dec.eof:
data = self.dec.unused_data + data
def check_sets(path, rel, entry, report, step, cancelled):
"""Decompress rel as a stream and parse it. entry: its take in the manifest, or None."""
parser = SetParser()
try:
if _zstd is not None or _zstandard is not None:
frames = Frames()
with open(path, "rb") as f:
while not parser.problem and (data := f.read(CHUNK)):
if cancelled():
raise Cancelled()
step(len(data))
for out in frames.feed(data):
parser.feed(out)
if parser.problem:
break
if not parser.problem and not frames.complete:
report.error(f"{rel}: the zstd stream is cut short")
return
else:
zstd = find_zstd()
if not zstd:
report.warn(f"{rel}: not checked: no zstd (Python 3.14's compression.zstd, the zstandard "
"package or the zstd program)")
return
argv = [zstd, "-dcq", path]
if os.name == "posix" and shutil.which("nice"):
argv = ["nice", "-n", "19"] + argv
proc = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
try:
while not parser.problem and (data := proc.stdout.read(CHUNK)):
if cancelled():
raise Cancelled()
parser.feed(data)
except BaseException:
proc.kill()
proc.wait()
proc.stdout.close()
raise
if parser.problem:
proc.kill()
code = proc.wait()
proc.stdout.close()
step(os.path.getsize(path))
if not parser.problem and code != 0:
report.error(f"{rel}: doesn't decompress (zstd exit {code})")
return
except Cancelled:
raise
except Exception as e: # OSError, compression.zstd.ZstdError
report.error(f"{rel}: doesn't decompress: {e}")
return
parser.finish()
if parser.problem:
report.error(f"{rel}: not a valid FHSET01 recording: {parser.problem}")
return
if parser.sets == 0:
report.error(f"{rel}: holds no frame sets")
if parser.backwards:
report.warn(f"{rel}: {parser.backwards} sets go back in time")
if entry is not None:
if entry.get("sets") != parser.sets:
report.error(f"{rel}: {parser.sets} sets, the manifest says {entry.get('sets')}")
if "raw_bytes" in entry and entry.get("raw_bytes") != parser.raw:
report.error(f"{rel}: {parser.raw} bytes uncompressed, the manifest says {entry.get('raw_bytes')}")
if isinstance(entry.get("cameras"), list) and parser.first is not None and entry["cameras"] != parser.first:
report.error(f"{rel}: its cameras don't match the manifest's")
return parser
# ---------------------------------------------------------------- the manifest
def need(obj, key, types, where, report, required=True):
"""obj[key] if it's of the given type(s); an error otherwise."""
if not isinstance(obj, dict) or key not in obj:
if required:
report.error(f"manifest: {where}{key} is missing")
return None
v = obj[key]
allowed = types if isinstance(types, tuple) else (types,)
if not isinstance(v, allowed) or (isinstance(v, bool) and bool not in allowed):
report.error(f"manifest: {where}{key} has the wrong type ({type(v).__name__})")
return None
return v
def check_pose(pose, where, report, extra=()):
"""A pose as device_config.json has it: plus_x, plus_z, position, each 3 finite numbers."""
if not isinstance(pose, dict):
report.error(f"device.json: {where} isn't an object")
return
for key in ("plus_x", "plus_z", "position"):
v = pose.get(key)
if not (isinstance(v, list) and len(v) == 3 and all(isinstance(x, (int, float)) and not isinstance(x, bool)
and math.isfinite(x) for x in v)):
report.error(f"device.json: {where}.{key} isn't 3 numbers")
unknown = set(pose) - {"plus_x", "plus_z", "position"} - set(extra)
if unknown:
report.error(f"device.json: {where} has unexpected keys: {listed(sorted(unknown))}")
def check_device(dev, report):
"""device.json: only cv.cad_from_cal and head (session.py's _write_device)."""
if not isinstance(dev, dict):
report.error("device.json: not a JSON object")
return
if set(dev) != {"cv", "head"}:
report.error(f"device.json: keys {listed(sorted(dev))}, expected cv and head only")
cv = dev.get("cv")
if not isinstance(cv, dict) or set(cv) != {"cad_from_cal"}:
report.error("device.json: cv should hold cad_from_cal only")
else:
check_pose(cv["cad_from_cal"], "cv.cad_from_cal", report, extra=("method",))
if not isinstance(cv["cad_from_cal"].get("method", ""), str):
report.error("device.json: cv.cad_from_cal.method isn't text")
if "head" in dev:
check_pose(dev["head"], "head", report)
_, removed = strip_calibration(dev)
if removed:
report.error(f"device.json: identifying fields: {listed(removed)}")
def identifying_keys(o, path):
"""Paths of keys under o that name a serial, uuid, mac or id (session.py's rule)."""
out = []
if isinstance(o, dict):
for k, v in o.items():
p = f"{path}.{k}"
out += [p] if _key_identifies(k) else identifying_keys(v, p)
elif isinstance(o, list):
for i, v in enumerate(o):
out += identifying_keys(v, f"{path}[{i}]")
return out
def check_manifest(m, report, root):
"""The manifest's keys and types. Returns {take id: entry} for the file checks."""
if not isinstance(m, dict):
report.error("manifest: not a JSON object")
return {}
if m.get("schema") != EXPORT_SCHEMA:
report.error(f"manifest: schema {m.get('schema')!r}, expected {EXPORT_SCHEMA}")
tool = need(m, "tool", str, "", report)
if tool is not None and not tool.startswith("ft-handrec"):
report.warn(f"manifest: tool is {tool!r}")
need(m, "exported", str, "", report)
sid = need(m, "session_id", str, "", report)
if sid is not None and not SESSION_RE.match(sid):
report.error(f"manifest: session_id {sid!r} isn't a session id")
if sid and SESSION_RE.match(os.path.basename(root)) and os.path.basename(root) != sid:
report.warn(f"the folder is named {os.path.basename(root)}, the manifest's session is {sid}")
contributor = need(m, "contributor", str, "", report)
if contributor is not None and not is_uuid4(contributor):
report.error(f"manifest: the contributor id {contributor!r} isn't a random uuid4")
parent = os.path.basename(os.path.dirname(root))
if contributor and is_uuid4(parent) and parent != contributor:
report.error(f"the export sits under contributor {parent}, but its manifest says {contributor}")
consent = need(m, "consent_version", str, "", report)
if consent is not None and not consent.strip():
report.error("manifest: the consent version is empty")
profile = need(m, "profile", dict, "", report)
if profile is not None:
if profile.get("contributor") != contributor:
report.error("manifest: profile.contributor differs from contributor")
pc = need(profile, "consent", dict, "profile.", report)
if pc is not None:
if pc.get("version") != consent:
report.error("manifest: profile.consent.version differs from consent_version")
if pc.get("adult") is not True:
report.error("manifest: the contributor didn't confirm being 18 or older")
# from consent 2026-10-03: not living in Illinois, Texas or Washington (CONSENT.md)
if str(pc.get("version") or "") >= REGION_CONSENT and pc.get("region_ok") is not True:
report.error("manifest: the contributor didn't confirm not living in Illinois, Texas or Washington")
need(pc, "accepted", str, "profile.consent.", report)
optional = profile.get("optional")
if isinstance(optional, dict) and str(optional.get("notes") or "").strip():
report.warn("the profile's notes are included: check they hold nothing private")
extra = set(profile) - {"schema", "contributor", "consent", "optional"}
if extra:
report.error(f"manifest: the profile has unexpected keys: {listed(sorted(extra))}")
session = need(m, "session", dict, "", report)
if session is not None:
if session.get("contributor") not in (contributor, ""):
report.error("manifest: session.contributor differs from contributor")
for key, t in (("started", str), ("lighting", dict), ("checklist", dict), ("device", dict),
("takes", list)):
need(session, key, t, "session.", report)
if session.get("dry_run"):
report.error("this is a dry-run session: it has no real recordings")
if "uploads" in session:
report.warn("manifest: session.uploads is included (earlier uploads' links)")
if not isinstance(session.get("calibration_removed", []), list):
report.error("manifest: session.calibration_removed isn't a list")
checklist = session.get("checklist")
if isinstance(checklist, dict) and str(checklist.get("notes") or "").strip():
report.warn("the checklist's notes are included: check they hold nothing private")
# Keys only: version strings like SteamVR's "r25358740+28b72a4f-1" look like serials.
keys = identifying_keys(session.get("device"), "session.device")
if keys:
report.error(f"manifest: identifying fields: {listed(keys)}")
if "/home/" in json.dumps(m):
report.warn("manifest: it mentions a home folder path (a username may show)")
entries = {}
takes = need(m, "takes", list, "", report)
for i, t in enumerate(takes or []):
where = f"takes[{i}]."
if not isinstance(t, dict):
report.error(f"manifest: takes[{i}] isn't an object")
continue
tid = need(t, "id", str, where, report)
if tid is None:
continue
if not TAKE_RE.match(tid):
report.error(f"manifest: take id {tid!r} isn't one")
continue
if tid in entries:
report.error(f"manifest: take {tid} is listed twice")
entries[tid] = t
for key, typ in (("section", str), ("title", str), ("status", str), ("sets", int),
("sets_deleted", int), ("cameras", list), ("duration_s", (int, float))):
need(t, key, typ, where, report)
if t.get("status") not in TAKE_STATUSES:
report.warn(f"manifest: take {tid} has status {t.get('status')!r}")
f = t.get("file")
if f is None:
if t.get("sets"):
report.error(f"manifest: take {tid} has {t.get('sets')} sets but no file")
elif f != f"takes/{tid}/sets.bin.zst":
report.error(f"manifest: take {tid}'s file is {f!r}")
elif not isinstance(t.get("raw_bytes"), int):
report.error(f"manifest: take {tid} has a file but no raw_bytes")
check_sides(m, entries, report)
return entries
def check_sides(m, entries, report):
"""Which side camera is which (sides.py): session.sides.swapped is true, false or null, and
every take's files carry names_swapped equal to it (export renames them so)."""
session = m.get("session") if isinstance(m.get("session"), dict) else {}
s = session.get("sides")
if s is None:
report.warn("manifest: no session.sides (recorded before the side cameras were checked): "
"the maintainer's check tells which way round they are")
return
if not isinstance(s, dict) or s.get("swapped") not in (True, False, None):
report.error("manifest: session.sides isn't {\"swapped\": true|false|null, ...}")
return
swapped = s["swapped"]
if swapped is None:
report.warn("the side cameras' naming wasn't decided while recording (no live tracker): "
"the maintainer's check tells which way round they are")
for tid, t in entries.items():
ts = t.get("sides")
if ts is None:
continue
if not isinstance(ts, dict) or ts.get("names_swapped") not in (True, False, None):
report.error(f"manifest: take {tid}'s sides isn't {{\"names_swapped\": true|false|null, ...}}")
elif swapped is not None and ts["names_swapped"] != swapped:
report.error(f"take {tid}: its side cameras aren't named right (names_swapped "
f"{ts['names_swapped']}, the session's swapped {swapped}): export it again")
def summarize(m):
"""What a pull request's description says about the export: takes, minutes, lighting,
objects, controllers, the consent and tool versions."""
if not isinstance(m, dict):
return {}
session = m.get("session") if isinstance(m.get("session"), dict) else {}
checklist = session.get("checklist") if isinstance(session.get("checklist"), dict) else {}
lighting = session.get("lighting") if isinstance(session.get("lighting"), dict) else {}
takes = [t for t in m.get("takes") or [] if isinstance(t, dict)]
seconds = sum(t.get("duration_s") or 0 for t in takes if isinstance(t.get("duration_s"), (int, float)))
return {"session": m.get("session_id", ""), "contributor": m.get("contributor", ""),
"takes": sum(1 for t in takes if t.get("file")), "takes_listed": len(takes),
"sets": sum(t.get("sets") or 0 for t in takes if isinstance(t.get("sets"), int)),
"minutes": round(seconds / 60, 1), "lighting": lighting.get("chosen", ""),
"objects": list(checklist.get("objects") or []), "own_objects": len(checklist.get("own_objects") or []),
"controllers": checklist.get("controllers", ""), "consent_version": m.get("consent_version", ""),
"tool": m.get("tool", "")}
# ---------------------------------------------------------------- all of it
def validate(root, progress=None, cancel=None):
"""Check the export at root. progress(fraction 0..1, text) is called as it goes; cancel()
(or cancel.is_set()) returning true raises Cancelled. Returns a Report."""
root = os.path.abspath(root)
report = Report(root)
cancelled = getattr(cancel, "is_set", cancel) or (lambda: False)
tell = progress or (lambda fraction, text: None)
if not os.path.isdir(root):
report.error(f"{root}: no such folder")
return report
files = walk_files(root, report)
sizes = {rel: os.path.getsize(os.path.join(root, rel)) for rel in files}
report.bytes = sum(sizes.values())
# Work: each file's checksum, plus reading each sets.bin.zst again to decompress it.
total = max(1, report.bytes + sum(n for rel, n in sizes.items() if rel.endswith(".zst")))
done = 0
def step(n, text):
nonlocal done
done += n
tell(min(done / total, 0.999), text)
tell(0.0, "Checking checksums")
check_sums(root, files, report, lambda n: step(n, "Checking checksums"), cancelled)
manifest = None
if "manifest.json" in files:
manifest = read_json_file(os.path.join(root, "manifest.json"), "manifest.json", report)
else:
report.error("manifest.json is missing")
entries = check_manifest(manifest, report, root) if manifest is not None else {}
report.summary = summarize(manifest)
if "calibration.json" in files:
cal = read_json_file(os.path.join(root, "calibration.json"), "calibration.json", report)
if cal is not None:
if not isinstance(cal, dict):
report.error("calibration.json: not a JSON object")
else:
_, removed = strip_calibration(cal)
if removed:
report.error(f"calibration.json: identifying fields left in: {listed(removed)}")
else:
report.warn("no calibration.json: the recordings can't be used in 3D without it")
if "device.json" in files:
dev = read_json_file(os.path.join(root, "device.json"), "device.json", report)
if dev is not None:
check_device(dev, report)
else:
report.warn("no device.json (a session from before it was recorded): the labeller falls back to "
"another unit's head frame")
take_dirs = sorted({rel.split("/")[1] for rel in files if rel.startswith("takes/") and rel.count("/") == 2})
for tid in take_dirs:
if tid not in entries:
report.error(f"takes/{tid}/ isn't in the manifest")
for tid, entry in entries.items():
if tid not in take_dirs:
report.error(f"take {tid} is in the manifest but has no folder")
for tid in take_dirs:
if cancelled():
raise Cancelled()
base = f"takes/{tid}/"
title = (entries.get(tid) or {}).get("title") or tid
for name in ("prompts.jsonl", "poses.jsonl"):
rel = base + name
if rel in sizes:
check_jsonl(os.path.join(root, rel), rel, report, cancelled)
else:
report.warn(f"{rel} is missing")
if base + "take.json" in sizes:
tj = read_json_file(os.path.join(root, base + "take.json"), base + "take.json", report)
if tj is not None and not isinstance(tj, dict):
report.error(f"{base}take.json: not a JSON object")
else:
report.warn(f"{base}take.json is missing")
rel = base + "sets.bin.zst"
entry = entries.get(tid)
if rel in sizes:
check_sets(os.path.join(root, rel), rel, entry, report,
lambda n, title=title: step(n, f"Checking {title}"), cancelled)
elif entry is not None and entry.get("file"):
report.error(f"{rel} is missing")
if report.bytes > MAX_BYTES:
report.error(f"the export is {report.bytes / 1000 ** 3:.1f} GB, over the {MAX_BYTES / 1000 ** 3:.0f} GB limit")
elif report.bytes > WARN_BYTES:
report.warn(f"the export is large: {report.bytes / 1000 ** 3:.1f} GB")
tell(1.0, "Checked")
return report
def main():
ap = argparse.ArgumentParser(description="Check a hand recorder export (an exports/<session>/ folder).")
ap.add_argument("dir")
ap.add_argument("--json", action="store_true", help="print the result as JSON")
a = ap.parse_args()
if not os.path.isdir(a.dir):
print(f"{a.dir}: no such folder", file=sys.stderr)
return 2
if hasattr(os, "setpriority"): # not on Windows
try:
os.setpriority(os.PRIO_PROCESS, 0, 19) # checksums and decompression: stay out of VR's way
except OSError:
pass
report = validate(a.dir)
if a.json:
print(json.dumps(report.as_dict(), indent=2))
else:
for e in report.errors:
print(f"error: {e}")
for w in report.warnings:
print(f"warning: {w}")
s = report.summary
if s:
print(f"{s.get('session')}: {s.get('takes')} takes, {s.get('sets')} sets, {s.get('minutes')} min, "
f"{report.bytes / 1000 ** 2:.1f} MB, consent {s.get('consent_version') or '-'}")
print("OK" if report.ok else f"{len(report.errors)} errors")
return 0 if report.ok else 1
if __name__ == "__main__":
sys.exit(main())
+146
View File
@@ -0,0 +1,146 @@
// Unit tests for the side cameras' naming check (track/sides.h), on made-up cameras and a
// made-up hand: no models, no recordings. make check (in the dev container) builds and runs it.
#include "../track/sides.h"
#include <cstdio>
#include <cstdlib>
namespace {
int failures = 0;
#define CHECK(c) \
do { \
if (!(c)) std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c), ++failures; \
} while (0)
V3 cross(V3 a, V3 b) { return {a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]}; }
// An equidistant fisheye (k = 0) at origin, looking along look, image "down" toward head -y.
Camera camera(const char *name, V3 origin, V3 look, int w, int h, double f) {
Camera c;
c.name = name, c.width = w, c.height = h, c.fx = c.fy = f, c.cx = w / 2.0, c.cy = h / 2.0;
const V3 z = unit(look), down{0, -1, 0};
const V3 y = unit(down - z * dot(down, z)), x = cross(y, z);
for (int i = 0; i < 3; ++i) c.R[i][0] = x[i], c.R[i][1] = y[i], c.R[i][2] = z[i];
c.origin = origin;
return c;
}
// MediaPipe-like world landmarks (m, hand-centred, flat: z = 0): x across the palm, y along the fingers
const double kHand[21][2] = {{0, 0}, {0.03, 0.03}, {0.05, 0.05}, {0.065, 0.07}, {0.075, 0.09},
{0.025, 0.09}, {0.025, 0.13}, {0.025, 0.155}, {0.025, 0.175}, {0.005, 0.095},
{0.005, 0.14}, {0.005, 0.165}, {0.005, 0.185}, {-0.015, 0.09}, {-0.015, 0.13},
{-0.015, 0.155}, {-0.015, 0.17}, {-0.033, 0.08}, {-0.033, 0.11}, {-0.033, 0.13},
{-0.033, 0.145}};
// The hand with its wrist at p, the palm facing toward `facing`, as cam sees it.
Landmarks view(const Camera &cam, V3 p, V3 facing) {
const V3 n = unit(facing - p), up0{0, 1, 0};
const V3 along = unit(up0 - n * dot(up0, n)), across = cross(along, n);
Landmarks lm;
for (int k = 0; k < 21; ++k) {
const V3 q = p + across * kHand[k][0] + along * kHand[k][1];
lm.pts[k] = cam.project(q, nullptr);
lm.world[k][0] = kHand[k][0], lm.world[k][1] = kHand[k][1], lm.world[k][2] = 0;
}
lm.presence = 0.9;
return lm;
}
Seen seen(const std::string &cam, const Landmarks &lm) { return Seen{cam, 0, Roi{}, lm, {}}; }
} // namespace
int main() {
std::map<std::string, Camera> cams;
cams["slam_left"] = camera("slam_left", {-0.045, 0, -0.03}, {-0.5, -0.6, -0.6}, 1056, 1024, 300);
cams["slam_right"] = camera("slam_right", {0.045, 0, -0.03}, {0.5, -0.6, -0.6}, 1056, 1024, 300);
cams["upper_left"] = camera("upper_left", {-0.03, 0.02, -0.04}, {-0.2, 0.1, -1}, 640, 480, 180);
cams["upper_right"] = camera("upper_right", {0.03, 0.02, -0.04}, {0.2, 0.1, -1}, 640, 480, 180);
const Camera &L = cams["slam_left"], &R = cams["slam_right"], &UL = cams["upper_left"], &UR = cams["upper_right"];
const V3 hand{0.0, -0.22, -0.35}, eyes{0, 0, -0.03};
const Landmarks inL = view(L, hand, eyes), inR = view(R, hand, eyes), inUL = view(UL, hand, eyes),
inUR = view(UR, hand, eyes);
SideCheck sc(cams);
CHECK(sc.usable());
// 1. the side pair, named right: meets as named, not swapped
SideCheck::Miss m = sc.test("slam_left", inL, "slam_right", inR);
std::printf("side pair as named: miss %.4f m as named, %.4f swapped\n", m.m[0], m.m[1]);
CHECK(m.m[0] >= 0 && m.m[0] < 0.001);
CHECK(SideCheck::vote(m) == 0);
// 2. the same images under each other's names (what a backwards ft-camd gives)
m = sc.test("slam_left", inR, "slam_right", inL);
std::printf("side pair swapped: miss %.4f m as named, %.4f swapped\n", m.m[0], m.m[1]);
CHECK(m.m[1] >= 0 && m.m[1] < 0.001);
CHECK(SideCheck::vote(m) == 1);
// 3. a side camera with an upper one
m = sc.test("slam_left", inL, "upper_left", inUL);
CHECK(SideCheck::vote(m) == 0);
m = sc.test("slam_right", inL, "upper_left", inUL); // slam_left's image under slam_right's name
CHECK(SideCheck::vote(m) == 1);
m = sc.test("upper_right", inUR, "slam_left", inR); // ... and the other way round, other order
CHECK(SideCheck::vote(m) == 1);
// 4. the upper pair alone says nothing
CHECK(sc.add({seen("upper_left", inUL), seen("upper_right", inUR)}, 1) == 0);
// 5. two different hands, one in each side camera, don't vote
const V3 other{0.25, -0.3, -0.3};
m = sc.test("slam_left", inL, "slam_right", view(R, other, eyes));
std::printf("two hands: miss %.4f m as named, %.4f swapped\n", m.m[0], m.m[1]);
CHECK(SideCheck::vote(m) == -1);
// 6. a vote needs one way clearly better: both meeting about as well is no vote
CHECK(SideCheck::vote({{0.004, 0.006}}) == -1);
CHECK(SideCheck::vote({{0.004, 0.02}}) == 0);
CHECK(SideCheck::vote({{-1, 0.003}}) == 1);
CHECK(SideCheck::vote({{0.02, -1}}) == -1); // too far apart to be one hand
CHECK(SideCheck::vote({{-1, -1}}) == -1);
// 7. the decision: min_clean votes and none against, or min_votes and at most max_other
// against, over min_span_s
const std::vector<Seen> named = {seen("slam_left", inL), seen("slam_right", inR)};
const std::vector<Seen> swapped = {seen("slam_left", inR), seen("slam_right", inL)};
const int64_t s = 1'000'000'000;
sc.reset();
for (int i = 0; i < 9; ++i) CHECK(sc.add(named, i * s / 5) == 1);
CHECK(sc.verdict() == SideCheck::Undecided); // 9 votes
sc.add(named, 9 * s / 5);
CHECK(sc.verdict() == SideCheck::AsNamed); // 10 clean votes over 1.8 s
std::printf("%s\n", sc.summary().c_str());
// fast: 30 clean votes in 0.97 s aren't enough; the vote at 1.0 s is
sc.reset();
for (int i = 0; i < 30; ++i) sc.add(swapped, i * s / 30);
CHECK(sc.votes[1] == 30 && sc.verdict() == SideCheck::Undecided);
sc.add(swapped, s);
CHECK(sc.verdict() == SideCheck::Swapped);
CHECK(sc.median_miss_mm(1) >= 0 && sc.median_miss_mm(1) < 1);
// one vote against: it waits for min_votes
sc.reset();
sc.add(swapped, 0);
for (int i = 1; i < 20; ++i) sc.add(named, i * s / 10);
CHECK(sc.verdict() == SideCheck::Undecided); // 19 to 1
sc.add(named, 2 * s);
CHECK(sc.verdict() == SideCheck::AsNamed); // 20 to 1
// mixed evidence waits until the other way is at most a fifth of the votes
sc.reset();
for (int i = 0; i < 20; ++i) sc.add(named, i * s / 10);
for (int i = 0; i < 6; ++i) sc.add(swapped, (20 + i) * s / 10);
CHECK(sc.verdict() == SideCheck::Undecided); // 6 of 26
for (int i = 0; i < 4; ++i) sc.add(named, (26 + i) * s / 10);
CHECK(sc.verdict() == SideCheck::AsNamed); // 6 of 30
// the stricter check after a decision
sc.reset();
sc.min_clean = 20, sc.min_votes = 40;
for (int i = 0; i < 19; ++i) sc.add(named, i * s / 10);
CHECK(sc.verdict() == SideCheck::Undecided);
sc.add(named, 2 * s);
CHECK(sc.verdict() == SideCheck::AsNamed);
CHECK(sc.json().find("\"as_named\": 20") != std::string::npos);
// without both side cameras it can't check
std::map<std::string, Camera> one{{"slam_left", L}, {"upper_left", UL}};
SideCheck none(one);
CHECK(!none.usable());
CHECK(none.add(named, 0) == 0);
std::printf(failures ? "%d FAILED\n" : "sides_test: all passed\n", failures);
return failures ? 1 : 0;
}
+274
View File
@@ -0,0 +1,274 @@
#!/usr/bin/env python3
"""Tests for hands/camcheck.py: the real XRService log of 2026-10-02 (a good start at 13:39,
the VCINT failure after the 17:02 wake) cut at several points, synthetic logs for the other
cases, and a made-up ft-camd ring. Nothing here touches SteamVR or the cameras.
python3 hands/tests/test_camcheck.py
"""
import io
import json
import os
import shutil
import struct
import sys
import tempfile
import time
import unittest
from contextlib import redirect_stdout
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(HERE))
import camcheck # noqa: E402
REAL_LOG = os.path.expanduser("~/.local/share/Steam/logs/XRService-2026.10.02/XRService-13-39-32.log")
def L(t, text, level="INFO"):
"""A log line as XRService writes it (with its colour codes on INFO lines)."""
if level == "INFO":
return "Fri Oct 02 2026 %s.000000 INFO: \x1b[0;36m%s\x1b[0m" % (t, text)
return "Fri Oct 02 2026 %s.000000 %s: %s" % (t, level, text)
START = [L("10:00:00", "XRService logging to /tmp/x.log. Use --showLogToConsole to see it here as well")]
GOOD_OPEN = [
L("10:00:01", "FPGA state check: PASSTHRU (register value: 0x00011212)"),
L("10:00:01", "Passthrough connected but FPGA is PASSTHRU - loading VCINT"),
L("10:00:01", "Loading FPGA image: VCINT"),
L("10:00:02", "FPGA image VCINT loaded and verified successfully"),
L("10:00:02", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)"),
L("10:00:02", "[buildMediaCtlSetupTasks] Created 6 tasks (4 tracking, 2 passthrough)"),
] + [L("10:00:03", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: /dev/v4l-subdev3%d"
% (i, n, i)) for i, n in enumerate((9, 13, 6, 7))]
CLOSE = [L("11:00:00", "[SystemdInhibitor] Received systemd suspend notification"),
L("11:00:00", "[DeckardCaptureSource] Closing tracking camera interfaces camerasToUse: 1111"),
L("11:00:01", "[DeckardCaptureSource] Streaming paused")]
RESUME = [L("11:30:00", "[SystemdInhibitor] Received systemd resume notification"),
L("11:30:00", "Failed to read FPGA register 0x12 (exit code 256)", "ERROR"),
L("11:30:00", "Passthrough connected but FPGA is ERROR/UNKNOWN - loading VCINT"),
L("11:30:00", "Loading FPGA image: VCINT")]
FAIL = [L("11:30:01", "FPGA load failed (exit code 256): Loading VC Interleaving FPGA image", "ERROR"),
"Loading FPGA image from bitstream file /usr/lib/deckard-fpga/images/csi_agg_deckard_ev1_1_vcint.binx",
" FAILED: FPGA config_done signal did not assert",
L("11:30:01", "Failed to load VCINT FPGA image when passthrough cameras are connected", "ERROR"),
L("11:30:01", "Upper cameras FPGA interleaving support: 0 (Driver features available = 1 | VCINT loaded = 0)"),
L("11:30:01", "[buildMediaCtlSetupTasks] Created 4 tasks (2 tracking, 2 passthrough)"),
L("11:30:01", "TrackingCameraInit: index: 0. video device: /dev/video9. v4l subdevice: /dev/v4l-subdev31"),
L("11:30:01", "TrackingCameraInit: index: 1. video device: /dev/video13. v4l subdevice: /dev/v4l-subdev30"),
L("11:30:02", "[DeckardCaptureSource] Streaming resumed (FPGA: PASSTHRU, VC interleaving: disabled)")]
# A wake that works prints no "Created N tasks" (2026-10-01 16:39), so an older one must not count.
RESUME_OK = [L("12:30:00", "[SystemdInhibitor] Received systemd resume notification"),
L("12:30:00", "Passthrough connected but FPGA is ERROR/UNKNOWN - loading VCINT"),
L("12:30:01", "FPGA image VCINT loaded and verified successfully"),
L("12:30:01", "FPGA state check: VCINT (register value: 0x00021211)"),
L("12:30:01", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)")] + \
[L("12:30:01", "TrackingCameraInit: index: %d. video device: /dev/video%d. v4l subdevice: x" % (i, n))
for i, n in enumerate((9, 13, 6, 7))] + \
[L("12:30:02", "[DeckardCaptureSource] Streaming resumed (FPGA: VCINT, VC interleaving: enabled)")]
EXIT = [L("13:00:00", "XRService - main thread exiting"), L("13:00:00", "Exiting XRService")]
def state(lines):
return camcheck.LogState("test").feed_text("\n".join(lines))
class SyntheticLogs(unittest.TestCase):
def test_good_start(self):
st = state(START + GOOD_OPEN)
self.assertEqual(st.verdict()[:2], ("ok", "4 tracking cameras running"))
self.assertEqual(st.episode["vcint"], "ok")
self.assertEqual(st.upper_nodes(), (6, 7))
def test_good_start_tasks_only(self):
# "Created 6 tasks (4 tracking ...)" and no camera init yet: 4 tracking cameras planned
self.assertEqual(state(START + GOOD_OPEN[:6]).verdict()[0], "ok")
def test_starting(self):
self.assertEqual(state(START + GOOD_OPEN[:3]).verdict()[:2], ("unknown", "the cameras are starting"))
def test_vcint_already_loaded(self):
# A SteamVR restart in the same boot (2026-10-01 15:27): the FPGA still has VCINT.
lines = START + [L("10:00:01", "FPGA state check: VCINT (register value: 0x00021211)"),
L("10:00:01", "Upper cameras FPGA interleaving support: 1 (Driver features available = 1 | VCINT loaded = 1)"),
L("10:00:01", "[buildMediaCtlSetupTasks] Created 6 tasks (4 tracking, 2 passthrough)")]
st = state(lines)
self.assertEqual(st.verdict()[0], "ok")
self.assertEqual(st.episode["vcint"], "loaded")
def test_asleep(self):
status, reason, ev = state(START + GOOD_OPEN + CLOSE).verdict()
self.assertEqual(status, "unknown")
self.assertIn("closed", reason)
self.assertTrue(any("Closing tracking camera interfaces" in e for e in ev))
def test_vcint_failure(self):
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL)
status, reason, ev = st.verdict()
self.assertEqual((status, reason), ("degraded", camcheck.VCINT_REASON))
self.assertTrue(any("Created 4 tasks (2 tracking, 2 passthrough)" in e for e in ev))
self.assertTrue(any("Closing tracking camera interfaces" in e for e in ev))
self.assertFalse(any("\x1b" in e for e in ev))
self.assertEqual(st.snapshot()["failure"], "test@11:30:01")
self.assertEqual(len(st.failures), 1)
def test_failure_seen_before_the_cameras_start(self):
# the failure line alone (camera init not logged yet): degraded already
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL[:4])
self.assertEqual(st.verdict()[0], "degraded")
def test_wake_after_failure_works(self):
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL + CLOSE + RESUME_OK)
self.assertEqual(st.verdict()[0], "ok")
self.assertEqual(st.snapshot()["failure"], "")
self.assertEqual(len(st.failures), 1) # still remembered for the log's history
def test_fewer_cameras_without_vcint(self):
lines = START + [L("10:00:01", "[buildMediaCtlSetupTasks] Created 4 tasks (2 tracking, 2 passthrough)")]
status, reason, _ = state(lines).verdict()
self.assertEqual(status, "degraded")
self.assertEqual(reason, "only 2 of 4 tracking cameras running")
def test_exited_and_empty(self):
self.assertEqual(state(START + GOOD_OPEN + EXIT).verdict()[0], "unknown")
self.assertEqual(state([]).verdict()[0], "unknown")
self.assertEqual(state(START).verdict()[:2], ("unknown", "the cameras haven't started yet in this log"))
def test_new_instance_resets(self):
st = state(START + GOOD_OPEN + CLOSE + RESUME + FAIL + START + GOOD_OPEN)
self.assertEqual(st.verdict()[0], "ok")
self.assertEqual(st.failures, [])
def test_incremental_equals_whole(self):
text = "\n".join(START + GOOD_OPEN + CLOSE + RESUME + FAIL)
st = camcheck.LogState("test")
for line in text.split("\n"):
st.feed(line + "\n")
self.assertEqual(st.snapshot(), state(START + GOOD_OPEN + CLOSE + RESUME + FAIL).snapshot())
@unittest.skipUnless(os.path.exists(REAL_LOG), "the 2026-10-02 XRService log isn't on this machine")
class RealLog(unittest.TestCase):
"""The log with both the good 13:39 start and the 17:02 failure, cut in copies in /tmp."""
@classmethod
def setUpClass(cls):
with open(REAL_LOG, errors="replace") as f:
cls.lines = f.read().split("\n")
cls.tmp = tempfile.mkdtemp(prefix="camcheck-test-")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def cut_after(self, needle, nth=1):
"""The log up to and including the nth line containing needle, as a file in /tmp."""
seen = 0
for i, line in enumerate(self.lines):
if needle in line:
seen += 1
if seen == nth:
path = os.path.join(self.tmp, "cut-%d.log" % i)
with open(path, "w") as f:
f.write("\n".join(self.lines[:i + 1]) + "\n")
return path
self.fail("no line %d with %r" % (nth, needle))
def check(self, path):
return camcheck.check(log=path, proc=False, ring=False)
def test_cut_points(self):
cases = [
("Loading FPGA image: VCINT", 1, "unknown", "the cameras are starting"),
("FPGA image VCINT loaded and verified successfully", 1, "unknown", "the cameras are starting"),
("Created 6 tasks (4 tracking, 2 passthrough)", 1, "ok", None),
("TrackingCameraInit: index: 3.", 1, "ok", None),
("Upper cameras are not in sync", 1, "ok", None), # 15:45: a resync, not a failure
("Closing tracking camera interfaces", 1, "unknown", None), # 16:41: asleep
("Passthrough connected but FPGA is ERROR/UNKNOWN", 1, "unknown", "the cameras are starting"),
("Failed to load VCINT FPGA image", 1, "degraded", camcheck.VCINT_REASON),
("Created 4 tasks (2 tracking, 2 passthrough)", 1, "degraded", camcheck.VCINT_REASON),
("Streaming resumed (FPGA: PASSTHRU", 1, "degraded", camcheck.VCINT_REASON),
]
for needle, nth, status, reason in cases:
with self.subTest(cut=needle):
r = self.check(self.cut_after(needle, nth))
self.assertEqual(r["status"], status, r["summary"])
if reason:
self.assertEqual(r["reason"], reason)
r = self.check(self.cut_after("Closing tracking camera interfaces"))
self.assertIn("closed", r["reason"])
def test_whole_log(self):
r = self.check(REAL_LOG)
self.assertEqual(r["summary"], camcheck.DEGRADED_VCINT)
ev = "\n".join(r["evidence"])
for want in ("17:02:47 Failed to load VCINT FPGA image", "interleaving support: 0",
"Created 4 tasks (2 tracking, 2 passthrough)", "/dev/video9", "/dev/video13",
"Closing tracking camera interfaces"):
self.assertIn(want, ev)
self.assertNotIn("/dev/video6", ev) # the 13:39 start isn't this episode's evidence
self.assertTrue(r["failure"].endswith("@17:02:47"))
self.assertTrue(camcheck.is_vcint_failure(r))
def test_cli(self):
out = io.StringIO()
with redirect_stdout(out):
code = camcheck.main(["--log", REAL_LOG, "--no-proc", "--no-ring", "--json"])
self.assertEqual(code, 1)
self.assertEqual(json.loads(out.getvalue())["status"], "degraded")
out = io.StringIO()
with redirect_stdout(out):
code = camcheck.main(["--log", self.cut_after("TrackingCameraInit: index: 3."), "--no-proc", "--no-ring"])
self.assertEqual(code, 0)
self.assertEqual(out.getvalue().split("\n")[0], "ok")
def make_ring(path, mono_names, alive=True):
"""A ring header as ft-camd writes it (camd/fhring.h), no frames."""
cams = [(b"og01a1b", n.encode(), 9 + i) for i, n in enumerate(mono_names)]
hb = time.clock_gettime_ns(time.CLOCK_MONOTONIC) if alive else 1
data = bytearray(camcheck.RING_HDR.pack(b"FHRING01", 1, 0, len(cams), 0, 0, 4242, 0))
struct.pack_into("<Q", data, 40, hb)
for sensor, name, node in cams:
data += camcheck.RING_CAM.pack(sensor, name, node, 0, 1056, 1024, 1056, 16, 0, 0, 0, 0, 0, 0, 0.0)
with open(path, "wb") as f:
f.write(bytes(data))
class Ring(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="camcheck-ring-")
self.ring = os.path.join(self.tmp, "cam-ring")
self.log = os.path.join(self.tmp, "x.log")
with open(self.log, "w") as f:
f.write("\n".join(START + GOOD_OPEN) + "\n")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_two_cameras_in_ring(self):
make_ring(self.ring, ["slam_video9", "slam_video13"])
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
self.assertEqual(r["status"], "degraded")
self.assertIn("ft-camd publishes only 2 of 4", r["reason"])
def test_four_cameras_in_ring(self):
make_ring(self.ring, ["a_video9", "b_video13", "c_video6", "d_video7", "a_video9_dk"])
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
self.assertEqual(r["status"], "ok")
self.assertEqual(len(r["ring"]["mono"]), 4) # the dark twin doesn't count
def test_stale_ring_ignored(self):
make_ring(self.ring, ["slam_video9"], alive=False)
r = camcheck.check(log=self.log, proc=False, ring_path=self.ring)
self.assertEqual(r["status"], "ok")
self.assertIn("stale ring", "\n".join(r["evidence"]))
def test_no_ring(self):
r = camcheck.check(log=self.log, proc=False, ring_path=os.path.join(self.tmp, "none"))
self.assertEqual(r["status"], "ok")
self.assertIsNone(r["ring"])
if __name__ == "__main__":
unittest.main()
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Tests for hands/ft-camwatch: its decision logic with made-up inputs (worn or not, VR apps,
remote viewers, cooldown, once per failure), following a growing log, and its settings. It
never notifies or restarts anything here.
python3 hands/tests/test_camwatch.py
"""
import importlib.machinery
import importlib.util
import os
import shutil
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
HANDS = os.path.dirname(HERE)
sys.path.insert(0, HANDS)
sys.path.insert(0, HERE)
from test_camcheck import CLOSE, FAIL, GOOD_OPEN, RESUME, RESUME_OK, START # noqa: E402
loader = importlib.machinery.SourceFileLoader("camwatch", os.path.join(HANDS, "ft-camwatch"))
spec = importlib.util.spec_from_loader("camwatch", loader)
cw = importlib.util.module_from_spec(spec)
loader.exec_module(cw)
ON = dict(cw.DEFAULTS, CAMWATCH_AUTO_RESTART="1", CAMWATCH_IDLE_S="60", CAMWATCH_COOLDOWN_MIN="30")
OFF = dict(cw.DEFAULTS)
IDLE = {"steamvr": True, "worn": False, "vr_apps": [], "remote": []}
WORN = dict(IDLE, worn=True)
F1, F2 = "a.log@17:02:47", "b.log@18:10:00"
def kinds(acts):
return [k for k, _ in acts]
class Decide(unittest.TestCase):
def setUp(self):
self.mem = cw.new_memory()
def d(self, now, failure, env=IDLE, conf=ON):
return cw.decide(now, failure, env, self.mem, conf)
def test_nothing_wrong(self):
self.assertEqual(self.d(0, "", {}), [])
self.assertEqual(self.mem["pending"], "")
def test_notify_once(self):
acts = self.d(0, F1, WORN, OFF)
self.assertEqual(kinds(acts), ["log", "notify", "log"])
self.assertIn("CAMWATCH_AUTO_RESTART=1", acts[2][1])
self.assertEqual(self.d(2, F1, WORN, OFF), []) # same failure, same reason: quiet
self.assertEqual(self.d(4, F1, IDLE, OFF), []) # off: never restarts, whatever the state
self.assertEqual(self.d(1000, F1, IDLE, OFF), [])
def test_notify_off(self):
acts = self.d(0, F1, WORN, dict(OFF, CAMWATCH_NOTIFY="0"))
self.assertNotIn("notify", kinds(acts))
def test_never_while_worn(self):
self.d(0, F1, WORN)
for t in range(2, 4000, 2):
self.assertNotIn("restart", kinds(self.d(t, F1, WORN)))
self.assertIn("worn", self.mem["why"])
def test_restart_after_idle_then_once(self):
self.d(0, F1, WORN)
self.assertNotIn("restart", kinds(self.d(10, F1, IDLE))) # just taken off: wait
self.assertIn("waiting", self.mem["why"])
self.assertNotIn("restart", kinds(self.d(69, F1, IDLE)))
acts = self.d(70, F1, IDLE)
self.assertEqual(kinds(acts), ["log", "restart"])
self.assertEqual(acts[1][1], F1)
# the same failure again (the new XRService hasn't logged yet, or failed the same way)
acts = self.d(72, F1, IDLE)
self.assertNotIn("restart", kinds(acts))
self.assertIn("restart the headset", self.mem["why"])
for t in range(74, 10000, 500):
self.assertNotIn("restart", kinds(self.d(t, F1, IDLE)))
def test_put_on_resets_the_wait(self):
self.d(0, F1, IDLE)
self.d(50, F1, WORN) # back on at 50 s
self.assertNotIn("restart", kinds(self.d(70, F1, IDLE))) # off again: the 60 s start over
self.assertNotIn("restart", kinds(self.d(129, F1, IDLE)))
self.assertIn("restart", kinds(self.d(131, F1, IDLE)))
def test_cooldown(self):
self.d(0, F1, IDLE)
self.assertIn("restart", kinds(self.d(60, F1, IDLE)))
# The restart's new XRService fails too: a new failure, but within the cooldown.
self.d(90, "", IDLE)
acts = self.d(120, F2, IDLE)
self.assertIn("notify", kinds(acts))
self.assertNotIn("restart", kinds(acts))
self.assertNotIn("restart", kinds(self.d(60 + 30 * 60 - 2, F2, IDLE)))
self.assertIn("cooldown", self.mem["why"])
self.assertIn("restart", kinds(self.d(60 + 30 * 60, F2, IDLE)))
def test_vr_app_remote_and_no_steamvr(self):
for env, word in ((dict(IDLE, vr_apps=["AppId=450390"]), "VR app"),
(dict(IDLE, remote=["0A00000B:D2F0"]), "remote desktop"),
(dict(IDLE, steamvr=False), "SteamVR isn't running")):
with self.subTest(word=word):
self.mem = cw.new_memory()
for t in range(0, 600, 2):
self.assertNotIn("restart", kinds(self.d(t, F1, env)))
self.assertIn(word, self.mem["why"])
# once it's gone (and the headset still off), the restart happens
self.assertIn("restart", kinds(self.d(600, F1, IDLE)))
def test_resolved(self):
self.d(0, F1, WORN)
acts = self.d(10, "", {})
self.assertEqual(kinds(acts), ["log"])
self.assertIn("no longer current", acts[0][1])
self.assertEqual(self.mem["pending"], "")
self.assertEqual(self.d(12, "", {}), [])
def test_memory_round_trip(self):
tmp = tempfile.mkdtemp(prefix="camwatch-test-")
try:
path = os.path.join(tmp, "state", "camwatch.json")
self.d(0, F1, IDLE)
self.d(60, F1, IDLE)
cw.save_memory(self.mem, path)
mem = cw.load_memory(path)
self.assertEqual(mem["restarted"], {F1: 60})
self.assertEqual(mem["notified"], [F1])
# the watcher restarted: the same failure neither notifies nor restarts again
acts = cw.decide(200, F1, IDLE, mem, ON)
self.assertNotIn("notify", kinds(acts))
self.assertNotIn("restart", kinds(acts))
self.assertEqual(cw.load_memory(os.path.join(tmp, "missing.json"))["restarted"], {})
finally:
shutil.rmtree(tmp, ignore_errors=True)
class Follow(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="camwatch-follow-")
def tearDown(self):
shutil.rmtree(self.tmp, ignore_errors=True)
def test_growing_log(self):
path = os.path.join(self.tmp, "x.log")
f = cw.Follower(path)
text = "\n".join(START + GOOD_OPEN) + "\n"
with open(path, "w") as out:
out.write(text)
self.assertEqual(cw.current_failure(f.poll()), "")
self.assertEqual(f.state.verdict()[0], "ok")
# half a line, then the rest: read as one line
more = "\n".join(CLOSE + RESUME + FAIL) + "\n"
cut = more.index("Failed to load VCINT") + 5
with open(path, "a") as out:
out.write(more[:cut])
self.assertEqual(cw.current_failure(f.poll()), "")
with open(path, "a") as out:
out.write(more[cut:])
self.assertTrue(cw.current_failure(f.poll()).endswith("@11:30:01"))
self.assertEqual(cw.current_failure(f.state, steamvr_running=False), "")
with open(path, "a") as out:
out.write("\n".join(CLOSE + RESUME_OK) + "\n")
self.assertEqual(cw.current_failure(f.poll()), "")
def test_new_log_starts_afresh(self):
a, b = os.path.join(self.tmp, "a.log"), os.path.join(self.tmp, "b.log")
with open(a, "w") as out:
out.write("\n".join(START + GOOD_OPEN + CLOSE + RESUME + FAIL) + "\n")
f = cw.Follower(a)
self.assertTrue(cw.current_failure(f.poll()))
with open(b, "w") as out:
out.write("\n".join(START + GOOD_OPEN) + "\n")
f.fixed = b # as when xrservice.txt points at a new XRService's log
self.assertEqual(cw.current_failure(f.poll()), "")
self.assertEqual(f.path, b)
class Settings(unittest.TestCase):
def test_read_conf(self):
tmp = tempfile.mkdtemp(prefix="camwatch-conf-")
try:
path = os.path.join(tmp, "frametop.conf")
with open(path, "w") as f:
f.write("# Frametop\nREMOTE=1 # comment\nCAMWATCH_AUTO_RESTART=1\nCAMWATCH_IDLE_S='90'\n"
"CAMWATCH_IGNORE_APPIDS=\"1, 2\"\nnot a setting\n")
conf = cw.read_conf(path)
self.assertEqual(conf["CAMWATCH_AUTO_RESTART"], "1")
self.assertEqual(cw.conf_int(conf, "CAMWATCH_IDLE_S"), 90)
self.assertEqual(conf["CAMWATCH_IGNORE_APPIDS"], "1, 2")
self.assertEqual(cw.conf_int(conf, "CAMWATCH_COOLDOWN_MIN"), 30) # the default
self.assertEqual(cw.read_conf(os.path.join(tmp, "none"))["CAMWATCH_AUTO_RESTART"], "0")
self.assertEqual(cw.conf_int({"CAMWATCH_IDLE_S": "soon"}, "CAMWATCH_IDLE_S"), 60)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def test_headset_worn(self):
tmp = tempfile.mkdtemp(prefix="camwatch-bl-")
orig = cw.process_running
try:
os.makedirs(os.path.join(tmp, "panel0"))
bright = os.path.join(tmp, "panel0", "brightness")
for value, compositor, worn in (("95", True, True), ("0", True, False), ("95", False, False)):
with open(bright, "w") as f:
f.write(value + "\n")
cw.process_running = lambda name, c=compositor: c and name == "vrcompositor"
self.assertEqual(cw.headset_worn(tmp), worn, (value, compositor))
self.assertFalse(cw.headset_worn(os.path.join(tmp, "none")))
finally:
cw.process_running = orig
shutil.rmtree(tmp, ignore_errors=True)
def test_remote_viewers(self):
tmp = tempfile.mkdtemp(prefix="camwatch-tcp-")
try:
path = os.path.join(tmp, "tcp")
with open(path, "w") as f:
f.write(" sl local_address rem_address st tx_queue rx_queue\n"
" 0: 0100007F:170C 00000000:0000 0A 00000000:00000000\n" # listening
" 1: 0B00640A:170C 0C00640A:D2F0 01 00000000:00000000\n" # a viewer
" 2: 0B00640A:0016 0C00640A:D2F1 01 00000000:00000000\n") # ssh
self.assertEqual(cw.remote_viewers(5900, (path,)), ["0C00640A:D2F0"])
self.assertEqual(cw.remote_viewers(5901, (path,)), [])
finally:
shutil.rmtree(tmp, ignore_errors=True)
if __name__ == "__main__":
unittest.main()
+71 -33
View File
@@ -1,11 +1,18 @@
"""Check that the side cameras' images carry the right names (slam_left vs slam_right).
usage: python tools/check_sides.py REC_DIR [--sets N]
python tools/check_sides.py --ring [--sets N] (live, from ft-camd's ring)
usage: python tools/check_sides.py REC [--sets N] [--pair side|upper] [--calib DIR] [--json]
python tools/check_sides.py --ring [--sets N] [--pair side|upper] (live, from ft-camd's ring)
With --ring it exits 0 when the names are right, 3 when they're swapped (run ft-hands
with --swap-sides), and 2 when it can't tell (too little texture in view, or the headset
isn't worn).
REC is a recording folder (its sets.bin) or a sets file (a take's sets-N.bin). It checks the
names as they are in the files: a recording's sides.json or session.json "sides" (the hand
recorder's) isn't applied. Exits 0 when the names are right, 3 when they're swapped, and 2 when
it can't tell (too little texture in view, or the headset isn't worn). --pair upper checks the
upper pair (upper_left vs upper_right) the same way. --calib DIR uses DIR/calibration.json and
DIR/device.json (a hand recorder session's, or cut.py's) instead of /persist. --json prints one
line: {"pair", "verdict": "named"|"swapped"|"unknown", "named", "swapped", "matches", "sets"}.
ft-hands decides the side cameras' naming by itself (HANDS_SWAP_SIDES=auto, track/sides.h);
this is the independent check, from the scene rather than hands.
ft-camd tells the two side cameras' buffers apart by the order XRService allocated them,
and after some XRService restarts that order puts each camera's images under the other's
@@ -15,6 +22,7 @@ with the factory calibration, once as named and once swapped: true matches meet
front of both cameras only under the right naming.
"""
import argparse
import json
import os
import sys
@@ -26,10 +34,14 @@ from tools.show_set import index, read_set # noqa: E402
from tools import calib # noqa: E402
PIPES = {'msm_vfe3_video0': 'slam_left', 'msm_vfe4_video0': 'slam_right'} # as ft-hands maps them
PIPES = {'msm_vfe3_video0': 'slam_left', 'msm_vfe4_video0': 'slam_right', # as ft-hands maps them
'msm_vfe2_video0': 'upper_left', 'msm_vfe2_video1': 'upper_right'}
PAIRS = {'side': ('slam_left', 'slam_right'), 'upper': ('upper_left', 'upper_right')}
def load_cams():
def load_cams(calib_dir=None):
if calib_dir:
return calib.load(os.path.join(calib_dir, 'calibration.json'), os.path.join(calib_dir, 'device.json'))
return calib.load()
@@ -68,18 +80,20 @@ def score(cam_a, cam_b, ua, ub):
return float(np.mean((d < 0.01) & front))
def recorded_pairs(rec, count):
"""(label, slam_left image, slam_right image) from sets spread across a recording."""
path = os.path.join(rec, 'sets.bin')
def recorded_pairs(rec, count, names=PAIRS['side']):
"""(label, left image, right image) from sets spread across a recording (or sets file)."""
path = rec if os.path.isfile(rec) else os.path.join(rec, 'sets.bin')
offs = index(path)
for n in np.linspace(0, len(offs) - 1, count).astype(int):
if not offs:
return
for n in sorted(set(np.linspace(0, len(offs) - 1, count).astype(int))):
images = read_set(path, offs[n])
if 'slam_left' in images and 'slam_right' in images:
yield 'set %5d' % n, images['slam_left'][0], images['slam_right'][0]
if names[0] in images and names[1] in images:
yield 'set %5d' % n, images[names[0]][0], images[names[1]][0]
def live_pairs(count):
"""(label, slam_left image, slam_right image) from ft-camd's ring, half a second apart."""
def live_pairs(count, names=PAIRS['side']):
"""(label, left image, right image) from ft-camd's ring, half a second apart."""
import time
from tools.ring import Ring
ring = Ring()
@@ -91,37 +105,61 @@ def live_pairs(count):
if name and not c.name.endswith('-dark'):
cams[name] = c
for k in range(count):
a, b = ring.read(cams['slam_left']), ring.read(cams['slam_right'])
a, b = ring.read(cams[names[0]]), ring.read(cams[names[1]])
if a is not None and b is not None:
yield 'frame %2d' % k, a.image, b.image
time.sleep(0.5)
def verdict(named, swapped, n, total_matches):
"""'named', 'swapped' or 'unknown', from the summed per-set scores: the winner must meet
clearly more often (by 0.08 a set) and at least 4 times as often. The upper cameras' small
images meet within 1 cm less often (0.1-0.4 a set as named, 0 swapped) than the side ones (0.4-0.9)."""
hi, lo = max(named, swapped), min(named, swapped)
if n == 0 or total_matches < 100 or (hi - lo) / n < 0.08 or lo > 0.25 * hi:
return 'unknown'
return 'named' if named > swapped else 'swapped'
def check(pairs, left, right, out=print):
"""Score (label, left image, right image) pairs: (verdict, named, swapped, matches, sets)."""
named = swapped = 0.0
n = total_matches = 0
for label, img_l, img_r in pairs:
ua, ub = matches(img_l, img_r)
s_named = score(left, right, ua, ub) # the left-named image seen by the left camera
s_swapped = score(right, left, ua, ub) # ... by the right camera
named, swapped, n, total_matches = named + s_named, swapped + s_swapped, n + 1, total_matches + len(ua)
out('%s: %4d matches, meeting as named %3.0f%%, swapped %3.0f%%' %
(label, len(ua), 100 * s_named, 100 * s_swapped))
return verdict(named, swapped, n, total_matches), named / max(n, 1), swapped / max(n, 1), total_matches, n
def main():
ap = argparse.ArgumentParser()
ap.add_argument('rec', nargs='?')
ap.add_argument('--ring', action='store_true', help='check the live cameras instead of a recording')
ap.add_argument('--sets', type=int, default=8, help='how many sets or live frames to check')
ap.add_argument('--pair', choices=sorted(PAIRS), default='side')
ap.add_argument('--calib', help='folder with calibration.json and device.json (default: /persist)')
ap.add_argument('--json', action='store_true', help='one JSON line instead of the report')
a = ap.parse_args()
if not a.ring and not a.rec:
ap.error('give a recording or --ring')
cams = load_cams()
left, right = cams['slam_left'], cams['slam_right']
named = swapped = 0.0
n = total_matches = 0
for label, img_l, img_r in (live_pairs(a.sets) if a.ring else recorded_pairs(a.rec, a.sets)):
ua, ub = matches(img_l, img_r)
s_named = score(left, right, ua, ub) # slam_left's image seen by the left camera
s_swapped = score(right, left, ua, ub) # ... by the right camera
named, swapped, n, total_matches = named + s_named, swapped + s_swapped, n + 1, total_matches + len(ua)
print('%s: %4d matches, meeting as named %3.0f%%, swapped %3.0f%%' %
(label, len(ua), 100 * s_named, 100 * s_swapped))
if n == 0 or total_matches < 100 or abs(named - swapped) / n < 0.2:
print('side cameras: can\'t tell (%d matches)' % total_matches)
sys.exit(2)
print('side cameras: %s (named %.2f, swapped %.2f)' %
('as named' if named > swapped else 'SWAPPED', named / n, swapped / n))
sys.exit(0 if named > swapped else 3)
cams = load_cams(a.calib)
names = PAIRS[a.pair]
left, right = cams[names[0]], cams[names[1]]
pairs = live_pairs(a.sets, names) if a.ring else recorded_pairs(a.rec, a.sets, names)
v, named, swapped, total, n = check(pairs, left, right, out=(lambda s: None) if a.json else print)
what = 'side cameras' if a.pair == 'side' else 'upper cameras'
if a.json:
print(json.dumps({'pair': a.pair, 'verdict': v, 'named': round(named, 3), 'swapped': round(swapped, 3),
'matches': total, 'sets': n}))
elif v == 'unknown':
print('%s: can\'t tell (%d matches)' % (what, total))
else:
print('%s: %s (named %.2f, swapped %.2f)' % (what, 'as named' if v == 'named' else 'SWAPPED', named, swapped))
sys.exit({'named': 0, 'swapped': 3, 'unknown': 2}[v])
if __name__ == '__main__':
+179 -23
View File
@@ -3,7 +3,7 @@
// Python prototype: the same scheduling, with the models on a few threads.
//
// ft-hands [--seconds N] [--threads N] [--int8] [--status S] [--models DIR] [--nice N]
// [--no-publish] [--no-gestures] [--record DIR] [--swap-sides] [--cams auto|mono|color|all] ...
// [--no-publish] [--no-gestures] [--record DIR] [--sides auto|0|1] [--cams auto|mono|color|all] ...
// (--help lists them all)
//
// --no-gestures: hands for the cutouts only. No pinch or grip detection, so nothing reaches
@@ -22,14 +22,24 @@
// own clock, so they're placed on the mono cameras' by when they were dequeued, less the
// mono cameras' measured delay.
//
// Which side camera is which (--sides, HANDS_SWAP_SIDES): ft-camd tells slam_left's buffers from
// slam_right's by XRService's allocation order, which some XRService starts reverse. auto (the
// default) tells from the hands it tracks (track/sides.h): once it's sure, it exchanges the two
// cameras if they're backwards (the tracked views move with their images), and checks once
// more. 0 and 1 force the naming (1: exchanged; --swap-sides is --sides 1); it still checks,
// and warns if the hands disagree. The decision is published in /run/user/UID/frametop-hands/sides.json (see
// write_sides below) and, for recordings, in DIR/sides.json. --record-only can't tell (it tracks
// nothing): under auto it records the ring's names as they are.
//
// Settings in ~/.config/frametop.conf (FT_<name> in the environment overrides them, and
// options override both): HANDS_SWAP_SIDES (1: as --swap-sides), HANDS_CPUS (as --cpus),
// options override both): HANDS_SWAP_SIDES (auto, 0 or 1), HANDS_CPUS (as --cpus),
// HANDS_CAMERAS, HANDS_BRIGHT, HANDS_BRIGHT_ON, HANDS_BRIGHT_OFF, HANDS_COLOR_LEFT (which
// colour camera is passthrough_left: color_video0 or color_video3), HANDS_COLOR_CROP
// (subtract or none: tools/check_color.py tells both).
#include "io.h"
#include "pinch.h"
#include "record.h"
#include "sides.h"
#include <sched.h>
#include <sys/resource.h>
@@ -45,6 +55,7 @@
#include <cstdio>
#include <cstring>
#include <fstream>
#include <optional>
#include <thread>
#include <utility>
@@ -148,12 +159,25 @@ struct Lighting {
}
};
// Writes path through a temporary file, so a reader never sees half of it.
bool write_file(const std::string &path, const std::string &text) {
const std::string tmp = path + ".tmp";
FILE *f = std::fopen(tmp.c_str(), "w");
if (!f) return false;
const bool ok = std::fputs(text.c_str(), f) >= 0;
if (std::fclose(f) != 0 || !ok || std::rename(tmp.c_str(), path.c_str()) != 0) return unlink(tmp.c_str()), false;
return true;
}
std::string json_bool(std::optional<bool> b) { return !b ? "null" : *b ? "true" : "false"; }
std::string json_str(const std::string &s) { return s.empty() ? "null" : "\"" + s + "\""; }
} // namespace
int main(int argc, char **argv) {
double seconds = 0, status = 5;
int threads = 3, niceness = 5;
bool int8 = false, publish = true, track = true, swap_sides = false, gestures_on = true;
bool int8 = false, publish = true, track = true, gestures_on = true;
std::string models = std::string(argv[0]).substr(0, std::string(argv[0]).rfind('/') + 1) + "../models/ncnn";
std::string record, ring_path = "/run/user/" + std::to_string(getuid()) + "/" FH_RING_NAME;
// SteamOS starts user processes on CPUs 0-4 and keeps 5-7 (two A720s and the X4) for
@@ -163,7 +187,9 @@ int main(int argc, char **argv) {
// latency 9.6 against 14.1 ms, and the compositor's late frames and CPU/GPU time didn't change.
std::vector<int> cpus = {5, 6, 7};
if (const auto c = parse_cpus(setting("HANDS_CPUS").c_str()); !c.empty()) cpus = c;
swap_sides = setting("HANDS_SWAP_SIDES") == "1";
// Which side camera is which (see the top): auto, 0 or 1, and where that came from
std::string sides_mode = setting("HANDS_SWAP_SIDES"), sides_from = "config";
if (sides_mode.empty()) sides_mode = "auto", sides_from = "default";
// Which cameras (see the top).
std::string cams_arg = setting("HANDS_CAMERAS"), bright_arg = setting("HANDS_BRIGHT");
std::string color_left = setting("HANDS_COLOR_LEFT"), color_crop = setting("HANDS_COLOR_CROP");
@@ -181,7 +207,7 @@ int main(int argc, char **argv) {
PinchParams pinch_params;
GripParams grip_params;
bool gesture_log = false; // what the pinch and grip detectors measure, 10 times a second
double record_for = 120;
double record_for = 120, record_hz = 0; // record_hz: at most this many sets a second (0: all)
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
const bool more = i + 1 < argc;
@@ -200,11 +226,13 @@ int main(int argc, char **argv) {
else if (a == "--grip-begin" && more) grip_params.begin = std::atof(argv[++i]);
else if (a == "--grip-end" && more) grip_params.end = std::atof(argv[++i]);
else if (a == "--gesture-log") gesture_log = true;
else if (a == "--swap-sides") swap_sides = true;
else if (a == "--swap-sides") sides_mode = "1", sides_from = "option";
else if (a == "--sides" && more) sides_mode = argv[++i], sides_from = "option";
else if (a == "--record-only") track = publish = false;
else if (a == "--ring" && more) ring_path = argv[++i];
else if (a == "--record" && more) record = argv[++i];
else if (a == "--record-for" && more) record_for = std::atof(argv[++i]);
else if (a == "--record-hz" && more) record_hz = std::max(0.0, std::atof(argv[++i]));
else if (a == "--keep-presence" && more) keep_presence = std::atof(argv[++i]);
else if (a == "--cams" && more) cams_arg = argv[++i];
else if (a == "--bright" && more) bright_arg = argv[++i];
@@ -222,19 +250,22 @@ int main(int argc, char **argv) {
else {
std::printf("usage: %s [--seconds N] [--threads N] [--int8] [--status S] [--models DIR] [--nice N] [--no-publish]\n"
" [--no-gestures] (hands for the cutouts only: no pinches or grips)\n"
" [--record DIR] [--record-for S] [--record-only] [--cpus 5,6,7] [--swap-sides]\n"
" [--record DIR] [--record-for S] [--record-hz N] [--record-only] [--cpus 5,6,7]\n"
" [--sides auto|0|1] (auto: tell from the hands which side camera is which; 1: exchange them,\n"
" as --swap-sides; 0: as ft-camd names them)\n"
" [--keep-presence P] (0.5) [--ring PATH] (ft-camd's, or ft-ringplay's)\n"
" [--cams auto|mono|color|all] (auto) [--bright all|color] (all) [--bright-on L] (40) [--bright-off L] (25)\n"
" [--color-left color_video0|color_video3] [--color-crop subtract|none]\n"
" [--pinch-begin M] (0.020) [--pinch-end M] (0.035) [--pinch-triangulated] [--pinch-palm-down MAX] (1: off)\n"
" [--grip-begin R] (1.2) [--grip-end R] (1.45) [--gesture-log]\n"
" [--contrast MODE|PALM/HAND] (clahe[:CLIP], none, stretch; default clahe:2/none)\n"
"Recording saves every frame set for S seconds (120) to DIR/sets.bin, for ft-handreplay; SIGUSR1\n"
"Recording saves every frame set (at most N a second with --record-hz) for S seconds (120) to DIR/sets.bin,\n"
"for ft-handreplay; SIGUSR1\n"
"starts one in ~/.local/share/frametop/hands/rec-<time>. --record-only records without tracking, so it\n"
"can run beside a tracking ft-hands. With ft-camd --with-dark, recordings also get each\n"
"camera's newest dark frame, as <name>_dk; with --with-color, the color cameras' as color_video<N>.\n"
"auto picks the cameras by the light (see the top of track/main.cpp).\n"
"Settings in ~/.config/frametop.conf: HANDS_SWAP_SIDES=1, HANDS_CPUS=5,6,7, HANDS_CAMERAS, HANDS_BRIGHT,\n"
"Settings in ~/.config/frametop.conf: HANDS_SWAP_SIDES=auto|0|1, HANDS_CPUS=5,6,7, HANDS_CAMERAS, HANDS_BRIGHT,\n"
"HANDS_BRIGHT_ON, HANDS_BRIGHT_OFF, HANDS_COLOR_LEFT, HANDS_COLOR_CROP (FT_<name> overrides).\n",
argv[0]);
return a == "--help" ? 0 : 1;
@@ -245,6 +276,8 @@ int main(int argc, char **argv) {
if ((!automatic && !parse_cams(cams_arg, fixed)) || !parse_cams(bright_arg, bright_cams) || bright_cams == Cams::Mono)
return std::fprintf(stderr, "--cams auto|mono|color|all, --bright all|color\n"), 1;
if (color_crop != "subtract" && color_crop != "none") return std::fprintf(stderr, "--color-crop subtract|none\n"), 1;
if (sides_mode != "auto" && sides_mode != "0" && sides_mode != "1")
return std::fprintf(stderr, "--sides (HANDS_SWAP_SIDES) auto, 0 or 1, not %s\n", sides_mode.c_str()), 1;
std::setvbuf(stdout, nullptr, _IOLBF, 0); // whole lines to the journal as they come
if (nice(niceness) < 0) std::perror("nice"); // the VR stack wins contested CPUs
std::signal(SIGINT, [](int) { g_stop = 1; });
@@ -260,10 +293,32 @@ int main(int argc, char **argv) {
Pinch pinch(pinch_params);
Grip grip(grip_params);
std::unique_ptr<Recorder> rec;
uint64_t rec_start = 0;
uint64_t rec_start = 0, rec_next_ns = 0; // rec_next_ns: --record-hz's next set, capture clock
// The side cameras (see the top). names_swapped: slam_left's and slam_right's ring cameras
// are exchanged from ft-camd's naming. truth: whether ft-camd's naming is backwards, once known.
bool names_swapped = sides_mode == "1";
std::optional<bool> truth;
std::string decided_by, sides_state = "deciding", decision_evidence;
double decided_after_s = -1;
if (sides_mode != "auto") truth = names_swapped, decided_by = sides_from, sides_state = "forced";
std::string rec_dir;
std::vector<std::pair<size_t, bool>> rec_names; // from which recorded set on, names_swapped was what
// DIR/sides.json beside a recording's sets.bin: how its side cameras are named. A set's
// names are right when its names_swapped equals swapped (null: not known when recorded).
auto write_rec_sides = [&] {
if (!rec) return;
std::string runs;
for (auto &[from, sw] : rec_names) runs += (runs.empty() ? "" : ", ") + ("[" + std::to_string(from) + ", " + json_bool(sw) + "]");
write_file(rec_dir + "/sides.json",
"{\"swapped\": " + json_bool(truth) + ", \"decided_by\": " + json_str(truth ? decided_by : "") +
", \"names_swapped\": [" + runs + "]" +
(decision_evidence.empty() ? "" : ", \"evidence\": " + decision_evidence) + "}\n");
};
auto start_recording = [&](const std::string &dir, std::string &e) {
rec = std::make_unique<Recorder>();
if (!rec->open(dir, e)) return rec.reset(), false;
rec_dir = dir, rec_names = {{0, names_swapped}};
write_rec_sides();
rec_start = mono_ns();
std::printf("recording to %s for %.0f s\n", dir.c_str(), record_for);
std::fflush(stdout);
@@ -299,12 +354,26 @@ int main(int argc, char **argv) {
else index[name] = i, used[name] = calib[name];
}
// ft-camd tells the side cameras' buffers apart by XRService's allocation order, which
// some XRService restarts reverse; tools/check_sides.py --ring tells when.
if (swap_sides && index.count("slam_left") && index.count("slam_right")) {
// some XRService restarts reverse (see the top).
const bool have_sides = index.count("slam_left") && index.count("slam_right");
std::map<std::string, uint64_t> last; // per camera: the frame last used
auto exchange_sides = [&] {
std::swap(index["slam_left"], index["slam_right"]);
std::swap(last["slam_left"], last["slam_right"]);
if (dark.count("slam_left_dk") && dark.count("slam_right_dk")) std::swap(dark["slam_left_dk"], dark["slam_right_dk"]);
std::printf("side cameras swapped (--swap-sides)\n");
};
if (names_swapped && have_sides) {
exchange_sides();
std::printf("side cameras exchanged (%s)\n", sides_from == "option" ? "--sides 1" : "HANDS_SWAP_SIDES=1");
}
// the mono cameras the side check may pair (not the colour ones)
std::map<std::string, Camera> side_cams;
for (auto &[name, i] : index) side_cams[name] = calib[name];
SideCheck side_check(side_cams);
bool checking = track && have_sides && side_check.usable();
int side_round = 0; // auto: 0 deciding, then each check after a decision
if (!track && sides_mode == "auto" && have_sides)
std::printf("side cameras: as ft-camd names them (--record-only can't tell; the recording's sides.json says so)\n");
// The colour pair, calibrated (see the top), unless only the mono cameras are wanted.
if (color.size() == 2 && (automatic || fixed != Cams::Mono)) {
const std::string left = color.count(color_left) ? color_left : color.begin()->first;
@@ -345,7 +414,6 @@ int main(int argc, char **argv) {
Tracker tracker(used, nets, pool);
tracker.set_keep_presence(keep_presence);
std::map<std::string, std::vector<uint8_t>> pixels;
std::map<std::string, uint64_t> last; // per camera: the frame last used
std::map<std::string, uint64_t> lit_seen; // per colour camera: the frame last counted for the light
const uint64_t start = mono_ns();
uint64_t t_status = start, next_ns = 0, t_want = 0, t_glog = 0;
@@ -357,6 +425,71 @@ int main(int argc, char **argv) {
// to place the colour frames, whose capture clock is their own (see the top).
double mono_delay_ns = -1;
const std::string want_file = run_dir() + "/color-fps";
// The side cameras' naming, for the hand recorder and other tools (hands/rec/session.py
// reads it): written by a tracking, publishing ft-hands at the start, on every change and
// every 2 s, and removed when it exits. swapped: ft-camd's naming is backwards (null: not
// known yet); names_swapped: whether this ft-hands exchanged them; ring_ino: the ring file's
// inode (a new ft-camd makes a new one, and the decision is only good for that run).
const std::string sides_file = run_dir() + "/sides.json";
const bool write_sides_file = publish && track;
struct stat ring_st{};
stat(ring_path.c_str(), &ring_st);
uint64_t t_sides = 0;
auto write_sides = [&] {
if (!write_sides_file) return;
t_sides = mono_ns();
write_file(sides_file,
"{\"pid\": " + std::to_string(getpid()) + ", \"ring_ino\": " + std::to_string(ring_st.st_ino) +
", \"mode\": \"" + sides_mode + "\", \"state\": \"" + sides_state + "\", \"swapped\": " +
json_bool(truth) + ", \"decided_by\": " + json_str(truth ? decided_by : "") +
", \"names_swapped\": " + json_bool(names_swapped) +
", \"decided_after_s\": " + std::to_string(decided_after_s) +
", \"evidence\": " + (decision_evidence.empty() ? "null" : decision_evidence) +
", \"checking\": " + (checking ? side_check.json() : "null") +
", \"updated_ns\": " + std::to_string(mono_ns()) + "}\n");
};
write_sides();
// A verdict from the side check (see the top and track/sides.h).
auto side_verdict = [&](SideCheck::Verdict v, uint64_t now) {
const bool backwards = v == SideCheck::Swapped; // relative to the names as they are now
const double after = (now - start) / 1e9;
const std::string ev = side_check.json(), text = side_check.summary();
if (sides_mode != "auto") { // forced: only say so
const std::string what = (sides_from == "option" ? "--sides " : "HANDS_SWAP_SIDES=") + sides_mode;
if (backwards)
std::printf("side cameras: %s looks WRONG: the hands say the side cameras are the other way round (%s). "
"Use auto.\n", what.c_str(), text.c_str());
else
std::printf("side cameras: %s agrees with the hands (%s)\n", what.c_str(), text.c_str());
sides_state = backwards ? "forced, disagrees" : "forced, agrees";
decision_evidence = ev;
checking = false;
} else if (side_round == 0 || backwards) {
if (backwards) {
exchange_sides();
names_swapped = !names_swapped;
tracker.exchange("slam_left", "slam_right");
if (rec) rec_names.push_back({rec->added(), names_swapped});
}
const bool reversed = side_round > 0;
truth = names_swapped, decided_by = "auto", decided_after_s = after, decision_evidence = ev;
sides_state = reversed ? "decided, reversed" : "decided";
std::printf("side cameras: %s after %.1f s (%s)\n",
reversed ? "decision REVERSED" : names_swapped ? "SWAPPED, now exchanged" : "as named", after,
text.c_str());
// check once more with the new names, more strictly; at most two changes
side_check.reset();
side_check.min_clean = 20, side_check.min_votes = 40;
checking = ++side_round < 3;
} else {
std::printf("side cameras: confirmed after %.1f s (%s)\n", after, text.c_str());
sides_state = "confirmed";
checking = false;
}
std::fflush(stdout);
write_rec_sides();
write_sides();
};
// The colour pair's newest frames if both are newer than last used and taken together
// (their own clock): their time, on the mono cameras' capture clock, else 0.
@@ -403,8 +536,13 @@ int main(int argc, char **argv) {
return n ? sum / n : -1;
};
int exit_code = 0;
while (!g_stop && (seconds <= 0 || (mono_ns() - start) / 1e9 < seconds)) {
if (!ring.alive()) return std::fprintf(stderr, "ft-camd stopped\n"), 2;
if (!ring.alive()) {
std::fprintf(stderr, "ft-camd stopped\n");
exit_code = 2;
break;
}
const uint64_t now0 = mono_ns();
const int64_t raw_off = raw_minus_mono_ns();
@@ -490,7 +628,16 @@ int main(int argc, char **argv) {
if (!start_recording(dir + "/" + name, e)) std::fprintf(stderr, "%s\n", e.c_str());
}
if (rec) { // about 80 MB/s; dark frames double that, color frames add 70 MB/s
if ((mono_ns() - rec_start) / 1e9 < record_for) {
const bool due = record_hz <= 0 || tmin >= rec_next_ns; // --record-hz skips the sets between
if (due && record_hz > 0) rec_next_ns = tmin + uint64_t(1e9 / record_hz) - 5'000'000;
if ((mono_ns() - rec_start) / 1e9 >= record_for) {
write_rec_sides();
const size_t n = rec->written(), d = rec->dropped();
rec.reset(); // writes out what's queued
std::printf("recording done: %zu sets, %zu dropped\n", n, d);
std::fflush(stdout);
if (!track) break;
} else if (due) {
for (auto &[name, i] : dark) { // the newest dark and color frames, as they are
fh_ring_slot_t meta;
const uint64_t n = ring.latest(i);
@@ -500,12 +647,6 @@ int main(int argc, char **argv) {
meta.dqbuf_ns});
}
rec->add(frames);
} else {
const size_t n = rec->written(), d = rec->dropped();
rec.reset(); // writes out what's queued
std::printf("recording done: %zu sets, %zu dropped\n", n, d);
std::fflush(stdout);
if (!track) break;
}
}
if (!track && rec && status > 0 && (mono_ns() - t_status) / 1e9 >= status) {
@@ -548,6 +689,16 @@ int main(int argc, char **argv) {
const auto hands = tracker.step(images, int64_t(tmin));
const uint64_t capture = uint64_t(int64_t(tmin) - raw_off); // CLOCK_MONOTONIC
const std::vector<Seen> views = tracker.views_now();
std::vector<Seen> side_views; // the tracker's views, plus the side check's own looks
if (checking) {
side_views = views;
for (Seen &v : side_check.probe(nets, pool, images, views, int64_t(tmin))) side_views.push_back(v);
}
if (checking && side_check.add(side_views, int64_t(tmin)) > 0) {
const SideCheck::Verdict v = side_check.verdict();
if (v != SideCheck::Undecided) side_verdict(v, mono_ns());
}
if (mono_ns() - t_sides > 2'000'000'000ull) write_sides();
if (gestures_on) {
grip.update(hands, views, int64_t(capture));
pinch.update(hands, views, int64_t(capture), grip.gripping());
@@ -603,6 +754,9 @@ int main(int argc, char **argv) {
s.handoff_miss, s.dups, s.splits, s.created, s.merged, s.forgotten,
!rec ? "" : (" recorded " + std::to_string(rec->written()) + " dropped " +
std::to_string(rec->dropped())).c_str());
if (checking)
std::printf(" side cameras: %s, %s\n", side_round ? "checking the decision" : "deciding",
side_check.summary().c_str());
if (gestures_on) {
std::printf(" pinches: left %u right %u (held back, palm down: %d %d) grips: left %u right %u",
pinch.side(0).begins, pinch.side(1).begins, pinch.held_back[0], pinch.held_back[1],
@@ -628,11 +782,13 @@ int main(int argc, char **argv) {
}
}
if (!color.empty()) unlink(want_file.c_str());
if (write_sides_file) unlink(sides_file.c_str());
write_rec_sides();
if (publish) pub.write({}, mono_ns());
if (publish && gestures_on) {
pinch.release(int64_t(mono_ns())); // a drag in progress ends, as lost
grip.release(int64_t(mono_ns()));
gestures.write(pinch, grip, mono_ns());
}
return 0;
return exit_code;
}
+1
View File
@@ -57,6 +57,7 @@ void Recorder::add(const std::vector<SetFrame> &frames) {
return;
}
queue_.push_back(std::move(rec));
++added_;
}
wake_.notify_one();
}
+4 -1
View File
@@ -42,6 +42,9 @@ public:
~Recorder();
bool open(const std::string &dir, std::string &err);
void add(const std::vector<SetFrame> &frames);
// Sets taken (not dropped for a full queue): the next one's place in the file, unless a
// write fails.
size_t added() const { return added_; }
size_t written() const { return written_; }
size_t dropped() const { return dropped_; }
@@ -53,7 +56,7 @@ private:
std::condition_variable wake_;
std::deque<std::vector<uint8_t>> queue_;
bool stop_ = false;
size_t written_ = 0, dropped_ = 0;
size_t written_ = 0, dropped_ = 0, added_ = 0;
};
// Reads a recording back one set at a time.
+81 -2
View File
@@ -3,6 +3,7 @@
//
// ft-handreplay DIR [--oracle N] [--slow F] [--timeline FILE] [--threads N] [--models DIR]
// [--from S] [--to S] [--contrast MODE|PALM/HAND] (clahe[:CLIP], none, stretch)
// [--sides file|0|1|auto]
//
// --oracle N: every N-th set, also search every tile of every camera (slow), to see
// which hands were there to find. Compares that with what the tracker had.
@@ -27,18 +28,29 @@
// views, hand scale, then its 21 world landmarks (the model's own 3D pose, averaged
// over its views, times the scale; metres, hand-centred) and its 21 published
// points (head frame). For studying gestures (pinch against typing, a fist).
// --sides file|0|1|auto: the side cameras' names as DIR/sides.json says they should be (file, the
// default: ft-hands writes one with every recording; hands/rec/sides.py has the rule;
// without one, as recorded), as recorded (0), exchanged (1), or as ft-hands' auto
// decides them from the recorded names (track/sides.h): exchanged from the set it decides on,
// the tracker's views moving with their images (Tracker::exchange). The side check runs in every mode, and the report
// says what it found and when: seconds into the recording, and after how long of
// hands (from the first set with a hand in view).
// --depth FILE: per processed set, a line per hand for tools/depth_report.py: its views'
// cameras, triangulation residual, hand scale, measured and published palm, and
// each view's one-view palm (Tracker::single_view at the hand's scale). The
// header has each camera's centre and focal length.
#include "pinch.h"
#include "record.h"
#include "sides.h"
#include "tracker.h"
#include <json/json.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <set>
#include <string>
@@ -76,7 +88,7 @@ int main(int argc, char **argv) {
double keep_presence = 0.5; // landmark presence a tracked view needs to stay
PinchParams pinch_params;
GripParams grip_params;
std::string use = "mono", color_left = "color_video0", color_crop = "subtract";
std::string use = "mono", color_left = "color_video0", color_crop = "subtract", sides = "file";
std::string timeline, depth, poses, models = std::string(argv[0]).substr(0, std::string(argv[0]).rfind('/') + 1) + "../models/ncnn";
for (int i = 2; i < argc; ++i) {
const std::string a = argv[i];
@@ -91,6 +103,7 @@ int main(int argc, char **argv) {
else if (a == "--cost") cost = true;
else if (a == "--keep-presence" && more) keep_presence = std::atof(argv[++i]);
else if (a == "--cams" && more) use = argv[++i];
else if (a == "--sides" && more) sides = argv[++i];
else if (a == "--pinch-begin" && more) pinch_params.begin_m = std::atof(argv[++i]);
else if (a == "--pinch-end" && more) pinch_params.end_m = std::atof(argv[++i]);
else if (a == "--pinch-triangulated") pinch_params.triangulated = true;
@@ -120,6 +133,24 @@ int main(int argc, char **argv) {
std::vector<std::vector<uint8_t>> px;
if (!in.next(cams, px)) return std::fprintf(stderr, "%s: no sets\n", dir.c_str()), 1;
if (use != "mono" && use != "color" && use != "all") return std::fprintf(stderr, "--cams mono|color|all\n"), 1;
if (sides != "file" && sides != "0" && sides != "1" && sides != "auto")
return std::fprintf(stderr, "--sides file|0|1|auto\n"), 1;
// --sides file: from which set on the recorded names need exchanging (hands/rec/sides.py)
std::vector<std::pair<int, bool>> file_runs = {{0, false}};
if (sides == "file") {
std::ifstream f(dir + "/sides.json");
Json::Value v;
Json::CharReaderBuilder b;
std::string e;
if (f && Json::parseFromStream(b, f, &v, &e) && v["swapped"].isBool()) {
file_runs.clear();
for (const Json::Value &r : v["names_swapped"])
file_runs.push_back({r[0].asInt(), r[1].asBool() != v["swapped"].asBool()});
if (file_runs.empty()) file_runs = {{0, v["swapped"].asBool()}};
std::printf("side cameras: %s.json says swapped %s (%s)\n", (dir + "/sides").c_str(),
v["swapped"].asBool() ? "true" : "false", v["decided_by"].asString().c_str());
}
}
if (use != "mono") {
std::vector<std::string> nodes;
for (auto &c : cams)
@@ -136,6 +167,21 @@ int main(int argc, char **argv) {
}
Pool pool(threads, {2, 3, 4});
Tracker tracker(used, nets, pool);
// The side cameras (see the top): names_swapped exchanges slam_left's and slam_right's names
// as sets are read.
bool names_swapped = sides == "1";
std::map<std::string, Camera> mono;
for (auto &[name, c] : used)
if (name.rfind("color_", 0) != 0) mono[name] = c;
SideCheck side_check(mono);
bool checking = side_check.usable();
int side_round = 0;
double first_hand_ts = -1;
std::string side_report;
auto rename = [&](const std::string &n) -> std::string {
if (!names_swapped) return n;
return n == "slam_left" ? "slam_right" : n == "slam_right" ? "slam_left" : n;
};
tracker.set_keep_presence(keep_presence);
FILE *dp = depth.empty() ? nullptr : std::fopen(depth.c_str(), "w");
FILE *pp = poses.empty() ? nullptr : std::fopen(poses.c_str(), "w");
@@ -164,13 +210,16 @@ int main(int argc, char **argv) {
double grip_begin_ts[2] = {0, 0};
std::vector<double> grip_len[2];
do {
if (sides == "file")
for (auto &[first, rename] : file_runs)
if (index + 1 >= first) names_swapped = rename;
std::map<std::string, Image> images;
// the set's time: the mono cameras' when they're used (the color ones run on another
// clock); color frames can repeat across sets, so a set that doesn't move time on is skipped
uint64_t t = UINT64_MAX, t_color = UINT64_MAX;
for (size_t i = 0; i < cams.size(); ++i) {
if (!used.count(cams[i].name)) continue;
images[cams[i].name] = {px[i].data(), int(cams[i].width), int(cams[i].height), int(cams[i].width)};
images[rename(cams[i].name)] = {px[i].data(), int(cams[i].width), int(cams[i].height), int(cams[i].width)};
uint64_t &ti = std::string(cams[i].name).rfind("color_", 0) == 0 ? t_color : t;
ti = std::min(ti, cams[i].capture_ns);
}
@@ -199,6 +248,30 @@ int main(int argc, char **argv) {
busy_ms += ms;
busy_until = t + uint64_t(ms * slow * 1e6) + 3'000'000; // + the ring hand-off
const std::vector<Seen> seen = tracker.views_now();
if (first_hand_ts < 0 && !seen.empty()) first_hand_ts = ts;
std::vector<Seen> side_views = seen;
if (checking)
for (Seen &v : side_check.probe(nets, pool, images, seen, int64_t(t))) side_views.push_back(v);
if (checking && side_check.add(side_views, int64_t(t)) > 0 && side_check.verdict() != SideCheck::Undecided) {
const bool backwards = side_check.verdict() == SideCheck::Swapped;
char line[400];
std::snprintf(line, sizeof line, "side cameras: %s %s at %.1f s (%.1f s after the first hand; %s)\n",
side_round ? "check" : "decision",
backwards ? (sides == "auto" ? "SWAPPED, exchanged" : "SWAPPED") : "as named", ts,
ts - first_hand_ts, side_check.summary().c_str());
side_report += line;
if (tl) std::fprintf(tl, "%.3f %s", ts, line);
if (sides != "auto") {
checking = false; // file, 0, 1: report only
} else if (side_round == 0 || backwards) {
if (backwards) names_swapped = !names_swapped, tracker.exchange("slam_left", "slam_right");
side_check.reset();
side_check.min_clean = 20, side_check.min_votes = 40;
checking = ++side_round < 3;
} else {
checking = false;
}
}
grip.update(out, seen, int64_t(t));
pinch.update(out, seen, int64_t(t), grip.gripping());
next_ns = t + uint64_t((std::min(tracker.interval(), pinch.engaged() || grip.engaged() ? 1 / 30.0 : 1.0) - 0.005) * 1e9);
@@ -361,6 +434,12 @@ int main(int argc, char **argv) {
std::printf("palm jitter (off a straight line through the last two updates): measured median %.1f mm, 90%% %.1f mm; "
"published median %.1f mm, 90%% %.1f mm\n", jit_raw[jit_raw.size() / 2], jit_raw[jit_raw.size() * 9 / 10],
jit_sm[jit_sm.size() / 2], jit_sm[jit_sm.size() * 9 / 10]);
if (!side_check.usable())
std::printf("side cameras: not both in this recording\n");
else
std::printf("%sside cameras %s: %s\n", side_report.c_str(), side_report.empty() ? "undecided" : "at the end",
checking || side_report.empty() ? side_check.summary().c_str()
: names_swapped ? "exchanged from the recorded names" : "as recorded");
if (o_sets) {
std::printf("oracle, %d sets: a left hand findable in %d, the tracker had it in %d (%.0f%%); right %d, had %d (%.0f%%)\n",
o_sets, o_left, o_left_hit, 100.0 * o_left_hit / std::max(o_left, 1), o_right, o_right_hit,
+216
View File
@@ -0,0 +1,216 @@
#include "sides.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <functional>
namespace {
bool is_side(const std::string &name) { return name == "slam_left" || name == "slam_right"; }
double median(std::vector<double> v) {
if (v.empty()) return -1;
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
return v[v.size() / 2];
}
constexpr int kMaxPairs = 12; // per step
constexpr int kMinFront = 15; // of 21 landmarks: rays meeting in front of both cameras
constexpr double kNear = 0.05, kFar = 1.5; // m along each ray: where a hand can be
constexpr double kRatioLo = 0.6, kRatioHi = 1.9; // as Tracker's size check (tracker.cpp)
constexpr double kProbeDepths[] = {0.8, 1.0, 1.25}; // probe(): times the one-view distance
} // namespace
SideCheck::SideCheck(const std::map<std::string, Camera> &cams) {
for (const auto &[name, cam] : cams) cams_[name] = &cam;
if (cams_.count("slam_left")) left_ = cams_["slam_left"];
if (cams_.count("slam_right")) right_ = cams_["slam_right"];
}
const Camera *SideCheck::cam(const std::string &name, bool swapped) const {
if (swapped && name == "slam_left") return right_;
if (swapped && name == "slam_right") return left_;
const auto it = cams_.find(name);
return it == cams_.end() ? nullptr : it->second;
}
double SideCheck::miss(const Camera &ca, const Landmarks &a, const Camera &cb, const Landmarks &b) const {
std::vector<double> d;
V3 palm{};
bool have_palm = false;
for (int k = 0; k < 21; ++k) {
const V3 oa = ca.origin, da = ca.ray(a.pts[k]), ob = cb.origin, db = cb.ray(b.pts[k]);
const V3 w = oa - ob;
const double ab = dot(da, db), p = dot(da, w), q = dot(db, w), den = 1 - ab * ab;
if (den < 1e-9) continue; // parallel rays
const double ta = (ab * q - p) / den, tb = (q - ab * p) / den;
if (ta < kNear || tb < kNear || ta > kFar || tb > kFar) continue;
const V3 pa = oa + da * ta, pb = ob + db * tb;
d.push_back(norm(pa - pb));
if (k == 9) palm = (pa + pb) * 0.5, have_palm = true;
}
if (int(d.size()) < kMinFront || !have_palm) return -1;
// as far from each camera as the hand's apparent size says (a hand of the model's size)
for (const auto &[c, lm] : {std::pair<const Camera *, const Landmarks *>{&ca, &a}, {&cb, &b}}) {
V3 mono[21];
if (!Tracker::single_view(*c, *lm, 1.0, mono)) return -1;
const double r = norm(palm - c->origin) / std::max(norm(mono[9] - c->origin), 1e-6);
if (r < kRatioLo || r > kRatioHi) return -1;
}
return median(d);
}
SideCheck::Miss SideCheck::test(const std::string &cam_a, const Landmarks &a, const std::string &cam_b,
const Landmarks &b) const {
Miss out{{-1, -1}};
for (int way = 0; way < 2; ++way) {
const Camera *ca = cam(cam_a, way == 1), *cb = cam(cam_b, way == 1);
if (ca && cb) out.m[way] = miss(*ca, a, *cb, b);
}
return out;
}
int SideCheck::vote(const Miss &m) {
for (int w = 0; w < 2; ++w) {
const double win = m.m[w], other = m.m[1 - w];
if (win >= 0 && win < kGood && (other < 0 || other > kClear * win)) return w;
}
return -1;
}
int SideCheck::add(const std::vector<Seen> &views, int64_t t_ns) {
if (!usable()) return 0;
std::vector<const Seen *> vs;
for (const Seen &v : views)
if (cams_.count(v.cam)) vs.push_back(&v);
int pairs = 0, voted = 0;
for (size_t i = 0; i < vs.size(); ++i)
for (size_t j = i + 1; j < vs.size() && pairs < kMaxPairs; ++j) {
if (vs[i]->cam == vs[j]->cam || (!is_side(vs[i]->cam) && !is_side(vs[j]->cam))) continue;
++pairs;
const Miss m = test(vs[i]->cam, vs[i]->lm, vs[j]->cam, vs[j]->lm);
const int v = vote(m);
if (v < 0) continue;
++votes[v], ++voted;
misses_[0].push_back(m.m[0]), misses_[1].push_back(m.m[1]);
if (first_ns_ < 0) first_ns_ = t_ns;
last_ns_ = t_ns;
}
return voted;
}
std::vector<Seen> SideCheck::probe(const Nets &nets, Pool &pool, const std::map<std::string, Image> &images,
const std::vector<Seen> &views, int64_t t_ns) {
if (!usable() || (probe_ns_ >= 0 && (t_ns - probe_ns_) / 1e9 < probe_interval_s - 0.01)) return {};
struct Job {
int way;
std::string cam;
Roi roi;
Landmarks lm;
};
std::vector<Job> jobs;
// the views to look from: confident ones, a different hand each time (round robin)
std::vector<const Seen *> order;
for (const Seen &v : views)
if (cams_.count(v.cam) && v.lm.presence >= 0.5) order.push_back(&v);
std::sort(order.begin(), order.end(), [](const Seen *a, const Seen *b) { return a->lm.presence > b->lm.presence; });
if (!order.empty()) std::rotate(order.begin(), order.begin() + (probe_turn_++ % order.size()), order.end());
// Only the other naming: the tracker hands hands over to the other cameras under the names
// as they are every step, and add() tests what that finds.
for (int way = 1; way < 2; ++way) {
bool found = false;
for (const Seen *v : order) {
for (const char *target : {"slam_left", "slam_right"}) {
if (v->cam == target || !images.count(target)) continue;
bool paired = false; // the tracker has this hand there already: add() tests that pair
for (const Seen &u : views) paired = paired || (u.cam == target && u.hand == v->hand && v->hand > 0);
if (paired) continue;
const Camera *cs = cam(v->cam, way == 1), *ct = cam(target, way == 1);
V3 pts[21];
if (!cs || !ct || !Tracker::single_view(*cs, v->lm, 1.0, pts)) continue;
// the hand at a few distances around the one-view guess, as the tracker hands
// a hand over to another camera (a crop around where its landmarks land)
const V3 axis{ct->R[0][2], ct->R[1][2], ct->R[2][2]}, o = cs->origin;
for (double f : kProbeDepths) {
V2 uv[21];
bool visible = true;
for (int k = 0; k < 21; ++k) {
const V3 p = o + (pts[k] - o) * f;
visible = visible && dot(unit(p - ct->origin), axis) > 0.17; // within 80 degrees
uv[k] = ct->project(p, nullptr);
}
const V2 c = uv[9];
if (!visible || c[0] < 0 || c[1] < 0 || c[0] >= ct->width || c[1] >= ct->height) continue;
jobs.push_back({way, target, roi_from_points(uv), {}});
found = true;
}
if (found) break;
}
if (found) break;
}
}
if (jobs.empty()) return {};
probe_ns_ = t_ns;
std::vector<std::function<void()>> run;
for (Job &j : jobs) run.push_back([&nets, &images, &j] { j.lm = nets.landmarks(images.at(j.cam), j.roi); });
pool.run(run);
static const bool debug = std::getenv("FT_SIDES_DEBUG") != nullptr;
std::vector<Seen> out;
probes += int(jobs.size());
for (int way = 1; way < 2; ++way) { // the best look
const Job *best = nullptr;
for (const Job &j : jobs)
if (j.way == way && (!best || j.lm.presence > best->lm.presence)) best = &j;
if (debug && best)
std::fprintf(stderr, "side probe (%s) %s at %.0f %.0f size %.0f: presence %.2f\n", way ? "swapped" : "as named",
best->cam.c_str(), best->roi.center[0], best->roi.center[1], best->roi.size, best->lm.presence);
if (!best || best->lm.presence < 0.5) continue;
++probe_hits;
out.push_back(Seen{best->cam, 0, best->roi, best->lm, {}});
}
return out;
}
SideCheck::Verdict SideCheck::verdict() const {
const int total = votes[0] + votes[1], w = votes[0] >= votes[1] ? 0 : 1;
const bool clean = votes[1 - w] == 0 && votes[w] >= min_clean;
const bool clear = votes[w] >= min_votes && votes[1 - w] <= max_other * total;
if (!(clean || clear) || span_s() < min_span_s) return Undecided;
return w == 0 ? AsNamed : Swapped;
}
void SideCheck::reset() {
votes[0] = votes[1] = 0;
probes = probe_hits = 0;
probe_ns_ = -1;
misses_[0].clear(), misses_[1].clear();
first_ns_ = last_ns_ = -1;
}
double SideCheck::median_miss_mm(int way) const {
std::vector<double> v;
for (double m : misses_[way])
if (m >= 0) v.push_back(m * 1000);
return median(v);
}
std::string SideCheck::summary() const {
char s[320];
std::snprintf(s, sizeof s,
"votes as named %d, swapped %d, over %.1f s; median ray miss as named %.1f mm, swapped %.1f mm "
"(-1: never met); probes %d, found %d",
votes[0], votes[1], span_s(), median_miss_mm(0), median_miss_mm(1), probes, probe_hits);
return s;
}
std::string SideCheck::json() const {
char s[320];
std::snprintf(s, sizeof s,
"{\"as_named\": %d, \"swapped\": %d, \"seconds\": %.2f, \"miss_mm\": [%.1f, %.1f], \"probes\": %d, "
"\"found\": %d}",
votes[0], votes[1], span_s(), median_miss_mm(0), median_miss_mm(1), probes, probe_hits);
return s;
}
+94
View File
@@ -0,0 +1,94 @@
// Are the side cameras' images under the right names? ft-camd tells slam_left's buffers from
// slam_right's only by the order XRService allocated them, and some XRService starts reverse
// that order: then each side camera's images carry the other's name, every hand is seen by one
// camera only, at the wrong depth, and the cutouts land beside the hands.
//
// SideCheck tells from the hands the tracker already finds. Whenever a hand's landmarks are
// found in two cameras in the same frame set (one of them a side camera), the rays through its
// 21 landmarks are intersected twice: with the calibrations as the images are named, and with
// the two side cameras' calibrations exchanged. The same hand seen right meets within a few mm,
// in front of both cameras and as far away as its apparent size says; under the wrong naming
// the rays miss by centimetres or meet behind a camera. Each such pair is a vote. It decides once
// one way has min_clean votes and the other none, or min_votes with at most max_other of all
// votes the other way, over at least min_span_s of hands.
//
// The tracker's own views rarely give a pair when the names are wrong: it hands a hand over
// to the other cameras where the wrong calibration puts it, finds nothing there, and keeps it in
// one camera (the replays of swapped recordings: one hand, every handoff a miss, no pair). So
// probe() looks for itself, 5 times a second while it's checking: it takes a hand the tracker
// sees, places it in 3D from that one view (as far as its size says) with the side cameras
// exchanged, and runs the landmark model where that puts it in the other side camera, at 0.8,
// 1 and 1.25 times the one-view distance. That's the tracker's handoff under the other naming
// (the tracker does it under the current one every step); the palm detector misses many of
// these hands, which the landmark model finds from a good crop. What it finds is a view
// like the tracker's, and the test above votes on it: finding a hand there proves nothing by
// itself. It doesn't depend on how the tracker paired the views up.
//
// FT_SIDES_DEBUG=1 in the environment prints each probe's crop and what it found (stderr).
//
// Upper-camera pairs with a side camera count too (the upper pair's own naming was checked
// stable: tools/check_sides.py --pair upper). Two upper views alone say nothing.
#pragma once
#include "tracker.h"
#include <map>
#include <string>
#include <vector>
class SideCheck {
public:
enum Verdict { Undecided, AsNamed, Swapped };
// cams: the mono cameras' calibrations; slam_left and slam_right are needed.
explicit SideCheck(const std::map<std::string, Camera> &cams);
bool usable() const { return left_ && right_; }
// One step's fresh views (Tracker::views_now, plus probe()'s), cameras named as the
// images are now. Returns how many pairs voted.
int add(const std::vector<Seen> &views, int64_t t_ns);
// At most every probe_interval_s: for each naming, one view the tracker has, looked for in
// the other side camera where that naming puts it (see the top). Returns the views found
// (presence 0.5 or more), for add() with the tracker's. Runs the models on pool.
std::vector<Seen> probe(const Nets &nets, Pool &pool, const std::map<std::string, Image> &images,
const std::vector<Seen> &views, int64_t t_ns);
double probe_interval_s = 0.2;
int probes = 0, probe_hits = 0; // landmark model runs, and the views they found
// One pair: the median landmark ray miss (m) as named [0] and with the side cameras
// exchanged [1]; -1 where they can't be one hand that way (rays meet behind a camera, or
// at a distance the hand's apparent size rules out). For tests.
struct Miss {
double m[2];
};
Miss test(const std::string &cam_a, const Landmarks &a, const std::string &cam_b, const Landmarks &b) const;
// The vote for a Miss: 0 as named, 1 swapped, -1 neither.
static int vote(const Miss &m);
Verdict verdict() const;
void reset();
// Evidence so far
int votes[2] = {0, 0};
double span_s() const { return first_ns_ >= 0 ? (last_ns_ - first_ns_) / 1e9 : 0; }
double median_miss_mm(int way) const; // over the voted pairs; -1 if none met that way
std::string summary() const; // for the log
std::string json() const; // for the sides file and recordings
// The rule (see the top)
int min_clean = 10, min_votes = 20;
double min_span_s = 1.0, max_other = 0.2;
static constexpr double kGood = 0.015; // m: a pair's median miss to count as meeting
static constexpr double kClear = 3.0; // both meet: one must miss this many times less
private:
const Camera *cam(const std::string &name, bool swapped) const;
double miss(const Camera &ca, const Landmarks &a, const Camera &cb, const Landmarks &b) const;
std::map<std::string, const Camera *> cams_;
const Camera *left_ = nullptr, *right_ = nullptr;
std::vector<double> misses_[2]; // per voted pair, each way (-1: implausible)
int64_t first_ns_ = -1, last_ns_ = -1; // the first and last vote
int64_t probe_ns_ = -1;
unsigned probe_turn_ = 0;
};
+8 -1
View File
@@ -162,7 +162,7 @@ void Tracker::run_landmarks(const std::map<std::string, Image> &images, std::vec
++stats.hand_batches;
}
bool Tracker::single_view(const Camera &cam, const Landmarks &lm, double scale, V3 out[21]) const {
bool Tracker::single_view(const Camera &cam, const Landmarks &lm, double scale, V3 out[21]) {
V3 rays[21];
for (int i = 0; i < 21; ++i) rays[i] = cam.ray(lm.pts[i]);
std::vector<std::pair<double, double>> est; // (depth, weight)
@@ -556,6 +556,13 @@ std::vector<Seen> Tracker::views_now() const {
return out;
}
void Tracker::exchange(const std::string &a, const std::string &b) {
if (!cams_.count(a) || !cams_.count(b)) return;
const Camera *ca = cams_[a], *cb = cams_[b];
for (View &v : views_) v.cam = v.cam == ca ? cb : v.cam == cb ? ca : v.cam;
for (auto &[id, h] : hands_) h.has_pts = false, h.frames = 0, h.residual = -1;
}
void Tracker::drop_camera(const std::string &name) {
views_.erase(std::remove_if(views_.begin(), views_.end(), [&](const View &v) { return v.cam->name == name; }),
views_.end());
+5 -1
View File
@@ -95,7 +95,11 @@ public:
void set_keep_presence(double p) { keep_presence_ = p; }
// One view's 3D hand: each landmark along its ray, as far as how big the palm looks says
// for a hand `scale` times the model's (Hand::scale). False if the palm is degenerate.
bool single_view(const Camera &cam, const Landmarks &lm, double scale, V3 out[21]) const;
static bool single_view(const Camera &cam, const Landmarks &lm, double scale, V3 out[21]);
// Cameras a and b's images were under each other's names (the side cameras, track/sides.h):
// each view moves to the other camera (its crop is in the image's pixels, so it keeps
// following its hand), and every hand's 3D starts over from its views at the next step.
void exchange(const std::string &a, const std::string &b);
private:
struct View {
+3
View File
@@ -23,6 +23,9 @@ packages=(
# tools (hands/tools) need NumPy and OpenCV, which aren't here: Fedora's python3-opencv pulls
# in over a gigabyte (hands/README.md says how to get them)
jsoncpp-devel glibc-static
# hand recorder (hands/rec): its export compresses recordings with zstd; its Upload page and
# hub.py upload to Hugging Face with huggingface_hub (also the hf command, for hf auth login)
zstd python3-huggingface-hub
# Frametop Input Settings app (Kirigami, PySide6)
python3-pyside6 kf6-kirigami kf6-qqc2-desktop-style qt6-qtwayland breeze-icon-theme plasma-breeze
# Frametop remote desktop (VNC bridge through krdp)