diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f52b054..7ae0fe9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,3 +33,26 @@ jobs: # (zarr v3 deprecation + missing rosbag fixture). Until those are # fixed in a separate PR, we gate CI on the MCAP-specific suite. run: pytest tests/test_mcap_*.py --no-cov -v + + quality: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.10", "3.11", "3.12"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + - name: Install quality test dependencies + run: pip install -e ".[dev,lerobot,video,visualize]" + - name: Run quality, viewer, reader, filter, and catalog tests + run: >- + pytest --no-cov -q + tests/test_quality.py tests/test_proprio_diagnostics.py + tests/test_quality_parallel.py tests/test_quality_visualize.py + tests/test_video_quality.py tests/test_video_motion.py tests/test_video_integrity.py + tests/test_filter.py tests/test_filter_video.py + tests/test_lerobot_v3_reader_video.py tests/test_lerobot_v3_video_cache.py + tests/test_catalog.py tests/test_catalog_dedup.py diff --git a/.gitignore b/.gitignore index e7b01e3..72336b1 100644 --- a/.gitignore +++ b/.gitignore @@ -91,6 +91,7 @@ PROJECT_PLAN.md RESEARCH_DIRECTIONS.md INTRO_DRAFTS.md CONVERSION_TESTS.md +SYNC_QA_PLAN.md # Converted dataset outputs stack_lego_rlds/ @@ -98,3 +99,7 @@ stack_lego_rlds/ # HuggingFace cache (user-specific) # ~/.cache/forge/ is outside repo, but just in case .cache/ + +# Local archive of retired plans and drafts (kept out of the repo) +.archive/ +FORGE_GAPS.md diff --git a/ACTION_TOKENIZER_PLAN.md b/ACTION_TOKENIZER_PLAN.md deleted file mode 100644 index cafbd0c..0000000 --- a/ACTION_TOKENIZER_PLAN.md +++ /dev/null @@ -1,196 +0,0 @@ -# Action Tokenizer Featureset for Forge - -## Context - -VLA/robot-learning models don't consume continuous action vectors directly — they -predict **discrete action tokens**. Every lab reinvents the discretization (RT-1 -uniform bins, OpenVLA percentile bins, Pi0-FAST DCT+BPE, BeT k-means), and picking -the right one for a given dataset is trial-and-error. This is exactly the kind of -fragmentation Forge already eliminates for *formats* — so it belongs in Forge as a -first-class featureset. - -**Goal:** add a `forge/tokenize/` module that turns the canonical `Frame.action` -stream into discrete tokens and back (`fit → encode → decode`), with: -1. **Proven strategies** shipped in-box (uniform, OpenVLA-percentile, quantile, mu-law — numpy only). -2. **Extensibility** via a `Protocol` + `TokenizerRegistry` (mirrors `FormatRegistry`) so a - user adds a strategy with one decorator and gets the CLI/compare/serialization for free. -3. **A compare tool** (`forge tokenize compare`) that benchmarks every strategy on *your* - dataset (reconstruction error, compression, vocab utilization) — the differentiator. -4. **A tokenized-dataset writer** (`forge tokenize write`) that emits a LeRobot v3 dataset - with an `action_tokens` column for direct model-training ingestion, plus the fitted - tokenizer saved alongside for **inference-time detokenization**. - -The module deliberately copies the layout of `forge/quality/` and `forge/segment/` -(`config.py` / `models.py` / `analyzer.py` / `__init__.py` / `README.md`) and the -strategy-registry pattern of `forge/formats/registry.py`. - ---- - -## Design - -### Tokenizer interface (`forge/tokenize/base.py`) - -```python -@runtime_checkable -class ActionTokenizer(Protocol): - name: str - @property - def vocab_size(self) -> int: ... # for sizing model embedding / LLM vocab slice - @property - def granularity(self) -> str: ... # "per_step" | "chunk" - @property - def is_fitted(self) -> bool: ... - def fit(self, actions: NDArray) -> "ActionTokenizer": ... # corpus (N, D) - def encode(self, actions: NDArray) -> NDArray: ... # (T, D) -> per_step (T,D) int / chunk (L,) int - def decode(self, tokens: NDArray) -> NDArray: ... # inverse -> (T, D) float - def get_params(self) -> dict: ... # JSON-serializable fitted params - @classmethod - def from_params(cls, params: dict) -> "ActionTokenizer": ... -``` - -`BaseTokenizer` (ABC) implements shared `save(path)` / `load(path)` on top of -`get_params`/`from_params`, embedding the registry `name` so `load` dispatches via the -registry. Small params (bin edges, mins/maxes) serialize to JSON; large arrays -(k-means centroids) to a sidecar `.npz`. This reuses the exact `to_dict`/`from_dict`/ -`to_json`/`from_json` style already in `forge/quality/models.py:119-172`. - -**The per-step vs. chunk distinction is the one real design decision.** Per-step -tokenizers (binning, mu-law) emit one token per action dim per frame → map cleanly to a -per-frame `action_tokens` column. Chunk tokenizers (FAST) consume a horizon of frames -and emit a variable-length sequence → they are usable through the library/compare API -but the **dataset-writer integration is per-step-only in v1** (chunk-column layout is a -documented follow-up). `granularity` makes this explicit and lets the writer reject -chunk tokenizers with a clear error. - -### Registry (`forge/tokenize/registry.py`) - -Direct mirror of `FormatRegistry` (`forge/formats/registry.py:38-115`): -`@TokenizerRegistry.register("openvla-bins")`, `get(name)`, `list_strategies()`, -`create(name, config)`. Add-a-strategy-and-you're-done ergonomics. - -### Built-in strategies (`forge/tokenize/strategies/`) — committed v1, numpy only - -| name | technique | reference | -|---|---|---| -| `uniform-bins` | per-dim min/max → N uniform bins | RT-1 (Brohan 2022) | -| `openvla-bins` | per-dim 1st–99th percentile, uniform bins in range, clip | OpenVLA (Kim 2024) | -| `quantile-bins` | equal-mass bins (each token equally likely) | — | -| `mu-law` | mu-law companding + uniform quantize (fine resolution near 0) | — | - -All four share a `_PerStepBinTokenizer` base (`fit` learns per-dim edges; `encode` = -`np.digitize`; `decode` = bin-center lookup). `vocab_size = num_bins`, `granularity = -"per_step"`. - -### Optional/stretch strategies (designed + registered, behind extras) - -- `fast` (`strategies/fast.py`) — DCT + BPE, Pi0-FAST (Pertsch 2025). `granularity="chunk"`. - Optional dep guard (`scipy`, `tokenizers`) via the `_ensure_*` / - `MissingDependencyError` pattern from `forge/segment/analyzer.py:27-40`. -- `kmeans` (`strategies/kmeans.py`) — BeT cluster tokenizer. Optional dep (`scikit-learn`). - -These prove the extension path end-to-end. Implemented only after the analytical set + -compare + writer are green; gated so base install is unaffected. - -### Comparator (`forge/tokenize/analyzer.py`) - -`TokenizerComparator.compare_dataset(path, strategies=None, sample=0) -> ComparisonReport`. -Iterates `reader.read_episodes()` (same path-resolution + iteration as -`forge/quality/analyzer.py:184-262` / `cli.py:_resolve_dataset_path` at -`forge/cli.py:94-163`), stacks per-frame `frame.action` into an `(N, D)` corpus, fits -each strategy, then for a held sample computes: -- reconstruction **MSE / MAE / max-abs / per-dim RMSE** (encode→decode vs. original), -- **tokens-per-step** and (for chunk strategies) compression ratio, -- **vocab utilization** (fraction of codebook actually used). - -`ComparisonReport` / `TokenizerStats` dataclasses in `forge/tokenize/models.py` with -`to_dict`/`to_json`/`from_json`. - -### Tokenized-dataset writer - -Reuses `LeRobotV3Writer` rather than subclassing. Two small, additive pieces: - -1. **Writer column hook** (`forge/formats/lerobot_v3/writer.py`): add - `tokenized_action_feature: str | None = None` to `LeRobotV3WriterConfig`. In the - row-building loop (`write_episode`, ~writer.py:347-419) — when set and the key is - present in `frame.extras` — emit it as an integer column and declare it in - `self._features` (dtype `int64`, shape `[D]`); exclude it from `_STAT_FEATURES` so - stats aren't computed on token ids. Purely opt-in; default `None` = current behavior. -2. **Write path** (`forge/tokenize/writer.py::tokenize_and_write`): resolve source → - reader; fit (or load) the tokenizer on the action corpus; stream episodes through a - thin Episode wrapper that sets `frame.extras["action_tokens"] = tok.encode(frame.action)` - per frame; call `LeRobotV3Writer.write_episode` / `finalize`; then save the fitted - tokenizer to `/meta/action_tokenizer.json`. v1 runs **sequentially** (mirrors - the converter's sequential loop in `forge/convert/converter.py:316-335`); the parallel - path is a documented follow-up to avoid the worker-serialization complexity. `--keep-actions` - controls whether the original float `action` column is retained alongside tokens. - -Saving the tokenizer into `meta/` gives the **inference detokenize path** for free: -`ActionTokenizer.load("/meta/action_tokenizer.json").decode(model_tokens)`. - -### CLI (`forge tokenize` sub-app in `forge/cli.py`) - -Mirror the `registry_app` wiring (`cli.py:20-24`): `tokenize_app = typer.Typer(...)`, -`app.add_typer(tokenize_app, name="tokenize")`. Commands: - -- `forge tokenize list` — registered strategies + vocab/granularity (rich table). -- `forge tokenize compare [--strategies a,b] [--sample N] [--export report.json]` - — the benchmark table (recon error / compression / vocab-util). **The headline command.** -- `forge tokenize fit --strategy openvla-bins [--num-bins 256] [--sample N] --out tok.json` -- `forge tokenize write --strategy openvla-bins [--tokenizer tok.json] [--keep-actions]` - — emit a LeRobot v3 dataset with `action_tokens`. - -All use the existing `_resolve_dataset_path` helper (`hf://` / local / registry-id), -`rich.progress` (`cli.py:1902-1907`), and `--export`→`report.to_json` conventions. - ---- - -## Files - -**New (`forge/tokenize/`):** `__init__.py`, `base.py`, `registry.py`, `config.py`, -`models.py`, `analyzer.py`, `writer.py`, `README.md`, and -`strategies/{__init__.py, bins.py, mulaw.py}` (committed) + -`strategies/{fast.py, kmeans.py}` (optional/stretch). - -**Modified:** -- `forge/formats/lerobot_v3/writer.py` — opt-in `tokenized_action_feature` column hook (additive). -- `forge/cli.py` — `tokenize` sub-app + commands. -- `forge/__init__.py` — export `tokenize` symbols (match how `quality`/`segment` are surfaced). -- `pyproject.toml` — optional extras `tokenize-fast` (`scipy`,`tokenizers`) and - `tokenize-learned` (`scikit-learn`); add to `all`. **No new base deps** (analytical = numpy). -- `README.md` / `ROADMAP.md` — document the featureset. - -**Tests:** `tests/test_tokenize.py` — encode/decode roundtrip & determinism; vocab -bounds; reconstruction error ↓ as bins ↑; mu-law finer near zero; `save`/`load` param -fidelity; registry registration; `TokenizerComparator` on a synthetic dataset; and the -writer integration producing a readable LeRobot v3 dataset with an `action_tokens` -column. Reuse the synthetic-Episode/mock-reader pattern from `tests/test_filter.py:18-71` -and `conftest.py` fixtures. - ---- - -## Verification - -1. `make test` (or `pytest tests/test_tokenize.py -v`) — all new tests green; existing - writer tests (`test_lerobot_v3_writer.py`) still pass (column hook is opt-in/default-off). -2. `ruff check forge/tokenize forge/cli.py` and `mypy forge/tokenize` clean. -3. End-to-end on a demo dataset: - - `forge tokenize list` - - `forge tokenize compare pusht --sample 20 --export /tmp/tok.json` → sane recon errors, - `openvla-bins` ≲ `uniform-bins` MAE; vocab-util reported. - - `forge tokenize write pusht /tmp/pusht_tok --strategy openvla-bins --sample 5` then - `forge inspect /tmp/pusht_tok` shows the dataset reads back and the `action_tokens` - feature is present in `meta/info.json`. - - Roundtrip in Python: `load("/tmp/pusht_tok/meta/action_tokenizer.json").decode(tokens)` - reconstructs actions within the bin tolerance. - ---- - -## Scope notes / assumptions - -- **v1 committed deliverable = analytical strategies + compare + per-step writer + inference - decode.** FAST and k-means are designed, registered, and dependency-gated, implemented as - a stretch once the core is green (you left the strategy-tier question open; this keeps base - install numpy-only and proves the extension pattern without blocking on heavy deps). -- Chunk-granularity tokenizers (FAST) work through the library/compare API but **not** the - dataset writer in v1 — flagged in the writer with a clear error and noted as follow-up. -- Tokenized-dataset writing is **sequential** in v1; parallel-worker support is a follow-up. diff --git a/CHANGELOG.md b/CHANGELOG.md index 80ac0f2..5733f7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- Quality scorer is now `q-v2-proprio`. Gripper channels and physical action limits are explicit. Invalid or unsupported motion remains unscored. +- Video results use `video-v2-integrity` and retain per-camera events, coverage, and provenance. Video checks remain separate from the proprioception score. +- `video_min_sharpness` is the minimum sampled sharpness. `--video-max-frames` caps decode attempts per camera. Recalibrate filters that depend on these values. + +### Fixed + +- LeRobot v3 episodes retain metadata FPS and declared cameras. Missing requested video frames raise errors instead of returning substitute images. +- Missing observations keep their frame alignment. Temporal video checks reset across gaps and decode errors. +- LeRobot v3 episodes declare image-mode cameras as well as MP4 cameras, so `forge quality --video` checks image-mode datasets. + ### Added - **Image-mode output for the LeRobot v3 writer.** @@ -19,6 +31,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 extra). Video mode stays the default and is unchanged. The LeRobot v3 **reader** decodes these inline PNG columns, so image-mode datasets round-trip through Forge. +- Localized quality events for held commands, motion pauses, reversals, and opt-in position-tracking stalls. +- `forge quality --visualize` with event timelines, camera filters, and click-to-seek playback. +- Camera coverage, decode failures, and timestamp-based frame-drop estimates in video reports. +- A web viewer with episode search, camera focus, playback controls, and all-channel plots. +- A reproducible CPU video benchmark. - **Streaming reads for cloud datasets (LeRobot-v3, Zarr).** `forge inspect` **and `forge ingest`** on `s3://…` / `gs://…` now read over the network with diff --git a/README.md b/README.md index 3d6f085..585a44e 100644 --- a/README.md +++ b/README.md @@ -1,159 +1,144 @@ +

forge

+

-

-███████╗ ██████╗ ██████╗  ██████╗ ███████╗
-██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝
-█████╗  ██║   ██║██████╔╝██║  ███╗█████╗
-██╔══╝  ██║   ██║██╔══██╗██║   ██║██╔══╝
-██║     ╚██████╔╝██║  ██║╚██████╔╝███████╗
-╚═╝      ╚═════╝ ╚═╝  ╚═╝ ╚═════╝ ╚══════╝
-
-

⚒ Robotics Data Toolkit & Data Engine ⚒

-Convert between every major robotics format — then turn a pile of datasets into a queryable, searchable, curatable corpus. -

-PyPI -Open in Colab -Website -Python 3.10+ -License: MIT +The data layer for robot learning.
+Convert any robotics dataset format, score every episode, and curate a corpus you can query, search and train on.

-Forge is two things that share one core: - -- **A format toolkit** — convert, inspect, score, lint, filter, segment, and visualize a single dataset across RLDS, LeRobot, HDF5, MCAP, Zarr, Rosbag, and more. -- **A data engine** — register every episode you collect into an append-only **catalog**, then query it with SQL, search it by natural language, dedup and curate it, and explore it in a visual **Studio**. - -Everything works on local paths, `hf://` datasets, and `s3://` / `gs://` buckets. - - - - - -
- -**Toolkit**  ·  [Install](#install) · [Convert](#convert--interop) · [Quality](#score--clean) · [Filter](#score--clean) · [Segment](#understand) · [Tokenize](#understand) · [Visualize](#understand) +

+PyPI +Open in Colab +Website +Python 3.10+ +License: MIT +

-
+

+Readers for RLDS, LeRobot, GR00T, HDF5, Zarr, MCAP, rosbag and RoboDM feed one Episode/Frame representation, which fans out to LeRobot v3, RLDS, MCAP and RoboDM writers and to the toolkit commands +

-**Data engine**  ·  [Catalog](#the-data-engine) · [Ingest & query](#1-ingest--query) · [Search](#2-search-semantically) · [Dedup & curate](#3-dedup--curate) · [Studio](#4-forge-studio) +Robot learning runs on data that arrives in a dozen formats, at the wrong frame rate, with idle starts, frozen cameras and gripper chatter that nobody notices until a policy learns them. Forge is the layer between the robot and the trainer: -
+- **A format toolkit.** Inspect, convert, score, lint, filter, segment, tokenize and visualize one dataset, across every major robotics format. +- **A data engine.** Register every episode into an append-only **catalog**, then query it with SQL, search it in natural language, dedup and curate it, and review it in **Studio**. -**Reference**  ·  [Cloud storage](#cloud-storage-s3--gcs) · [Registry](#dataset-registry) · [Formats](#supported-formats) · [Command cheatsheet](#command-cheatsheet) · [Roadmap](#roadmap) +Every command works on local paths, `hf://` datasets, registry ids and `s3://` / `gs://` buckets. -
+

+Install · +Convert · +Quality · +Segment & tokenize · +Data engine · +Formats · +Limitations · +Roadmap +

--- ## Install ```bash -pip install forge-robotics # base CLI + LeRobot v3 read/write +pip install forge-robotics # CLI + LeRobot v3 read/write pip install "forge-robotics[all]" # everything ``` -Pick only the extras you need: +
+Pick only the extras you need | Extra | Adds | Extra | Adds | |---|---|---|---| -| `[rlds]` | RLDS / Open-X (TensorFlow) | `[s3]` | Read from Amazon S3 (`s3://`) | -| `[lerobot]` | LeRobot v2/v3 (Parquet) | `[gcs]` | Read from Google Cloud (`gs://`) | -| `[mcap]` | MCAP (ROS2 + Foxglove) | `[catalog]` | The catalog (DuckDB) | +| `[rlds]` | RLDS / Open-X (TensorFlow) | `[s3]` | Read from Amazon S3 | +| `[lerobot]` | LeRobot v2/v3 (Parquet) | `[gcs]` | Read from Google Cloud Storage | +| `[mcap]` | MCAP (ROS 2 + Foxglove) | `[catalog]` | The catalog (DuckDB) | | `[hdf5]` | HDF5 (ALOHA, robomimic) | `[embed]` | Semantic search (SigLIP) | -| `[zarr]` | Zarr (Diffusion Policy, UMI) | `[video]` | Video quality + Studio thumbnails | -| `[rosbag]` | ROS1/ROS2 bags | `[rerun]` | Rerun 3D viewer | - -> **Heads up:** the published PyPI build is the stable **format toolkit**. The **data-engine** features — catalog, semantic search, dedup/curation, and Forge Studio — are newer than the last release tag. To use those today, install from source: -> -> ```bash -> git clone https://github.com/arpitg1304/forge.git && cd forge -> pip install -e ".[all]" -> ``` - -
-RoboDM (optional) +| `[zarr]` | Zarr (Diffusion Policy, UMI) | `[video]` | Video decoding, video quality, Studio thumbnails | +| `[rosbag]` | ROS 1 / ROS 2 bags | `[rerun]` | Rerun viewer | -RoboDM's `.vla` format (up to 70× compression) needs a manual install — the PyPI build has a codec bug: +**RoboDM** (`.vla`, up to 70× compression) needs a manual install because the PyPI build has a codec bug: ```bash -git clone https://github.com/BerkeleyAutomation/robodm.git -pip install -e robodm +git clone https://github.com/BerkeleyAutomation/robodm.git && pip install -e robodm ```
-## Try it in 60 seconds +> [!NOTE] +> The PyPI release is the stable **format toolkit**. The **data engine** (catalog, semantic search, dedup, curation and Studio) is newer than the last release. To use it today, install from source: +> ```bash +> git clone https://github.com/arpitg1304/forge.git && cd forge && pip install -e ".[all]" +> ``` -[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/arpitg1304/forge/blob/main/notebooks/forge_quickstart.ipynb) — pick a public LeRobot dataset, score every episode on 8 quality metrics, drill into the worst demos. No GPU, no auth, ~60 seconds. +## Try it in 60 seconds -Or locally: +[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/arpitg1304/forge/blob/main/notebooks/forge_quickstart.ipynb) Pick a public LeRobot dataset, score every episode and drill into the worst demos. No GPU, no auth. ```bash -forge inspect hf://lerobot/pusht # what's in it? +forge inspect hf://lerobot/pusht # what's in it? +forge quality hf://lerobot/pusht --fps 10 # score every episode forge convert hf://lerobot/pusht ./out --format lerobot-v3 # convert it -forge quality hf://lerobot/pusht # score every episode ``` -Forge speaks a hub-and-spoke architecture: **any reader → `Episode`/`Frame` → any writer**. Add a reader, get every writer for free — no N×M conversion logic. See [docs/architecture.md](docs/architecture.md). +Forge is hub-and-spoke: **any reader → `Episode` / `Frame` → any writer**. Add a reader and every writer works with it, with no N×M conversion code. See [docs/architecture.md](docs/architecture.md). --- # The format toolkit -Per-dataset operations. Every command takes a local path, a registry id (`droid`), an `hf://` URL, or an `s3://` / `gs://` URI. +One dataset at a time. Every command takes a local path, a registry id (`droid`), an `hf://` URL or an `s3://` / `gs://` URI. -## Convert & interop +## Convert ```bash -forge inspect ./dataset # structure, schema, cameras +forge inspect ./dataset # structure, schema, cameras, fps forge convert ./rlds_dataset ./out --format lerobot-v3 # convert between formats -forge convert ./data.zarr ./out --format lerobot-v3 --visualize +forge convert ./data.zarr ./out --format lerobot-v3 --fps 10 --visualize ``` | You have | You want | One command | |---|---|---| -| MCAP from ROS2 / teleop | LeRobot v3 for HuggingFace | `forge convert teleop.mcap ./out --format lerobot-v3` | -| RLDS from Open-X | LeRobot for finetuning | `forge convert hf://openvla/modified_libero_rlds ./out -f lerobot-v3` | +| MCAP from ROS 2 / teleop | LeRobot v3 for Hugging Face | `forge convert teleop.mcap ./out --format lerobot-v3` | +| RLDS from Open-X | LeRobot for fine-tuning | `forge convert hf://openvla/modified_libero_rlds ./out -f lerobot-v3` | | HDF5 from ALOHA / robomimic | MCAP for Foxglove playback | `forge convert aloha.hdf5 ./out --format mcap` | | Zarr from Diffusion Policy | LeRobot v3 | `forge convert pusht.zarr ./out --format lerobot-v3` | -For complex conversions, generate a YAML config: `forge inspect ds/ --generate-config config.yaml`, then `forge convert ds/ out/ --config config.yaml`. See [docs/configuration.md](docs/configuration.md). +For complex conversions, generate a YAML config with `forge inspect ds/ --generate-config config.yaml`, then run `forge convert ds/ out/ --config config.yaml`. See [docs/configuration.md](docs/configuration.md), and note which config keys are applied today under [Known limitations](#known-limitations). + +## Score and clean -## Score & clean +

+An episode timeline with camera, state, gripper and timestamp rows, flagged for a motion pause, gripper chatter, a frozen camera and a timestamp gap, next to a heuristic score of 6.4 out of 10 +

-Quality — score each episode 0–10 from proprioception alone (no video needed), on 8 research-backed metrics. +**Quality** scores every episode from proprioception, and optionally from video. The 0–10 score is a heuristic; episodes that can't be scored stay `null`. Every flag is a review candidate, not a failure label. ```bash -forge quality ./my_dataset -forge quality ./my_dataset --video --video-level motion # also score camera streams +forge quality ./my_dataset --fps 10 --gripper-dims 6 --export quality.json --visualize +forge quality ./my_dataset --video --video-level motion # needs [video] ``` -
-The 8 metrics - -- **Smoothness (LDLJ)** — jerk-based smoothness (Hogan & Sternad, 2009) -- **Dead actions** — zero/constant action detection (Kim et al. "OpenVLA", 2024) -- **Gripper chatter** — rapid open/close transitions (Sakr et al., 2024) -- **Static detection** — idle periods (Liu et al. "SCIZOR", 2025) -- **Timestamp regularity** — dropped frames and frequency jitter -- **Action saturation** — time spent at hardware limits -- **Action entropy** — diversity vs repetitiveness (Belkhale et al. "DemInf", 2025) -- **Path length** — wandering / hesitation in joint space - -`--video` adds pixel metrics (blur, exposure, frozen frames) and, at `--video-level motion`, optical-flow motion, camera-vs-scene split, and shot-cut detection. Needs `[video]`. Details: [quality](forge/quality/README.md) · [video quality](forge/quality/video/README.md). -
+- **Motion:** held commands, measured-motion pauses, direction reversals, smoothness (LDLJ), action entropy, path length. +- **Timing:** timestamp gaps and jitter. +- **Gripper:** chatter on the channels you name. Physical action limits are set explicitly. +- **Tracking:** stall candidates from known absolute-position action/state pairs (`--tracking-pairs`). +- **Video:** camera coverage, decode failures, blur, exposure, frozen frames and estimated observation gaps. -Lint — check dataset *hygiene* (missing task strings, ambiguous cameras, low-res / single-view, missing action fields) against HuggingFace's LeRobot guidelines. Exits non-zero, so it drops into CI. +Details: [quality](forge/quality/README.md) · [video quality](forge/quality/video/README.md) · [viewer](forge/visualize/README.md) · [validation and benchmarks](docs/reports/README.md). + +**Lint** checks dataset hygiene against Hugging Face's LeRobot guidelines: missing task strings, ambiguous cameras, low resolution, single view, missing action fields. It exits non-zero, so it drops into CI. ```bash -forge lint ./my_dataset --strict # fail on warnings too +forge lint ./my_dataset --strict ``` -Filter — drop bad episodes by quality, flags, or ids → a new dataset. +**Filter** drops episodes by score, flags or ids, and writes a new dataset. Pass the report you reviewed so filtering uses the same scores: ```bash -forge filter ./my_dataset ./clean --min-quality 6.0 --exclude-flags jerky,mostly_static +forge filter ./my_dataset ./clean --from-report quality.json --min-quality 6.0 \ + --exclude-flags jerky,mostly_static,gripper_chatter ``` -Dedup — remove near-duplicate episodes *within one dataset* by perceptual hashing of keyframes (numpy only, no model). +**Dedup** removes near-duplicate episodes within one dataset by perceptual hashing of keyframes (numpy only, no model). ```bash forge dedup ./my_dataset ./deduped --threshold 0.05 @@ -163,29 +148,27 @@ Details: [lint](forge/lint/README.md) · [filter](forge/filter/README.md) · [de ## Understand -Segment — split episodes into phases (reach / grasp / place) via PELT changepoint detection on proprio. +**Segment** splits episodes into phases (reach, grasp, place) with PELT changepoint detection on proprioception. ```bash forge segment hf://lerobot/droid_100 --export segments.json --plot timeline.png ``` -Tokenize — turn continuous actions into discrete tokens for VLA training; benchmark strategies on *your* data. +**Tokenize** turns continuous actions into discrete tokens for VLA training, and benchmarks strategies on *your* data. Built-ins: `uniform-bins` (RT-1), `openvla-bins`, `quantile-bins`, `mu-law`. ```bash -forge tokenize compare ./my_dataset --sample 20 # recon error / vocab util +forge tokenize compare ./my_dataset --sample 20 # reconstruction error, vocab use forge tokenize write ./my_dataset ./tokenized --strategy openvla-bins ``` -Built-ins: `uniform-bins` (RT-1), `openvla-bins`, `quantile-bins`, `mu-law`. - -Visualize — three backends: browser (default), matplotlib, and [Rerun](https://rerun.io) (cameras + time-series on one timeline). +**Visualize** in the browser (default, no install), matplotlib, OpenCV or [Rerun](https://rerun.io) (cameras and time series on one timeline). ```bash -forge visualize pusht # web (no install) +forge visualize pusht forge visualize pusht --backend rerun --segment ``` -![Rerun viewer showing camera stream alongside action and state time series](docs/assets/rerun_viz.png) +![Rerun viewer showing a camera stream alongside action and state time series](docs/assets/rerun_viz.png) Details: [segment](forge/segment/README.md) · [tokenize](forge/tokenize/README.md). @@ -193,29 +176,28 @@ Details: [segment](forge/segment/README.md) · [tokenize](forge/tokenize/README. # The data engine -The toolkit works one dataset at a time. The **catalog** turns Forge into a *system of record*: an append-only set of Parquet tables that registers every episode you ingest and annotates it with quality, embeddings, and curation decisions — all queryable with SQL. It's **zero-server** (Parquet + embedded DuckDB), lives on a **local dir or an `s3://` / `gs://` bucket**, and is readable by pandas / Polars / Spark without Forge. +

+Datasets from local disk, hf:// and cloud buckets flow through ingest, quality, embed, search, dedup and curate; each stage appends to a catalog table (episodes, quality_scores, embeddings, dedup_edges, curation_labels), and Studio reads the catalog +

-``` -ingest ──▶ query ──▶ embed ──▶ search ──▶ dedup ──▶ curate ──▶ Studio - (snapshot → soon) -``` +The toolkit works on one dataset. The **catalog** makes forge a system of record: append-only Parquet tables that register every episode you ingest and annotate it with quality, embeddings and curation decisions, all queryable with SQL. There is no server (Parquet plus embedded DuckDB), it lives in a local directory or an `s3://` / `gs://` bucket, and pandas, Polars or Spark can read it without forge. ```bash pip install "forge-robotics[catalog]" # + [embed] for search, [video] for Studio thumbnails ``` -## 1. Ingest & query +### 1. Ingest and query ```bash -forge catalog init ./forge-catalog # local dir or cloud bucket -forge ingest ./my_dataset -c ./forge-catalog # register + quality-score each episode -forge ingest s3://lab-bucket/raw/2026-07-18/ -c ./forge-catalog # re-runs are a no-op (content hash) +forge catalog init ./forge-catalog # local dir or cloud bucket +forge ingest ./my_dataset -c ./forge-catalog # register + score each episode +forge ingest s3://lab-bucket/raw/2026-07-18/ -c ./forge-catalog # re-runs are a no-op (content hash) forge query "SELECT task, count(*) FROM episodes GROUP BY task" -c ./forge-catalog forge catalog stats -c ./forge-catalog ``` -Ingestion reuses the same readers as `forge inspect` and the same scorer as `forge quality`, so the catalog stays consistent with the toolkit. Writes go through pyarrow; reads through DuckDB (views: `episodes`, `quality_scores`, `v_latest_quality`). +Ingest reuses the readers behind `forge inspect` and the scorer behind `forge quality`, so the catalog agrees with the toolkit. Views: `episodes`, `quality_scores`, `v_latest_quality`, `v_curation`. ```python from forge.catalog import Catalog @@ -227,58 +209,68 @@ df = cat.sql("SELECT robot, avg(overall_score) FROM episodes " "JOIN v_latest_quality USING(episode_id) GROUP BY robot").to_pandas() ``` -## 2. Search semantically +### 2. Search in natural language -Embed episodes with [SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384) (a shared image–text model), then search by natural language — text queries match episode *video*, not just metadata. +Embed episodes with [SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384), a shared image–text model, so text queries match what happens in the *video*, not just the metadata. ```bash -pip install "forge-robotics[embed]" - -forge embed -c ./forge-catalog # GPU auto: CUDA → Apple MPS → CPU +forge embed -c ./forge-catalog # CUDA → Apple MPS → CPU forge search "picks up the red cup" -c ./forge-catalog --top 10 -forge search --like -c ./forge-catalog # visually-similar episodes +forge search --like -c ./forge-catalog # visually similar episodes ``` -Vectors are versioned per model (`siglip-so400m@`) and stored in the catalog. Details: [forge/embed/README.md](forge/embed/README.md). +Vectors are versioned per model (`siglip-so400m@`). Details: [forge/embed/README.md](forge/embed/README.md). -## 3. Dedup & curate +### 3. Dedup and curate -Find near-duplicate episodes across the whole corpus (cosine over embeddings), then curate a clean, labeled training set. Near-dup pairs are recorded as **facts**; which episode wins is decided by **policy** at curation time. +Near-duplicate pairs across the whole corpus are stored as **facts**; which episode wins is a **policy** applied at curation time. Curation is an append log (latest label wins), so nothing is ever deleted. ```bash -forge catalog dedup -c ./forge-catalog --threshold 0.97 # store near-dup pairs (dedup_edges) +forge catalog dedup -c ./forge-catalog --threshold 0.97 forge curate -c ./forge-catalog \ --where "overall_score > 6 AND task = 'pick_place'" \ --dedup 0.97 --dedup-policy keep-higher-quality --label approved -``` - -Curation isn't only SQL-driven — **semantic search and visual review can drive it too**. Save a search result (or Studio's keep/reject decisions) to a selection file and label it, provenance included: -```bash forge search "regrasp after a failed pick" -c ./forge-catalog --top 20 --save sel.json -forge curate -c ./forge-catalog --from sel.json --label approved # or --ids e1,e2,e3 +forge curate -c ./forge-catalog --from sel.json --label approved ``` -Curation is an append-log (`curation_labels`, latest-wins) — nothing is deleted. Policies: `keep-higher-quality`, `keep-longer`, `keep-first`. +Policies: `keep-higher-quality`, `keep-longer`, `keep-first`. -## 4. Forge Studio +### 4. Studio -A self-contained, themed HTML app to explore the catalog — **Overview · Corpus** (thumbnails + quality rings) **· Dedup review** (keep/reject pairs) **· Snapshot**. One shareable file, no server; real data and video thumbnails embedded. +One self-contained HTML file to explore the catalog: overview, corpus (thumbnails and quality rings), dedup review (keep or reject pairs) and snapshot. No server; share it like any file. ```bash forge studio -c ./forge-catalog -o studio.html && open studio.html ``` -Details, storage layout, and commit protocol: [forge/catalog/README.md](forge/catalog/README.md). A ready-to-explore [example catalog](forge/catalog/catalog_example_droid_100/) (droid_100) ships in the repo. +Storage layout and commit protocol: [forge/catalog/README.md](forge/catalog/README.md). An [example catalog](forge/catalog/catalog_example_droid_100/) built from droid_100 ships in the repo. --- # Reference -## Cloud storage (S3 & GCS) +## Supported formats + +| Format | Read | Write | Notes | +|---|:-:|:-:|---| +| LeRobot v3 | ✓ | ✓ | Hugging Face, Parquet + MP4 | +| LeRobot v2 | ✓ | – | Read only; convert to v3 to write | +| RLDS | ✓ | ✓ | Open-X, TensorFlow Datasets | +| MCAP | ✓ | ✓ | ROS 2 CDR + Foxglove Protobuf, no ROS install needed | +| RoboDM | ✓ | ✓ | Berkeley `.vla` (manual install) | +| GR00T | ✓ | – | NVIDIA Isaac, LeRobot v2 + embodiment metadata | +| HDF5 | ✓ | – | robomimic, ACT / ALOHA | +| Zarr | ✓ | – | Diffusion Policy, UMI | +| Rosbag | ✓ | – | ROS 1 `.bag`, ROS 2 SQLite3 (images only today, see below) | + +Which models use which format: [docs/model_formats.md](docs/model_formats.md). Format specs: [docs/format_reference.md](docs/format_reference.md). -Every command that takes a dataset or catalog path also accepts `s3://` and `gs://` URIs. Cloud datasets are downloaded to a temp dir on first access and cleaned up automatically, so every format works exactly as it does locally. +## Cloud storage + +Any dataset or catalog path can be an `s3://` or `gs://` URI. Auth uses each provider's standard credential chain; forge never handles credentials. ```bash pip install "forge-robotics[s3]" # or [gcs] @@ -286,59 +278,59 @@ forge inspect s3://my-bucket/datasets/run_0413 forge convert gs://lab-data/rosbags ./out --format lerobot-v3 ``` -**Streaming reads.** For **LeRobot-v3** and **Zarr**, `forge inspect` and `forge ingest` read over the network with **range requests** instead of downloading. Inspecting a 464 MB cloud LeRobot dataset fetches ~3 KB (its `info.json`); **ingesting it — register + quality-score every episode — reads only the proprio parquet columns (~3 MB), never the videos.** `forge inspect --deep` forces a full download when you need per-episode stats; embeddings/video quality still fetch frames. - -Auth uses each provider's standard credential chain (AWS env vars / profiles / IAM roles; GCP Application Default Credentials) — Forge never handles credentials itself. Catalogs can be read *and written* in the cloud; per-format conversion **outputs** are local-only for now. Full guide + connectivity troubleshooting: [forge/io/README.md](forge/io/README.md). +For **LeRobot v3** and **Zarr**, `inspect` and `ingest` stream with range requests instead of downloading. Inspecting a 464 MB cloud dataset fetches about 3 KB; ingesting it reads only the proprio columns (about 3 MB), never the videos. Other formats are downloaded to a temp dir and cleaned up. Conversion outputs are local only for now. Guide: [forge/io/README.md](forge/io/README.md). ## Dataset registry -A curated catalog of 23+ prominent robotics datasets — browse and use by name instead of memorizing URIs. **[Browse online](https://arpitg1304.github.io/forge/registry.html)** +23+ well-known robotics datasets, usable by name. **[Browse online](https://arpitg1304.github.io/forge/registry.html)** ```bash -forge registry list --format rlds --embodiment franka # filter +forge registry list --format rlds --embodiment franka forge registry search "franka manipulation" forge inspect droid # ids work in any command -forge demo # download + inspect + score a demo +forge demo # download, inspect and score a demo ``` -Add datasets via [forge/registry/CONTRIBUTING.md](forge/registry/CONTRIBUTING.md). - -## Supported formats - -| Format | Read | Write | Notes | -|--------|:----:|:-----:|-------| -| RLDS | ✓ | ✓ | Open-X, TensorFlow Datasets | -| LeRobot v2/v3 | ✓ | ✓ | HuggingFace, Parquet + MP4 | -| GR00T | ✓ | – | NVIDIA Isaac, LeRobot v2 + embodiment metadata | -| RoboDM | ✓ | ✓ | Berkeley `.vla`, up to 70× compression (manual install) | -| Zarr | ✓ | – | Diffusion Policy, UMI | -| HDF5 | ✓ | – | robomimic, ACT/ALOHA | -| MCAP | ✓ | ✓ | ROS2 CDR + Foxglove Protobuf, no ROS install required | -| Rosbag | ✓ | – | ROS1 `.bag`, ROS2 SQLite3 | +To add a dataset, see [forge/registry/CONTRIBUTING.md](forge/registry/CONTRIBUTING.md). -Which models use which format: [docs/model_formats.md](docs/model_formats.md) · format specs: [docs/format_reference.md](docs/format_reference.md). +## Commands -## Command cheatsheet +| | | +|---|---| +| **Toolkit** | `inspect` · `convert` · `quality` · `lint` · `filter` · `dedup` · `segment` · `tokenize` · `visualize` · `stats` · `export-video` | +| **Data engine** | `catalog init` · `ingest` · `query` · `catalog stats` · `embed` · `search` · `catalog dedup` · `curate` · `studio` | +| **Discovery** | `hub` · `local` · `registry` · `demo` · `formats` · `version` | -**Toolkit** (per dataset): `inspect` · `convert` · `quality` · `lint` · `filter` · `dedup` · `segment` · `tokenize` · `visualize` · `stats` · `export-video` +Full reference: [docs/cli.md](docs/cli.md), or `forge --help`. -**Data engine** (per catalog): `catalog init` · `ingest` · `query` · `catalog stats` · `embed` · `search` · `catalog dedup` · `curate` · `studio` +## Known limitations -**Discovery**: `hub` · `local` · `registry` · `demo` · `formats` · `version` +Forge is honest about what it does not do yet. These are tracked and being fixed: -Full reference: [docs/cli.md](docs/cli.md). Run `forge --help` for any command. +- **Rosbag** conversion reads image topics only and yields the whole bag as one episode; state and action are not filled yet, even though `inspect` lists those topics. +- **YAML conversion configs** apply `writer_config:` and `cameras:` only. `fields:`, `video:`, `include_depth` and `transform` are parsed but not applied yet. +- **LeRobot v3 writer** writes `names: null` for features, uses the task `"default"` when an episode has no language instruction, and creates one chunk per episode. +- **`--sample` and `--quick`** take the *first* N episodes, not a random subset. +- **`filter` without `--from-report`** re-scores with a reduced config (gripper dims, FPS, bounds only). Pass `--from-report` to filter on the scores you reviewed. +- **Zarr** has no FPS metadata, so it defaults to 30 Hz. Pass `--fps` (Push-T is 10 Hz). +- **`--visualize`** blocks until Ctrl+C, so avoid it in scripts. +- **RLDS:** episode-level language only (Open-X often stores it per step), and the writer emits flat `tf.train.Example` records rather than nested RLDS. +- **LeRobot v2 videos:** a frame that can't be decoded is replaced by a black frame, now with a warning in the log. ## Roadmap -- [x] Dataset registry — curated catalog of 23+ datasets with CLI + HTML browser -- [x] MCAP first-class support — read + write, ROS2 CDR + Foxglove, no ROS install -- [x] Episode filtering, quality scoring, linting, segmentation, tokenization -- [x] Cloud storage — `s3://` / `gs://` on every command -- [x] The catalog — ingest, SQL query, semantic search, dedup, curation, Studio -- [ ] **Snapshots + export** — freeze a curated selection → LeRobot/RLDS for training -- [~] **Streaming reads** — `forge inspect` + `forge ingest` stream LeRobot-v3 / Zarr (metadata + proprio via range reads, no video download); frame/embedding streaming next -- [ ] **Dataset merging & splitting** — combine datasets; stratified train/val/test -- [ ] **Depth / point-cloud support** · **GR00T writer** · **distributed conversion** +- [x] Format toolkit: convert, inspect, quality, lint, filter, dedup, segment, tokenize, visualize +- [x] MCAP read + write without a ROS install · cloud storage on every command · dataset registry +- [x] The catalog: ingest, SQL, semantic search, dedup, curation, Studio +- [~] Streaming reads: LeRobot v3 and Zarr metadata + proprio today; frames and embeddings next +- [ ] Close the gaps above, starting with rosbag state/action and YAML field mappings +- [ ] Trim idle starts and ends on write (`convert --trim-idle`) +- [ ] q01 / q99 quantiles in LeRobot v3 `stats.json` (needed by π0.5-style training) +- [ ] Train / val / test split by episode or session +- [ ] Snapshots + export: a curated catalog selection → LeRobot / RLDS for training +- [ ] `forge push` to the Hugging Face Hub +- [ ] Episode-length outliers, failed-take detection, action-to-state lag, camera drift +- [ ] Depth and point clouds · GR00T writer · distributed conversion ## Development @@ -348,7 +340,7 @@ make install-dev make test ``` -Contributions welcome. See [docs/architecture.md](docs/architecture.md) for the design. +Contributions welcome. Start with [docs/architecture.md](docs/architecture.md). ## License diff --git a/ROADMAP.md b/ROADMAP.md deleted file mode 100644 index 59cf593..0000000 --- a/ROADMAP.md +++ /dev/null @@ -1,177 +0,0 @@ -# Forge Roadmap - -## Current Status (v0.1) - -### Supported Formats -| Format | Read | Write | Notes | -|--------|------|-------|-------| -| RLDS | ✅ | ✅ | Open X-Embodiment, OpenVLA, Octo | -| LeRobot v2 | ✅ | - | HuggingFace robotics | -| LeRobot v3 | ✅ | ✅ | Target format for all conversions | -| Zarr | ✅ | - | Diffusion Policy datasets | -| HDF5 | ✅ | - | robomimic, ACT/ALOHA datasets | -| MCAP | ✅ | ✅ | ROS2 CDR + Foxglove Protobuf, no ROS install required | -| ROS bags | ✅ | - | ROS1 .bag, ROS2 SQLite3 | - -### Core Features -- [x] Format auto-detection -- [x] CLI (`forge inspect`, `convert`, `visualize`, `formats`, `hub`) -- [x] YAML configuration files -- [x] Parallel episode processing (`--workers N`) -- [x] Unified visualizer -- [x] HuggingFace Hub integration (`hf://` URLs) - ---- - -## Completed (v0.1.1) - -### ✅ HuggingFace Hub Integration -**Status:** Done - -```bash -# Download and inspect -forge inspect hf://lerobot/pusht - -# Download and convert -forge convert hf://openvla/modified_libero_rlds output/ --format lerobot-v3 - -# Search datasets -forge hub "robot manipulation" -forge hub --author lerobot -``` - -Features: -- [x] `hf://` URL scheme for HuggingFace datasets -- [x] Automatic download and caching (`~/.cache/forge/datasets/`) -- [x] Dataset search/discovery (`forge hub` command) -- [ ] Streaming support for large datasets (future) - ---- - -## Completed (v0.2) - -### ✅ RLDS Writer -**Status:** Done - -```bash -# Convert LeRobot to RLDS -forge convert lerobot_dataset/ output/ --format rlds - -# Round-trip conversion (RLDS → LeRobot v3 → RLDS) -forge convert original_rlds/ temp/ --format lerobot-v3 -forge convert temp/ reconverted_rlds/ --format rlds -``` - -Features: -- [x] Write RLDS format (TFRecord) -- [x] Generate proper episode metadata (dataset_info.json, features.json) -- [x] Support OXE-compatible schema -- [x] Round-trip conversion verified - -### ✅ Action Tokenization -**Status:** Done - -```bash -forge tokenize compare ./dataset --export report.json -forge tokenize write ./dataset ./tokenized --strategy openvla-bins -``` - -Features: -- [x] `ActionTokenizer` protocol + `TokenizerRegistry` (one-decorator extension) -- [x] Built-in per-step strategies: `uniform-bins`, `openvla-bins`, `quantile-bins`, `mu-law` (numpy-only) -- [x] `TokenizerComparator` — reconstruction error / tokens-per-step / vocab utilization -- [x] Tokenized LeRobot v3 writer (`action_tokens` column) + saved tokenizer for inference decode -- [ ] FAST (DCT+BPE) and k-means (BeT) strategies — dependency-gated stretch -- [ ] Chunk-granularity dataset writer (per-step only in v1) -- [ ] Parallel write path (sequential in v1) - ---- - -## High Priority (v0.3) - -### 1. Validation Tools -**Why:** Ensure converted datasets are correct and complete. - -```bash -forge validate output/ --check-frames --check-videos -``` - -- [ ] Frame count validation -- [ ] Video integrity checks -- [ ] Schema compatibility checks -- [ ] Compare source vs converted statistics - ---- - -## Medium Priority (v0.3) - -### 4. Additional Formats - -#### DROID Dataset -- Large-scale bimanual manipulation dataset -- Already converted to LeRobot: `IPEC-COMMUNITY/droid_lerobot` - -#### BridgeData V2 -- 60k+ trajectories from WidowX robots -- Core component of Octo training - -#### LIBERO -- Simulation benchmark used by OpenVLA and Pi0 -- Pre-converted versions exist on HF Hub - -### 5. Streaming & Large Dataset Support -- [ ] Lazy loading for datasets > RAM -- [ ] Chunked processing -- [ ] Resume interrupted conversions - -### ✅ Statistics & Analysis -```bash -forge stats dataset/ --plot -forge stats dataset/ --sample 100 --output stats.json -``` -- [x] Action/state distributions (min, max, mean, std per dimension) -- [x] Episode length histograms -- [x] Coverage metrics (language, success labels, rewards) -- [x] JSON export for programmatic access -- [x] Matplotlib visualization with --plot flag - ---- - -## Low Priority (v0.4+) - -### 7. HuggingFace Upload -```bash -forge upload output/ --repo my-org/my-dataset -``` - -### 8. Data Augmentation -- [ ] Image augmentations during conversion -- [ ] Action noise injection -- [ ] Temporal subsampling - -### 9. Format Converters -- [x] HDF5 reader (robomimic, ACT/ALOHA) ✅ Done -- [ ] MuJoCo dataset support -- [ ] Isaac Gym recordings - ---- - -## VLA Model Compatibility Matrix - -| Model | Training Format | Fine-tune Format | Forge Support | -|-------|----------------|------------------|---------------| -| OpenVLA | RLDS | RLDS | ✅ Read | -| Octo | RLDS | RLDS | ✅ Read | -| Pi0/OpenPI | Proprietary | LeRobot v2 | ✅ Read/Write | -| ACT | HDF5 | HDF5 | ✅ Read | -| Diffusion Policy | Zarr | Zarr | ✅ Read | - ---- - -## References - -- [Open X-Embodiment](https://github.com/google-deepmind/open_x_embodiment) - 1M+ trajectories, RLDS format -- [OpenVLA](https://github.com/openvla/openvla) - Uses RLDS, fine-tunes on RLDS -- [Octo](https://github.com/octo-models/octo) - Uses RLDS from OXE -- [OpenPI (Pi0)](https://github.com/Physical-Intelligence/openpi) - Uses LeRobot for fine-tuning -- [LeRobot](https://github.com/huggingface/lerobot) - HuggingFace robotics standard diff --git a/docs/assets/readme/engine.svg b/docs/assets/readme/engine.svg new file mode 100644 index 0000000..cfbcb2d --- /dev/null +++ b/docs/assets/readme/engine.svg @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + +forge://catalog +zero-server · append-only Parquet + DuckDB · local or s3:// / gs:// +datasets +./local +hf:// +s3:// gs:// + + +catalog +ingest + + +episodes +quality + + +quality_scores +embed + + +embeddings +search + + +↑ reads +dedup + + +dedup_edges +curate + + +curation_labels +$ forge query "SELECT task, count(*) FROM episodes GROUP BY task" + + +studio + + + + + + + + + + +export totraining · soon + + diff --git a/docs/assets/readme/hero.svg b/docs/assets/readme/hero.svg new file mode 100644 index 0000000..2e8a92b --- /dev/null +++ b/docs/assets/readme/hero.svg @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + +forge://hub +add a reader, get every writer · O(n), not O(n²) +read +write + + + + + + + + + + + + +RLDS +LeRobot v2/v3 +GR00T +HDF5 +Zarr +MCAP +rosbag +RoboDM +LeRobot v3 +RLDS +MCAP +RoboDM + + + + + + + + + + + + + + +Episode / Frame + + + + + + + + + + + + + + + + + + + + + + + + + +inspect + +quality + +lint + +filter + +segment + +tokenize + +visualize +local · hf:// · s3:// · gs:// + + diff --git a/docs/assets/readme/quality.svg b/docs/assets/readme/quality.svg new file mode 100644 index 0000000..1a59eb2 --- /dev/null +++ b/docs/assets/readme/quality.svg @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + +forge://quality +flags are review candidates, not failure labels +camera +state +gripper +time + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +motion pause +gripper chatter +timestamp gap +frozen camera + + + + +6.4 +heuristic / 10 +ep_0007 · 4 flags +→ review + + diff --git a/docs/cli.md b/docs/cli.md index e128076..781ddc2 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -99,8 +99,10 @@ forge visualize /path/to/dataset --backend opencv ``` **Backends:** -- `matplotlib` (default) - Interactive with sliders, slower playback +- `web` (default) - Browser viewer, no extra install +- `matplotlib` - Interactive with sliders, slower playback - `opencv` - Fast video playback, keyboard controls +- `rerun` - Cameras and time series on one timeline (`pip install "forge-robotics[rerun]"`) **Matplotlib controls:** - Episode slider: Navigate between episodes @@ -132,13 +134,13 @@ forge quality /path/to/dataset --gripper-dim 6 --fps 30 forge quality /path/to/dataset --export report.json forge quality /path/to/dataset --export-flagged flagged.json -# Quick mode (skip expensive metrics) +# Quick mode (scores the first 50 episodes) forge quality /path/to/dataset --quick # Known action bounds (tighter saturation detection) forge quality /path/to/dataset --action-bounds -1.0,1.0 -# Sample subset +# Score only the first 50 episodes (not a random sample) forge quality /path/to/dataset --sample 50 ``` @@ -226,7 +228,7 @@ forge segment /path/to/dataset --penalty aic --min-segment-length 15 - `--cost-model`: Cost function for segment homogeneity (`rbf`, `l2`, `l1`, `normal`, `ar`) - `--min-segment-length`: Minimum segment length in frames (default: 10) - `--normalize / --no-normalize`: Z-score normalize per dimension (default: enabled) -- `--sample`: Analyze a random subset of episodes +- `--sample`: Analyze the first N episodes (not a random sample) - `--export`: Save JSON report with per-episode segmentation results - `--plot`: Generate a timeline PNG visualization - `--format`: Format hint for dataset loading @@ -324,7 +326,7 @@ forge hub --author berkeley-humanoid forge hub --download lerobot/pusht ``` -Downloaded datasets are cached in `~/.cache/forge/datasets/`. +Downloads use the standard Hugging Face Hub cache (`~/.cache/huggingface/hub/`, honouring `HF_HOME` / `HF_HUB_CACHE`), so they are shared with other HF tools. Set `FORGE_CACHE_DIR` to use `$FORGE_CACHE_DIR/datasets/` instead. --- @@ -354,7 +356,7 @@ forge version | Variable | Description | Default | |----------|-------------|---------| -| `FORGE_CACHE_DIR` | Dataset cache location | `~/.cache/forge` | +| `FORGE_CACHE_DIR` | Override the dataset cache (`$FORGE_CACHE_DIR/datasets`) | unset: Hugging Face Hub cache | | `FORGE_LOG_LEVEL` | Logging verbosity | `INFO` | --- @@ -367,11 +369,11 @@ forge version # Download from HuggingFace forge hub --download openvla/droid_100 -# Inspect to understand structure -forge inspect ~/.cache/forge/datasets/openvla/droid_100 +# Inspect to understand structure (hf:// paths resolve to the local cache) +forge inspect hf://openvla/droid_100 # Convert to LeRobot v3 -forge convert ~/.cache/forge/datasets/openvla/droid_100 \ +forge convert hf://openvla/droid_100 \ ./droid_lerobot \ --format lerobot-v3 \ --workers 4 diff --git a/docs/index.html b/docs/index.html index 84c3dca..5e661ec 100644 --- a/docs/index.html +++ b/docs/index.html @@ -771,7 +771,7 @@

Everything you need for a single dataset

Dataset Inspection
Auto-detect format, list episodes, cameras, action/state dimensions, FPS, and schema. Works with local paths and HuggingFace URIs.
- $ forge inspect hf://lerobot/aloha_sim_cube + $ forge inspect aloha_sim_transfer_cube
@@ -781,9 +781,9 @@

Everything you need for a single dataset

Quality Scoring
-
Score every episode 0-10 with 8 research-backed metrics. Detect jerky demos, dead actions, gripper chatter, and idle periods from proprioception alone.
+
Score every episode 0-10 with Inspectable quality metrics. Detect jerky demos, dead actions, gripper chatter, and idle periods from proprioception alone.
- $ forge quality ./my_dataset --export report.json + $ forge quality ./my_dataset --visualize --export report.json
@@ -867,7 +867,7 @@

Everything you need for a single dataset

Action Tokenization
Turn continuous actions into the discrete tokens VLA models train on. Four built-in strategies (RT-1, OpenVLA, quantile, mu-law) and a comparator that benchmarks them on your data — measure, don't guess.
- $ forge tokenize compare ./my_dataset --export report.json + $ forge tokenize compare ./my_dataset --visualize --export report.json
@@ -1410,8 +1410,8 @@

Format support matrix

-

8 research-backed metrics

-

Score every episode 0-10 from proprioception data alone. No video processing needed.

+

Inspectable quality metrics

+

Measure motion and timing from proprioception. Scores are heuristic; unavailable results remain unscored.

@@ -1425,19 +1425,19 @@

8 research-backed metrics

-
Gripper Chatter
Rapid open/close cycles
+
Gripper Chatter
Explicit gripper channels
-
Static Detection
Idle period detection
+
Static Detection
Sustained low measured speed
-
Timestamp Regularity
Dropped frames & jitter
+
Timestamp Regularity
Observation gaps & jitter
-
Action Saturation
Time at hardware limits
+
Action Saturation
Requires supplied limits
@@ -1445,14 +1445,14 @@

8 research-backed metrics

-
Path Length
Wandering & hesitation
+
Path Length
Measured position travel
- $ forge quality hf://lerobot/aloha_sim_cube --export report.json
- $ forge filter ./dataset ./filtered --min-quality 6.0 # remove bad demos + $ forge quality aloha_sim_transfer_cube --visualize --export report.json
+ $ forge filter ./dataset ./filtered --min-quality 6.0 # apply a calibrated threshold
diff --git a/docs/reports/.gitignore b/docs/reports/.gitignore new file mode 100644 index 0000000..b3c2ebd --- /dev/null +++ b/docs/reports/.gitignore @@ -0,0 +1,3 @@ +quality_survey_oct_2026/ +video_quality_benchmark_oct_2026.json +proprio_quality_validation_oct_2026.md diff --git a/docs/reports/README.md b/docs/reports/README.md new file mode 100644 index 0000000..2510fb3 --- /dev/null +++ b/docs/reports/README.md @@ -0,0 +1,60 @@ +# Quality validation and benchmarks + +## PR validation — October 17, 2026 + +- 264 tests passed across quality, video, viewer handoff, filters, catalog, video caching, and LeRobot round-trip/upstream compatibility. +- 7 streaming tests passed, including the local mock S3 server. +- 1 Chrome integration test passed for playback, event navigation, camera filtering, plots, and mobile layout. +- The broader CLI suite passed 16 tests. Two existing Zarr fixture setup errors require an explicit `shape` in `create_dataset`; they occur before command execution. +- Ruff passed on the quality implementation, viewer, reader, filter engine, new tests, and the benchmark script. Existing lint issues elsewhere in the CLI and older tests remain. +- `git diff --check` passed. + +The quality CI job covers the core quality, viewer backend, reader, filter, and +catalog tests on Python 3.10–3.12. Browser and upstream LeRobot tests need optional +local dependencies. This is regression coverage, not measured detection accuracy. + +Run the browser check with: + +```bash +FORGE_TEST_CHROME=/path/to/chrome pytest tests/test_web_viewer_browser.py --no-cov +``` + +## Video CPU benchmark + +Local benchmark measurements use an Apple M5 Pro +with 18 CPU cores and 64 GiB RAM. The fixture contains 300 DROID frames resized +to 1280×720 and encoded as H.264. Pixel checks use a 128-pixel longest side; +optical flow uses 64 pixels. Every frame is analyzed. + +| Pipeline | Median milliseconds/frame | Frames/second | +|---|---:|---:| +| Forge decode + pixel checks | 1.93 | 519 | +| Forge decode + pixel and motion checks | 3.11 | 321 | + +Results are medians of five warm runs. Timings include file opening, decoding, +RGB conversion, metrics, integrity checks, and event aggregation. They exclude +fixture creation, imports, downloads, dataset indexing, proprioception, and UI. + +Estimated processing time for one camera, using measured throughput: + +| Input FPS | Video duration | Pixel checks | Pixel + motion | +|---|---|---:|---:| +| 20 | 10 seconds | 0.39 s | 0.62 s | +| 20 | 30 seconds | 1.16 s | 1.87 s | +| 20 | 60 seconds | 2.31 s | 3.73 s | +| 30 | 10 seconds | 0.58 s | 0.93 s | +| 30 | 30 seconds | 1.73 s | 2.80 s | +| 30 | 60 seconds | 3.47 s | 5.60 s | + +Longer durations are linear estimates, not separately measured runs. Codec, +scene, hardware, and camera count affect throughput. No GPU was used. Generated JSON and video files are kept locally, outside Git. + +Reproduce with a local source video: + +```bash +PYTHONPATH=. python scripts/benchmark_video_quality.py SOURCE.mp4 \ + --output /tmp/forge-video-benchmark/results.json +``` + +See the [quality guide](../../forge/quality/README.md) and +[video guide](../../forge/quality/video/README.md) for current semantics. diff --git a/examples/test_config.yaml b/examples/test_config.yaml deleted file mode 100644 index 151fb20..0000000 --- a/examples/test_config.yaml +++ /dev/null @@ -1,30 +0,0 @@ -# Forge conversion configuration -# Generated from: sample_data/robomimic_ph/can_ph_image/1.0.1 -# Source format: rlds - -# Target format for conversion -target_format: lerobot-v3 - -# fps: 30 # Specify FPS (required if not in source) -# robot_type: franka # Specify robot type - -# Camera name mapping (source → target) -# Modify target names as needed for your use case -cameras: - robot0_eye_in_hand_image: robot0_eye_in_hand_image - agentview_image: agentview_image - -# Field mapping (source → target) -# Uncomment and modify as needed -fields: - # action: steps/action # Specify action field path - # state: observation/robot_state # Specify state field path - -# Video encoding settings (optional) -# video: -# codec: h264 -# crf: 23 # Quality (lower = better, 18-28 typical) - -# Behavior settings -fail_on_error: false -skip_existing: true diff --git a/forge/__init__.py b/forge/__init__.py index 4014f67..5461814 100644 --- a/forge/__init__.py +++ b/forge/__init__.py @@ -69,7 +69,7 @@ load_tokenizer, ) -__version__ = "0.1.0" +__version__ = "0.2.0" __all__ = [ # Version diff --git a/forge/catalog/README.md b/forge/catalog/README.md index adcd810..312dd4b 100644 --- a/forge/catalog/README.md +++ b/forge/catalog/README.md @@ -165,3 +165,12 @@ Snapshots + training-set export (Phase 4: `forge snapshot create/materialize`); frame/segment-level embeddings and Lance/ANN for >100k episodes (Phase 5); distributed execution, locking, compaction, and gc. The manifest convention is in place so gc becomes possible later, but it is not implemented. + +## Quality scorer compatibility + +New scores use `q-v2-proprio`. Gripper channels and physical command limits are +explicit, and unsupported motion can leave `overall_score` null. Existing rows +remain available with their original scorer version. Recompute quality reports +and recalibrate thresholds before comparing old and new results. Re-ingesting +an unchanged episode does not automatically refresh its catalog score. Detailed +quality events are stored in report exports; see the [quality guide](../quality/README.md). diff --git a/forge/catalog/schema.py b/forge/catalog/schema.py index 652035b..02cb869 100644 --- a/forge/catalog/schema.py +++ b/forge/catalog/schema.py @@ -23,10 +23,9 @@ # `dedup_edges` and `curation_labels`. SCHEMA_VERSION = 3 -# Version tag stamped on every quality_scores row. The quality module has no -# version of its own today, so the catalog owns this constant. Bump it when the -# scoring math changes so old scores remain distinguishable and reproducible. -SCORER_VERSION = "q-v1" +# Version tag stamped on every quality_scores row. Keep this aligned with +# EpisodeQuality.scorer_version when scoring semantics change. +SCORER_VERSION = "q-v2-proprio" # Names of the per-episode quality metrics, mirrored EXACTLY from the flat dict # produced by forge.quality.models.EpisodeQuality.to_dict(). Kept as a list so diff --git a/forge/cli.py b/forge/cli.py index b0f0487..3d75ab7 100644 --- a/forge/cli.py +++ b/forge/cli.py @@ -1123,7 +1123,7 @@ def stats_cmd( output: Path | None = typer.Option(None, "--output", "-o", help="Save stats to JSON file"), sample: int = typer.Option(0, "--sample", "-s", help="Sample N episodes (0 = all)"), quality: bool = typer.Option(False, "--quality", "-q", help="Include quality metrics"), - gripper_dim: int = typer.Option(-1, "--gripper-dim", help="Gripper action dimension index"), + gripper_dim: int | None = typer.Option(None, "--gripper-dim", help="Gripper action dimension index"), fps: float = typer.Option(30.0, "--fps", help="Recording FPS (fallback if no timestamps)"), ) -> None: """Compute and display dataset statistics. @@ -1337,7 +1337,8 @@ def stats_cmd( report = analyzer.analyze_dataset(resolved_path, sample=sample) - console.print(f" Overall Quality Score: [bold]{report.overall_score:.1f}[/bold] / 10") + score_label = f"{report.overall_score:.1f} / 10" if report.overall_score is not None else "N/A" + console.print(f" Heuristic Quality Score: [bold]{score_label}[/bold]") console.print() for key, val in report.subscores.items(): @@ -1932,7 +1933,18 @@ def local_cmd( @app.command("quality") def quality_cmd( path: str = typer.Argument(..., help="Path to dataset (local or hf://org/repo)"), - gripper_dim: int = typer.Option(-1, "--gripper-dim", "-g", help="Gripper dimension index (-1 = last)"), + gripper_dim: int | None = typer.Option(None, "--gripper-dim", "-g", help="Gripper dimension index (-1 = last)"), + gripper_dims: str | None = typer.Option(None, "--gripper-dims", help="Comma-separated gripper action columns, e.g. 6,13; omit for no gripper scoring"), + action_semantics: str = typer.Option("unknown", "--action-semantics", help="unknown, position, velocity, or delta"), + tracking_pairs: str | None = typer.Option(None, "--tracking-pairs", help="Absolute-position action:state column pairs, e.g. 0:0,1:1; compatible units required"), + state_dims: str | None = typer.Option(None, "--state-dims", help="Position-state columns for motion diagnostics"), + state_scales: str | None = typer.Option(None, "--state-scales", help="Positive scale per original state column"), + pause_speed: float = typer.Option(0.001, "--pause-speed", help="Pause threshold in scaled position units/second"), + event_min_duration: float = typer.Option(0.5, "--event-min-duration", help="Minimum pause/hold/stall duration in seconds"), + tracking_error: float = typer.Option(0.05, "--tracking-error", help="Position mismatch threshold in scaled state units"), + tracking_lag: float = typer.Option(0.0, "--tracking-lag", help="Command-to-state latency in seconds"), + visualize: bool = typer.Option(False, "--visualize", help="Open web playback with quality-event timelines after scoring"), + fps: float = typer.Option(30.0, "--fps", "-f", help="Fallback FPS if timestamps unavailable"), sample: int = typer.Option(0, "--sample", "-s", help="Analyze N episodes (0 = all)"), export: Path | None = typer.Option(None, "--export", "-e", help="Export full report to JSON"), @@ -1940,12 +1952,17 @@ def quality_cmd( quick: bool = typer.Option(False, "--quick", "-q", help="Quick mode (sample 50 episodes)"), action_bounds: str | None = typer.Option(None, "--action-bounds", help="Known action bounds as 'min,max' (e.g., '-1,1')"), workers: int = typer.Option(1, "--workers", "-w", help="Parallel worker processes (1 = sequential)"), - video: bool = typer.Option(False, "--video", help="Also analyze camera streams (Tier 0 pixel metrics)"), - video_level: str = typer.Option("pixel", "--video-level", help="Video tier: 'pixel' (Tier 0) or 'motion' (Tier 1: optical flow). 'semantic' coming soon."), + video: bool = typer.Option(False, "--video", help="Also analyze camera integrity and pixel metrics"), + video_level: str = typer.Option("pixel", "--video-level", help="Video checks: 'pixel' or 'motion' (includes optical flow)"), video_downscale: int = typer.Option(128, "--video-downscale", help="Longest side (px) of the analysis frame"), - video_stride: int = typer.Option(1, "--video-stride", help="Analyze every Nth image-bearing frame"), - video_max_frames: int = typer.Option(0, "--video-max-frames", help="Cap analyzed frames per camera (0 = all)"), + video_stride: int = typer.Option(1, "--video-stride", help="Analyze every Nth episode observation"), + video_max_frames: int = typer.Option(0, "--video-max-frames", help="Cap decode attempts per camera (0 = all)"), video_cameras: str | None = typer.Option(None, "--video-cameras", help="Comma-separated camera names (default: all)"), + video_fps: float | None = typer.Option(None, "--video-fps", help="Explicit expected camera observation FPS; default: episode metadata"), + video_drop_frames: int = typer.Option(3, "--video-drop-frames", help="Estimated missing observations in one gap considered significant"), + video_gap_seconds: float = typer.Option(0.2, "--video-gap-seconds", help="Missing time beyond one expected frame that makes a gap significant"), + video_drop_fraction: float = typer.Option(0.05, "--video-drop-fraction", help="Estimated dropped-observation fraction that triggers a warning"), + video_freeze_seconds: float = typer.Option(0.5, "--video-freeze-seconds", help="Near-identical sampled-image span considered a sustained freeze candidate"), ) -> None: """Compute quality metrics on dataset episodes. @@ -1976,16 +1993,32 @@ def quality_cmd( if action_bounds: try: parts = action_bounds.split(",") + if len(parts) != 2: + raise ValueError("Expected two bounds") bounds = (float(parts[0]), float(parts[1])) except (ValueError, IndexError): console.print("[red]Error:[/red] --action-bounds must be 'min,max' (e.g., '-1,1')") raise typer.Exit(1) - config = QualityConfig( - gripper_dim=gripper_dim, - fps=fps, - action_bounds=bounds, - ) + try: + def parse_columns(value): + return tuple(int(x.strip()) for x in value.split(",")) if value is not None else None + + pairs = None + if tracking_pairs is not None: + pairs = tuple(tuple(int(x) for x in item.split(":")) for item in tracking_pairs.split(",")) + if any(len(pair) != 2 for pair in pairs): + raise ValueError("tracking pairs must use action:state syntax") + config = QualityConfig( + gripper_dim=gripper_dim, gripper_dims=parse_columns(gripper_dims), fps=fps, + action_bounds=bounds, action_semantics=action_semantics, tracking_pairs=pairs, + state_dims=parse_columns(state_dims), + state_scales=tuple(float(x) for x in state_scales.split(",")) if state_scales else None, + motion_speed_threshold=pause_speed, event_min_duration_s=event_min_duration, + tracking_error_threshold=tracking_error, tracking_lag_s=tracking_lag, + ) + except ValueError as exc: + raise typer.BadParameter(str(exc)) from exc # Video (Tier 0) config — only built when --video is passed. video_config = None @@ -1999,13 +2032,18 @@ def quality_cmd( from forge.quality.video import VideoQualityConfig cam_list = [c.strip() for c in video_cameras.split(",")] if video_cameras else None - video_config = VideoQualityConfig( - level=video_level, - downscale=video_downscale, - sample_stride=video_stride, - max_frames=video_max_frames, - cameras=cam_list, - ) + try: + video_config = VideoQualityConfig( + level=video_level, downscale=video_downscale, + sample_stride=video_stride, max_frames=video_max_frames, + cameras=cam_list, expected_fps=video_fps, + significant_drop_frames=video_drop_frames, + significant_gap_s=video_gap_seconds, + drop_fraction_flag=video_drop_fraction, + frozen_duration_s=video_freeze_seconds, + ) + except ValueError as exc: + raise typer.BadParameter(str(exc)) from exc if quick and sample == 0: sample = 50 @@ -2121,7 +2159,7 @@ def on_progress(done: int, total: int) -> None: import numpy as np scores = [eq.overall_score for eq in report.per_episode if eq.overall_score is not None] - report.overall_score = float(np.mean(scores)) if scores else 0.0 + report.overall_score = float(np.mean(scores)) if scores else None all_keys: set[str] = set() for eq in report.per_episode: @@ -2142,7 +2180,9 @@ def on_progress(done: int, total: int) -> None: # Overall score with color score = report.overall_score - if score >= 8.0: + if score is None: + score_color = "dim" + elif score >= 8.0: score_color = "green" elif score >= 6.0: score_color = "yellow" @@ -2151,7 +2191,9 @@ def on_progress(done: int, total: int) -> None: # Build the quality report panel lines: list[str] = [] - lines.append(f"Overall Quality Score: [{score_color}]{score:.1f} / 10[/{score_color}]") + display_score = f"{score:.1f} / 10" if score is not None else "N/A — review diagnostic events" + lines.append(f"Heuristic Quality Score: [{score_color}]{display_score}[/{score_color}]") + lines.append(f"[dim]q-v2-proprio · {len(scores)}/{report.num_episodes} episodes scored; not a task-success grade[/dim]") lines.append("") # Subscores with bar visualization @@ -2221,6 +2263,16 @@ def _collect(attr: str) -> list[float]: f"[dim](range {np.min(sa_vals):.2f}\u2013{np.max(sa_vals):.2f})[/dim]" ) + from collections import Counter + + event_counts = Counter(event.kind for eq in report.per_episode for event in eq.events) + if event_counts: + lines.append("") + lines.append("[bold]Proprioception events[/bold] [dim](review candidates, not verified failures)[/dim]") + for kind, count in sorted(event_counts.items()): + lines.append(f" {kind.replace('_', ' '):<30} {count}") + lines.append(" [dim]Use --visualize to review intervals; --export saves timestamps and applicability.[/dim]") + # Video (Tier 0) summary vid_eps = [eq for eq in report.per_episode if eq.video is not None] if vid_eps: @@ -2308,6 +2360,12 @@ def _vid_line(label: str, value: float | None, flag_key: str, fmt: str) -> None: console.print(f"[green]Flagged episodes saved to:[/green] {export_flagged}") + if visualize: + from forge.visualize.web_viewer import web_visualize + + web_visualize(resolved_path, max_episodes=report.num_episodes, quality_report=report) + + @app.command("filter") def filter_cmd( source: str = typer.Argument(..., help="Path to dataset (local or hf://org/repo)"), @@ -2322,10 +2380,10 @@ def filter_cmd( include_episodes: str | None = typer.Option(None, "--include-episodes", help="Only include these episode IDs (comma-separated)"), exclude_episodes: str | None = typer.Option(None, "--exclude-episodes", help="Exclude these episode IDs (comma-separated)"), from_report: Path | None = typer.Option(None, "--from-report", "-r", help="Use pre-computed quality report JSON"), - gripper_dim: int = typer.Option(-1, "--gripper-dim", "-g", help="Gripper dimension index (-1 = last)"), + gripper_dim: int | None = typer.Option(None, "--gripper-dim", "-g", help="Gripper dimension index (-1 = last)"), fps: float = typer.Option(30.0, "--fps", "-f", help="Fallback FPS if timestamps unavailable"), action_bounds: str | None = typer.Option(None, "--action-bounds", help="Known action bounds as 'min,max'"), - video_stride: int = typer.Option(1, "--video-stride", help="[video] Analyze every Nth image-bearing frame during live analysis"), + video_stride: int = typer.Option(1, "--video-stride", help="[video] Analyze every Nth episode observation during live analysis"), ) -> None: """Filter dataset episodes based on quality scores and flags. @@ -2361,6 +2419,8 @@ def filter_cmd( if action_bounds: try: parts = action_bounds.split(",") + if len(parts) != 2: + raise ValueError("Expected two bounds") bounds = (float(parts[0]), float(parts[1])) except (ValueError, IndexError): console.print("[red]Error:[/red] --action-bounds must be 'min,max' (e.g., '-1,1')") diff --git a/forge/filter/engine.py b/forge/filter/engine.py index af0b029..d7187c3 100644 --- a/forge/filter/engine.py +++ b/forge/filter/engine.py @@ -11,7 +11,7 @@ from dataclasses import dataclass, field from pathlib import Path -from forge.core.exceptions import ForgeError, UnsupportedFormatError +from forge.core.exceptions import ForgeError from forge.formats.registry import FormatRegistry from forge.quality.models import EpisodeQuality, QualityReport @@ -20,7 +20,20 @@ # Flags produced by the video analyzer — used to decide whether --exclude-flags # requires video analysis during live filtering. -_VIDEO_FLAGS = frozenset({"blurry", "over_exposed", "under_exposed", "frozen_frames"}) +_VIDEO_FLAGS = frozenset( + { + "blurry", + "over_exposed", + "under_exposed", + "frozen_frames", + "video_camera_missing", + "video_decode_failure", + "video_invalid_pixels", + "video_resolution_change", + "video_frame_drops", + "video_invalid_timestamps", + } +) # Flags that need Tier 1 (optical flow), which is pricier than Tier 0 pixel stats. _MOTION_FLAGS = frozenset({"no_motion", "shaky", "cut_detected"}) @@ -34,13 +47,13 @@ class FilterConfig: exclude_flags: list[str] | None = None # Video (Tier 0) numeric filters — keep episodes within these bounds. - min_sharpness: float | None = None # reject if video min_sharpness < this - max_frozen_fraction: float | None = None # reject if frozen_fraction > this + min_sharpness: float | None = None # reject if video min_sharpness < this + max_frozen_fraction: float | None = None # reject if frozen_fraction > this max_overexposed_fraction: float | None = None max_underexposed_fraction: float | None = None # Video (Tier 1) numeric filters — trigger optical-flow analysis. - min_motion: float | None = None # reject if mean_motion < this (px/frame) + min_motion: float | None = None # reject if mean_motion < this (px/frame) # Explicit episode selection include_episodes: list[str] | None = None @@ -50,7 +63,7 @@ class FilterConfig: from_report: Path | None = None # Quality config for live analysis - gripper_dim: int = -1 + gripper_dim: int | None = None fps: float = 30.0 action_bounds: tuple[float, float] | None = None @@ -282,15 +295,15 @@ def _evaluate_episode( # Quality-based filters require quality data if eq is None and self._needs_quality_analysis(): - logger.warning( - "No quality data for %s — skipping quality filters", episode_id - ) + logger.warning("No quality data for %s — skipping quality filters", episode_id) return True, [] # Min quality score if self.config.min_quality is not None and eq is not None: score = eq.overall_score - if score is not None and score < self.config.min_quality: + if score is None: + reasons.append(f"no quality score (min {self.config.min_quality} required)") + elif score < self.config.min_quality: reasons.append(f"score {score:.1f} < min {self.config.min_quality}") # Exclude flags @@ -342,9 +355,7 @@ def _evaluate_video( and vq.frozen_fraction is not None and vq.frozen_fraction > c.max_frozen_fraction ): - reasons.append( - f"frozen {vq.frozen_fraction:.2f} > max {c.max_frozen_fraction:g}" - ) + reasons.append(f"frozen {vq.frozen_fraction:.2f} > max {c.max_frozen_fraction:g}") if ( c.max_overexposed_fraction is not None and vq.overexposed_fraction is not None diff --git a/forge/formats/lerobot_v2/reader.py b/forge/formats/lerobot_v2/reader.py index a9b8776..f504e7c 100644 --- a/forge/formats/lerobot_v2/reader.py +++ b/forge/formats/lerobot_v2/reader.py @@ -26,6 +26,7 @@ from __future__ import annotations import json +import logging from collections.abc import Iterator from pathlib import Path from typing import TYPE_CHECKING, Any @@ -49,6 +50,8 @@ if TYPE_CHECKING: from numpy.typing import NDArray +logger = logging.getLogger(__name__) + def _check_pyarrow() -> None: """Check if PyArrow is available.""" @@ -475,12 +478,26 @@ def _extract_frame(self, video_path: Path, frame_index: int) -> NDArray[Any]: if current_frame >= frame_index: return frame.to_ndarray(format="rgb24") - # If we didn't find the frame, return black + # Frame index past the end of the video. Fill with black, but say so: + # a silent black frame looks like valid data downstream. + logger.warning( + "Frame %d not found in %s; substituting a black frame", frame_index, video_path + ) return np.zeros((480, 640, 3), dtype=np.uint8) - except (ImportError, Exception): + except ImportError as e: + raise MissingDependencyError( + "av", "decoding LeRobot v2 video frames", "pip install \"forge-robotics[video]\"" + ) from e + except Exception as e: import numpy as np + logger.warning( + "Could not decode frame %d of %s (%s); substituting a black frame", + frame_index, + video_path, + e, + ) return np.zeros((480, 640, 3), dtype=np.uint8) def read_episode(self, path: Path, episode_id: str) -> Episode: diff --git a/forge/formats/lerobot_v3/reader.py b/forge/formats/lerobot_v3/reader.py index 2310349..6c7601c 100644 --- a/forge/formats/lerobot_v3/reader.py +++ b/forge/formats/lerobot_v3/reader.py @@ -57,7 +57,7 @@ # Global video frame cache for efficient sequential access -_video_cache: dict[str, "VideoFrameCache"] = {} +_video_cache: dict[str, VideoFrameCache] = {} _video_cache_lock = Lock() @@ -92,6 +92,9 @@ def _open(self) -> bool: self._total_frames = self._stream.frames or 0 return True except Exception: + if self._container is not None: + self._container.close() + self._container = self._stream = self._decoder = None return False def _frame_index_of(self, frame: Any) -> int: @@ -117,53 +120,42 @@ def _prune(self, around: int) -> None: del self._frame_cache[k] def get_frame(self, frame_idx: int, dims: tuple[int, int, int] = (480, 640, 3)) -> Any: - """Get a frame, using cache or sequential decode.""" - import numpy as np + """Return the requested decoded frame; never fabricate pixels on failure. + ``dims`` remains accepted for caller compatibility. A missing/undecodable + frame raises ValueError so quality analysis can record the failure and + viewers can display an unavailable-frame placeholder. + """ with self._lock: if frame_idx in self._frame_cache: return self._frame_cache[frame_idx] - if not self._open(): - return np.zeros(dims, dtype=np.uint8) - + raise ValueError(f"Cannot open video: {self.video_path}") try: - # Seek when going backwards, jumping far ahead, or starting fresh. if ( self._decoder is None or frame_idx < self._current_frame_idx or frame_idx > self._current_frame_idx + 30 ): self._seek_to_frame(frame_idx) - - last_img = None for frame in self._decoder: fi = self._frame_index_of(frame) self._current_frame_idx = fi img = frame.to_ndarray(format="rgb24") self._frame_cache[fi] = img - last_img = img self._prune(frame_idx) - if fi == frame_idx: return img if fi > frame_idx: - # Overshot (target frame absent / PTS rounding) — return - # the closest frame we have rather than a black frame. - return self._frame_cache.get(frame_idx, img) - - # Decoder exhausted before reaching the target. Return the last - # real frame instead of black so a short/edge read can't masquerade - # as a scene cut or frozen frame downstream. + raise ValueError( + f"Requested video frame {frame_idx} is absent (next decoded index {fi})" + ) + raise ValueError(f"Video ended before requested frame {frame_idx}") + except Exception as exc: self._decoder = None - if frame_idx in self._frame_cache: - return self._frame_cache[frame_idx] - if last_img is not None: - return last_img - return np.zeros(dims, dtype=np.uint8) - - except Exception: - return np.zeros(dims, dtype=np.uint8) + raise ValueError( + f"Cannot decode frame {frame_idx} from {self.video_path}: {exc}" + ) from exc def _seek_to_frame(self, target_frame: int) -> None: """Seek to (a keyframe at or before) a frame position. @@ -271,10 +263,13 @@ def can_read(cls, path: Path) -> bool: major = int(version.split(".")[0]) if major >= 3: return True + # v2.x datasets can also contain tasks.jsonl, so an explicit + # older version wins over the file-based checks below. + return False except (ValueError, IndexError): pass - elif isinstance(version, (int, float)) and version >= 3: - return True + elif isinstance(version, (int, float)): + return version >= 3 except (json.JSONDecodeError, KeyError): pass @@ -1152,9 +1147,11 @@ def _build_episode( # Image-mode cameras (dtype == "image"): inline PNG bytes live directly # in the data parquet under their full feature key. image_camera_features: dict[str, dict] = {} + dataset_fps = None if info_path.exists(): with open(info_path) as f: info = json.load(f) + dataset_fps = info.get("fps") for key, spec in info.get("features", {}).items(): if spec.get("dtype") == "video": camera_features[key] = spec @@ -1434,6 +1431,21 @@ def make_image_loader( return Episode( episode_id=episode_id, language_instruction=language, + fps=dataset_fps, + cameras={ + key.split(".")[-1]: CameraInfo( + name=key.split(".")[-1], + height=spec.get("shape", [480, 640, 3])[0], + width=spec.get("shape", [480, 640, 3])[1], + channels=3, + storage=storage, + ) + for features, storage in ( + (camera_features, "mp4"), + (image_camera_features, "image"), + ) + for key, spec in features.items() + }, _frame_loader=load_frames, ) diff --git a/forge/formats/lerobot_v3/writer.py b/forge/formats/lerobot_v3/writer.py index 97c6b20..a9d20d9 100644 --- a/forge/formats/lerobot_v3/writer.py +++ b/forge/formats/lerobot_v3/writer.py @@ -626,7 +626,10 @@ def finalize(self, output_path: Path, dataset_info: DatasetInfo) -> None: meta_dir = output_path / "meta" meta_dir.mkdir(parents=True, exist_ok=True) - fps = int(self.config.fps or dataset_info.inferred_fps or 30) + fps = float(self.config.fps or dataset_info.inferred_fps or 30) + # Keep fractional rates (29.97, 12.5 Hz); write whole rates as ints like LeRobot does. + if fps.is_integer(): + fps = int(fps) # Use metadata count if available, otherwise fall back to dataset_info # (needed for parallel processing where workers write directly) total_episodes = len(self._episode_metadata) if self._episode_metadata else dataset_info.num_episodes diff --git a/forge/io/README.md b/forge/io/README.md index 6ef3eba..a575f8d 100644 --- a/forge/io/README.md +++ b/forge/io/README.md @@ -51,7 +51,7 @@ Any command that takes a dataset path works with a cloud URI: ```bash forge inspect s3://my-bucket/datasets/run_0413 forge convert gs://lab-data/rosbags ./out --format lerobot-v3 -forge quality s3://my-bucket/datasets/droid --report report.html +forge quality s3://my-bucket/datasets/droid --export report.json forge stats gs://lab-data/pusht.zarr ``` diff --git a/forge/quality/README.md b/forge/quality/README.md index a299703..f2a5b5c 100644 --- a/forge/quality/README.md +++ b/forge/quality/README.md @@ -1,241 +1,108 @@ -# Forge Quality Metrics +# Quality metrics -Episode-level quality scoring for robotics demonstration data using proprioception signals only (joint states, actions, timestamps). No video or image processing. +Analyze robot states, actions, and timestamps with NumPy. Video checks are optional +and separate from the proprioception score. -## Usage - -### CLI +## Quick start ```bash -# Local dataset -forge quality ./my_dataset/ - -# HuggingFace dataset -forge quality hf://lerobot/aloha_sim_cube - -# With options -forge quality ./my_dataset --gripper-dim 6 --fps 30 --export report.json -forge quality ./my_dataset --export-flagged flagged.json -forge quality ./my_dataset --sample 50 --quick - -# Known action bounds (tighter saturation detection) -forge quality ./my_dataset --action-bounds -1.0,1.0 - -# Via stats command -forge stats ./my_dataset --quality -``` - -### Python API - -```python -from forge.quality import QualityAnalyzer, QualityConfig - -# Analyze a full dataset -analyzer = QualityAnalyzer(gripper_dim=-1, fps=30.0) -report = analyzer.analyze_dataset("./my_dataset") -print(report.overall_score) # 7.8 -print(report.flagged_episodes) # {"jerky": ["ep_42", ...], ...} -report.to_json("quality_report.json") - -# Analyze a single episode from numpy arrays -eq = analyzer.analyze_episode_arrays( - episode_id="ep_0", - actions=actions_array, # (T, D) - states=states_array, # (T, D) - timestamps=timestamps, # (T,) - fps=30.0, -) -print(eq.overall_score) # 8.4 -print(eq.flags) # [] -print(eq.is_flagged) # False -``` - -## Metrics - -### 1. Dead Action Detection -Detects timesteps where all action dimensions are zero or constant, indicating teleoperation disconnects or recording artifacts. - -- **Output**: `dead_fraction` (0-1), `dead_ranges` (contiguous segments) -- **Reference**: Kim et al. "OpenVLA" (2024) — filters degenerate transitions - -### 2. Log Dimensionless Jerk (LDLJ) -Gold-standard smoothness metric from motor control. Computes jerk (third derivative of position) normalized by movement duration and peak velocity. - -- **Output**: `ldlj_score` (more negative = jerkier; smooth: -6 to -8, jerky: -15 to -25) -- **Scoring**: Sigmoid normalization with configurable center/scale -- **Reference**: Hogan & Sternad (2009); validated by Scano et al., Frontiers in Neurology (2018) - -### 3. Gripper Chatter Detection -Counts rapid open/close transitions that indicate noisy teleoperation input. - -- **Output**: `chatter_count`, `chatter_rate` (transitions/sec), `is_chattery` -- **Reference**: Sakr et al. "Consistency Matters" (ACM THRI, 2024) - -### 4. Path Length -Sum of step-to-step distances in joint space. Useful as a relative metric to compare episodes of the same task (longer = more wandering/hesitation). - -- **Output**: `joint_path_length` -- **Note**: Not included in composite score (relative metric, not absolute quality) -- **Reference**: Sakr et al. "Consistency Matters" (2024); Osa et al. (2018) - -### 5. Timestamp Regularity -Detects recording issues: dropped frames, irregular timing, frequency drift. - -- **Output**: `dt_mean`, `dt_std`, `jitter_ratio`, `num_gaps`, `gap_locations`, `effective_fps` -- **Reference**: General signal integrity; HuggingFace LeRobot video encoding blog (2024) - -### 6. Action Range Saturation -Percentage of timesteps where action dimensions hit their min/max bounds, indicating hardware limits or clipping. - -- **Output**: `saturation_per_dim`, `overall_saturation`, `saturated_dims` -- **Supports**: Known bounds via `--action-bounds` or auto-inferred from data - -### 7. Static Episode Detection -Fraction of episode where the robot is essentially not moving, detecting idle periods. - -- **Output**: `static_fraction`, `is_mostly_static`, `longest_static_run`, `static_segments` -- **Reference**: Liu et al. "SCIZOR" (2025) — 15.4% avg improvement after filtering static data - -### 8. Action Distribution Entropy -Shannon entropy of action distribution per dimension, normalized to 0-1 range. Measures diversity within an episode. - -- **Output**: `entropy_per_dim`, `mean_entropy` -- **Scoring**: Bell curve — penalizes both too low (repetitive) and too high (random) -- **Reference**: Belkhale et al. "DemInf" (2025); Belkhale & Sadigh "Data Quality in Imitation Learning" (NeurIPS, 2023) - -### 9. Manipulability Index (Yoshikawa) — Deferred -Distance from singular configurations. Requires a kinematic model (URDF). - -- **Status**: Not implemented. Needs robot-specific URDF and a kinematics library (pinocchio/ikpy). -- **Reference**: Yoshikawa (1985); validated in Sakr et al. (2024) - -### 10. Composite Quality Score -Weighted combination of metrics 1-8, normalized to a 0-10 scale. - -| Metric | Weight | Scoring | -|---|---|---| -| Smoothness (LDLJ) | 0.25 | Sigmoid normalization | -| Dead Actions | 0.15 | 1.0 - dead_fraction | -| Gripper Health | 0.15 | 1.0 if clean, penalized by chatter rate | -| Static Detection | 0.15 | 1.0 - static_fraction | -| Timestamp Regularity | 0.10 | 1.0 if jitter < threshold | -| Action Saturation | 0.10 | 1.0 - overall_saturation | -| Action Diversity | 0.10 | Bell curve around expected entropy | - -All weights and thresholds are configurable via `QualityConfig`. - -## Module Structure - -``` -forge/quality/ - __init__.py Public API exports - config.py QualityConfig dataclass (all thresholds, weights, params) - metrics.py Individual metric functions (pure numpy) - analyzer.py QualityAnalyzer orchestrator + dataset-level analysis - models.py EpisodeQuality, QualityReport, TimestampResult, StaticResult -``` - -## Adding a New Metric - -To add a new quality metric, update these locations: - -### 1. Add the metric function (`metrics.py`) - -Write a pure function that takes numpy arrays and returns results. Follow the existing pattern: - -```python -def my_new_metric( - actions: NDArray, config: QualityConfig -) -> tuple[float, ...]: - """One-line description. - - Args: - actions: Shape (T, D) action array. - config: Quality configuration. - - Returns: - Tuple of result values. - """ - # Implementation using vectorized numpy — no Python loops over timesteps - ... +forge quality ./dataset --visualize --export quality.json +forge quality aloha_sim_transfer_cube --sample 5 --video --visualize +forge quality ./dataset --gripper-dims 6,13 --action-bounds=-1,1 ``` -Requirements: -- **Numpy only** — no torch, tensorflow, or heavy dependencies -- **Return None** if the metric can't be computed (too few frames, missing data) -- **Handle NaN/Inf** gracefully — the analyzer sanitizes inputs, but be defensive -- Cite the paper in the module docstring at the top of `metrics.py` - -### 2. Add result fields (`models.py`) - -Add fields to `EpisodeQuality` for storing the metric's output: - ```python -# Metric N: My New Metric -my_metric_value: float | None = None -``` +from forge.quality import QualityAnalyzer -If the metric returns a complex result, add a new dataclass (like `StaticResult` or `TimestampResult`) and reference it from `EpisodeQuality`. Include relevant fields in `to_dict()` for JSON export. +analyzer = QualityAnalyzer() # No inferred gripper channel or physical limits. +report = analyzer.analyze_dataset("./dataset") +report.to_json("quality.json") -### 3. Wire into the analyzer (`analyzer.py`) - -In `QualityAnalyzer.analyze_episode_arrays()`, call your metric and store the results: - -```python -# N. My new metric -eq.my_metric_value = my_new_metric(actions, self.config) +result = analyzer.analyze_episode_arrays( + "episode_0", actions=actions, states=states, timestamps=timestamps, fps=30.0 +) +print(result.overall_score) # A heuristic score, or None when unavailable. +print(result.events) ``` -Place it in the appropriate section (action-based, state-based, or timestamp-based). - -### 4. Add scoring to composite score (`metrics.py`) - -In `composite_score()`, add a scoring block that maps your metric's raw value to a 0-1 quality signal: - -```python -# My new metric -if my_metric_value is not None: - subscores["my_metric"] = ... # 0-1 quality signal - weights["my_metric"] = config.weight_my_metric - if my_metric_value > config.my_metric_flag: - flags.append("my_metric_issue") -``` +## Proprioception diagnostics and visual review (q-v2-proprio) -### 5. Add config fields (`config.py`) +```bash +forge quality ./my_dataset --sample 20 --visualize --export quality.json -Add any thresholds, weights, and parameters to `QualityConfig`: +# Only for datasets with known absolute position actions and matching state units: +forge quality ./my_dataset --action-semantics position \ + --tracking-pairs 0:0,1:1 --tracking-error 0.05 --tracking-lag 0.1 \ + --pause-speed 0.001 --event-min-duration 0.5 --visualize -```python -# ── My new metric ── -my_metric_threshold: float = 0.5 -weight_my_metric: float = 0.10 +# Explicit grippers for a known bimanual layout: +forge quality ./my_dataset --gripper-dims 6,13 ``` -Adjust existing weights so they still sum to 1.0 (or close to it — the composite score normalizes by total weight). +`--visualize` opens the existing local web viewer after scoring. It displays the analyzed episodes, event lanes, shaded action/state plots, episode flags, and metric availability. Click a span or choose an event to seek playback. The command serves the viewer until Ctrl+C. Green means **no event detected by enabled checks**, not task success; amber marks review candidates, red tracking-stall candidates, and gray unavailable data/gaps. Direction reversals are hidden by default; enable the checkbox to show these descriptive events in blue. Episode-wide flags without localized evidence remain listed separately. -### 6. Add recommendations (`analyzer.py`) +| Diagnostic | Interpretation | +|---|---| +| `held_command_fraction` / `held_command` | Sustained adjacent repeated commands, measured over observed duration | +| `static` / `motion_pause` | Sustained low measured speed, with frame and time intervals | +| `direction_reversal_count` / `direction_reversal` | Sustained direction changes per selected state channel; descriptive, not a retry classifier | +| `path_length_scaled`, `net_to_path_ratio` | Travel and endpoint displacement divided by travel; closed-loop tasks can naturally have a low ratio | +| `tracking_error_mean`, `tracking_error_p95` | Maximum mapped command/state residual at each sample, with optional causal lag | +| `tracking_stall_fraction` / `tracking_stall_candidate` | Low measured speed while mapped absolute-position commands remain far away; contact can cause this too | +| `valid_duration_s`, `time_coverage`, `timestamp_gap` | Observed time support; events never bridge long recording gaps | -In `_generate_recommendations()`, add a human-readable flag and actionable suggestion: +Motion metrics assume **position** state columns. Select them with `--state-dims`; `--state-scales` supplies a positive divisor for every original state column, including unselected columns. Default scales are 1, so thresholds use native units (and native units/second for speed). For mixed units, supply meaningful scales before comparing episodes. Tracking pairs require compatible action/state units and explicit `position` semantics; vector shape does not establish correspondence. Tune duration, speed, error, and lag thresholds to the robot and task. -```python -if "my_metric_issue" in flagged: - n = len(flagged["my_metric_issue"]) - flags.append(f"{n} episodes with my metric issue") - recs.append("Suggestion for the user") -``` +Scores are heuristics, not validated usefulness or success grades. Invalid/nonfinite data, nonmonotonic timestamps, irregular timebases, or degenerate measured motion can produce `overall_score: null`. Constant measured states never fall back to moving commands for smoothness. Missing gripper mappings and hardware limits are omitted from their subscores. Changing available subscores changes score comparability; **q-v1 thresholds should be recalibrated**. -### 7. Add tests (`tests/test_quality.py`) +JSON exports preserve `scorer_version`, configuration/timebase `provenance`, `metric_status`, raw `diagnostics`, static/timestamp results, and localized `events`. Each event has an inclusive `start_frame`, exclusive `end_frame`, timestamps, and affected state channels where applicable. Event duration is the difference between boundary timestamps, not the frame count divided by FPS. Legacy reports can still be loaded and are marked q-v1. Catalog scoring uses a new version; detailed events live in report exports. -Add a test class with at least: -- A test for the expected good case -- A test for the expected bad case -- Edge cases (empty data, constant values, etc.) +Retries, task progress, contact success, and failure grades need task context or additional evidence. These checks intentionally expose motion candidates for review. Video checks are documented separately. -```python -class TestMyNewMetric: - def test_good_case(self): - ... +## Measurements and scoring - def test_bad_case(self): - ... -``` +| Measurement | Meaning | Included in score? | +|---|---|---| +| LDLJ smoothness | Position jerk normalized by duration and peak speed | Yes | +| Dead-action fraction | Zero or adjacent repeated commands; holds can be intentional | Yes | +| Gripper chatter | Rapid transitions on explicitly configured action channels | When configured | +| Static fraction | Sustained low measured speed over valid observed time | When available | +| Timestamp regularity | Jitter and gaps against expected FPS | When available | +| Action saturation | Occupancy near supplied physical command limits | When configured | +| Action entropy | Marginal action-distribution entropy | Yes | +| Path length | Travel in selected, scaled position channels | No | +| SPARC | Frequency-based smoothness | No | +| PSD bands | Action energy in configured frequency bands | No; can flag high-band activity | +| State/action consistency | Raw action variance among nearby within-episode states | No | + +The composite normalizes weights over available components. Default weights are +0.25 for smoothness; 0.15 each for dead actions, gripper health, and static fraction; +and 0.10 each for timing, saturation, and entropy. Configure them with `QualityConfig`. +Missing components and robot-specific thresholds limit comparisons between scores. +Path length, entropy, and consistency do not establish task progress or success. + +## Compatibility + +- Gripper detection is disabled by default. Set `gripper_dim` or `gripper_dims`. +- Without physical limits, observed action-range occupancy is descriptive only. +- Motion requires position-state columns. Command smoothness is a fallback only + when states are absent and `action_semantics="position"` is explicit. +- Invalid data retains its frame alignment and is not replaced with zeros. +- Scores can be null. Consumers must handle unavailable results. +- Legacy JSON remains readable. Recalibrate thresholds when moving from q-v1. +- Video JSON keeps per-camera details and legacy flat fields. See the + [video compatibility notes](video/README.md#reports-and-viewer). + +## Development + +`config.py` defines thresholds; `metrics.py` contains scalar measurements; +`diagnostics.py` produces temporal events. `analyzer.py` coordinates them, and +`models.py` handles report serialization. + +For a new check, add configuration, result fields, availability, and provenance. +Add frame/time evidence when localizable. Keep descriptive attributes outside the +composite unless their interpretation is justified. Test valid, invalid, missing, +and degenerate inputs, plus serialization and CLI integration where applicable. + +See [validation and benchmarks](../../docs/reports/README.md) and the +[viewer guide](../visualize/README.md). diff --git a/forge/quality/__init__.py b/forge/quality/__init__.py index 33c7603..6d0bd4e 100644 --- a/forge/quality/__init__.py +++ b/forge/quality/__init__.py @@ -8,18 +8,19 @@ from forge.quality import QualityAnalyzer, QualityReport - analyzer = QualityAnalyzer(gripper_dim=-1, fps=30.0) + analyzer = QualityAnalyzer(fps=30.0) report = analyzer.analyze_dataset("./bridge_v2") print(report.overall_score) """ from forge.quality.analyzer import QualityAnalyzer from forge.quality.config import QualityConfig -from forge.quality.models import EpisodeQuality, QualityReport +from forge.quality.models import EpisodeQuality, QualityEvent, QualityReport __all__ = [ "QualityAnalyzer", "QualityConfig", "QualityReport", "EpisodeQuality", + "QualityEvent", ] diff --git a/forge/quality/analyzer.py b/forge/quality/analyzer.py index bfc1acc..75a688d 100644 --- a/forge/quality/analyzer.py +++ b/forge/quality/analyzer.py @@ -3,8 +3,8 @@ from __future__ import annotations from collections import defaultdict +from dataclasses import asdict, replace from pathlib import Path -from typing import Iterator import numpy as np @@ -16,11 +16,9 @@ dead_action_detection, gripper_chatter, log_dimensionless_jerk, - path_length, psd_band_energy, spectral_arc_length, state_conditioned_action_variance, - static_detection, timestamp_regularity, ) from forge.quality.models import EpisodeQuality, QualityReport @@ -31,7 +29,7 @@ class QualityAnalyzer: Usage:: - analyzer = QualityAnalyzer(gripper_dim=-1, fps=30.0) + analyzer = QualityAnalyzer(fps=30.0) report = analyzer.analyze_dataset("./bridge_v2") print(report.overall_score) """ @@ -75,111 +73,161 @@ def analyze_episode_arrays( Returns: EpisodeQuality with all computable metrics. """ - eq = EpisodeQuality(episode_id=episode_id) - effective_fps = fps or self.config.fps - - # Determine frame count - for arr in (actions, states, timestamps): - if arr is not None: - eq.num_frames = len(arr) - break + from forge.quality.diagnostics import diagnose, indices + eq = EpisodeQuality(episode_id=episode_id) + effective_fps = self.config.fps if fps is None else fps + if not np.isfinite(effective_fps) or effective_fps <= 0: + raise ValueError("fps must be finite and positive") + eq.provenance = { + "config": asdict(self.config), + "fps": effective_fps, + "timebase": "stored" if timestamps is not None else "inferred_from_fps", + } + arrays = {} + for name, value in (("actions", actions), ("states", states), ("timestamps", timestamps)): + if value is None: + continue + value = np.asarray(value, dtype=np.float64) + expected_ndim = 1 if name == "timestamps" else 2 + if value.ndim != expected_ndim or (value.ndim == 2 and value.shape[1] == 0): + raise ValueError( + f"{name} must have {'(T,)' if expected_ndim == 1 else '(T, D)'} shape" + ) + arrays[name] = value + lengths = {len(x) for x in arrays.values()} + if len(lengths) > 1: + raise ValueError("actions, states, and timestamps must have matching frame counts") + eq.num_frames = next(iter(lengths), 0) + for name, value in arrays.items(): + if not np.isfinite(value).all(): + eq.flags.append(f"nan_in_{name}") + eq.metric_status[name] = ( + "invalid: nonfinite or missing samples; no zero substitution" + ) + if eq.flags: + eq.metric_status["score"] = "unavailable: invalid input" + return eq if eq.num_frames < self.config.min_frames: + eq.metric_status["score"] = "unavailable: insufficient frames" return eq - - # Compute dt for derivative metrics - if timestamps is not None and len(timestamps) > 1: - dt = float(np.mean(np.diff(timestamps))) - else: - dt = 1.0 / effective_fps - - duration = (eq.num_frames - 1) * dt - - # ── Action-based metrics ── - if actions is not None and actions.size > 0: - # Handle NaN/Inf - if np.any(~np.isfinite(actions)): - eq.flags.append("nan_in_actions") - actions = np.nan_to_num(actions, nan=0.0, posinf=0.0, neginf=0.0) - - # 1. Dead actions - eq.dead_fraction, eq.dead_ranges = dead_action_detection( - actions, self.config + actions, states = arrays.get("actions"), arrays.get("states") + timestamps = arrays.get("timestamps") + t = np.arange(eq.num_frames) / effective_fps if timestamps is None else timestamps + if np.any(np.diff(t) <= 0): + eq.flags.append("invalid_timestamps") + eq.metric_status["score"] = "unavailable: timestamps must strictly increase" + return eq + dt = float(np.mean(np.diff(t))) + duration = float(t[-1] - t[0]) + eq.diagnostics, eq.events, statuses, eq.static = diagnose( + actions, states, t, self.config, effective_fps + ) + eq.metric_status.update(statuses) + regular = True + if timestamps is not None: + eq.timestamps = timestamp_regularity(t, effective_fps) + regular = ( + eq.timestamps.num_gaps == 0 + and eq.timestamps.jitter_ratio <= self.config.jitter_warn_ratio ) - - # 3. Gripper chatter - if actions.shape[1] > 1: - eq.gripper_chatter_count, eq.gripper_chatter_rate, eq.is_chattery = ( - gripper_chatter(actions, duration, self.config) + if eq.timestamps.num_gaps: + eq.flags.append("timestamp_gaps") + if abs(eq.timestamps.effective_fps / effective_fps - 1) > self.config.jitter_warn_ratio: + eq.flags.append("sample_rate_mismatch") + eq.metric_status["uniform_sampling"] = ( + "available" + if regular + else "unavailable: irregular timestamps; spectral/derivative metrics skipped" + ) + if actions is not None: + eq.dead_fraction, eq.dead_ranges = dead_action_detection(actions, self.config) + eq.metric_status["dead_actions"] = ( + "diagnostic: zero/repeated commands can be intentional" + ) + dims = self.config.gripper_dims + if dims is None: + dims = () if self.config.gripper_dim is None else (self.config.gripper_dim,) + dims = indices(dims, actions.shape[1], "gripper_dims") + for dim in dims: + count, rate, flagged = gripper_chatter( + actions, duration, replace(self.config, gripper_dims=None, gripper_dim=dim) ) - - # 6. Action saturation - sat_per_dim, eq.overall_saturation, eq.saturated_dims = action_saturation( - actions, self.config + eq.grippers[str(dim)] = {"transitions": count, "rate": rate, "is_chattery": flagged} + if eq.grippers: + eq.gripper_chatter_count = sum(g["transitions"] for g in eq.grippers.values()) + eq.gripper_chatter_rate = max(g["rate"] for g in eq.grippers.values()) + eq.is_chattery = any(g["is_chattery"] for g in eq.grippers.values()) + eq.metric_status["gripper"] = ( + "available: explicit channels" + if dims + else "not_applicable: no gripper channels configured" ) - eq.saturation_per_dim = sat_per_dim.tolist() - - # 7. Static detection - eq.static = static_detection(actions, effective_fps, self.config) - - # 8. Action entropy - ent_per_dim, eq.mean_entropy = action_entropy(actions) - eq.entropy_per_dim = ent_per_dim.tolist() - - # 9b. PSD band energy (generalized chatter across all action dims) - bands = psd_band_energy( - actions, - effective_fps, - low_hz=self.config.psd_low_hz, - high_hz=self.config.psd_high_hz, + sat, overall, saturated_dims = action_saturation(actions, self.config) + if self.config.action_bounds is not None or self.config.action_limits is not None: + eq.saturation_per_dim = sat.tolist() + eq.overall_saturation = overall + eq.saturated_dims = saturated_dims + eq.metric_status["saturation"] = "available: supplied command limits" + else: + eq.observed_range_edge_fraction = overall + eq.metric_status["saturation"] = ( + "unavailable: no supplied limits; observed_range_edge_fraction is descriptive only" + ) + entropy, eq.mean_entropy = action_entropy(actions) + eq.entropy_per_dim = entropy.tolist() + if regular: + bands = psd_band_energy( + actions, 1 / dt, low_hz=self.config.psd_low_hz, high_hz=self.config.psd_high_hz + ) + if bands is not None: + eq.psd_bands = bands + eq.psd_high_fraction = bands["high_fraction"] + if eq.psd_high_fraction > self.config.psd_high_flag: + eq.flags.append("psd_high_band_chatter") + eq.metric_status["psd"] = ( + "available" + if eq.psd_bands is not None + else "unavailable: sample rate or regularity cannot support configured bands" ) - if bands is not None: - eq.psd_bands = bands - eq.psd_high_fraction = bands["high_fraction"] - if bands["high_fraction"] > self.config.psd_high_flag: - eq.flags.append("psd_high_band_chatter") - - # ── State-based metrics ── - if states is not None and states.size > 0: - if np.any(~np.isfinite(states)): - eq.flags.append("nan_in_states") - states = np.nan_to_num(states, nan=0.0, posinf=0.0, neginf=0.0) - - # 2. LDLJ smoothness (joint space) - eq.ldlj = log_dimensionless_jerk(states, dt) - - # 9a. SPARC smoothness (frequency-domain complement to LDLJ) - eq.sparc = spectral_arc_length(states, dt) - - # 4. Path length (joint space) - eq.joint_path_length = path_length(states) - - # If no states but actions available, compute LDLJ + SPARC from actions - if actions is not None and actions.size > 0: - if eq.ldlj is None: - eq.ldlj = log_dimensionless_jerk(actions, dt) - if eq.sparc is None: - eq.sparc = spectral_arc_length(actions, dt) - - # 9c. State-conditioned action variance (proprio STAC analogue) — - # needs both states and actions of matching length. - if ( - states is not None - and actions is not None - and states.size > 0 - and actions.size > 0 - and len(states) == len(actions) - ): - _per_frame, mean_var = state_conditioned_action_variance( + # Never substitute command motion for a supplied stationary state trace. + positions = states + if states is not None: + dims = indices( + self.config.state_dims + if self.config.state_dims is not None + else range(states.shape[1]), + states.shape[1], + "state_dims", + ) + scales = ( + np.ones(states.shape[1]) + if self.config.state_scales is None + else np.asarray(self.config.state_scales) + ) + positions = states[:, dims] / scales[dims] + eq.joint_path_length = eq.diagnostics["path_length_scaled"] + elif self.config.action_semantics == "position": + positions = actions + if positions is not None and regular: + eq.ldlj = log_dimensionless_jerk(positions, dt) + eq.sparc = spectral_arc_length(positions, dt) + eq.metric_status["smoothness"] = ( + ( + "available: state positions" + if states is not None + else "available: commanded positions" + ) + if eq.ldlj is not None + else "unavailable: no motion, no positional data, or irregular timing" + ) + if states is not None and actions is not None: + _, eq.state_action_consistency = state_conditioned_action_variance( states, actions, k=self.config.state_action_k ) - eq.state_action_consistency = mean_var - - # ── Timestamp metrics ── - if timestamps is not None and len(timestamps) > 1: - eq.timestamps = timestamp_regularity(timestamps, effective_fps) - - # ── Composite score ── + eq.metric_status["state_action_consistency"] = ( + "diagnostic: unnormalized within-episode neighbors; not a task-correctness score" + ) eq.overall_score, eq.subscores, score_flags = composite_score( dead_fraction=eq.dead_fraction, ldlj_score=eq.ldlj, @@ -192,7 +240,16 @@ def analyze_episode_arrays( config=self.config, ) eq.flags.extend(score_flags) - + if any(e.kind == "tracking_stall_candidate" for e in eq.events): + eq.flags.append("tracking_stall_candidate") + eq.metric_status["score"] = ( + "heuristic: not task success or training utility; missing components omitted" + ) + if not eq.subscores or not regular or (states is not None and eq.ldlj is None): + eq.overall_score = None + eq.metric_status["score"] = ( + "unavailable: no evaluable motion or irregular timebase; review diagnostics" + ) return eq def analyze_episode(self, episode) -> EpisodeQuality: @@ -213,26 +270,35 @@ def analyze_episode(self, episode) -> EpisodeQuality: # Single pass: collect proprio arrays and, when enabled, feed video # frames into per-camera accumulators so the episode decodes only once. video_accums = ( - self._video_analyzer.new_accumulators() + self._video_analyzer.new_accumulators(episode.fps, episode.cameras) if self._video_analyzer is not None else None ) - image_frame_idx = -1 - - for frame in episode.frames(): - if frame.action is not None: - actions_list.append(np.asarray(frame.action, dtype=np.float64)) - if frame.state is not None: - states_list.append(np.asarray(frame.state, dtype=np.float64)) - if frame.timestamp is not None: - timestamps_list.append(frame.timestamp) - if video_accums is not None and frame.images: - image_frame_idx += 1 - self._video_analyzer.consume_frame(frame, video_accums, image_frame_idx) - - actions = np.stack(actions_list) if actions_list else None - states = np.stack(states_list) if states_list else None - timestamps = np.array(timestamps_list) if timestamps_list else None + + for frame_index, frame in enumerate(episode.frames()): + actions_list.append( + None if frame.action is None else np.asarray(frame.action, dtype=np.float64) + ) + states_list.append( + None if frame.state is None else np.asarray(frame.state, dtype=np.float64) + ) + timestamps_list.append(frame.timestamp) + if video_accums is not None: + self._video_analyzer.consume_frame(frame, video_accums, frame_index) + + def aligned(values): + example = next((v for v in values if v is not None), None) + if example is None: + return None + return np.stack([np.full_like(example, np.nan) if v is None else v for v in values]) + + actions = aligned(actions_list) + states = aligned(states_list) + timestamps = ( + np.array([np.nan if t is None else t for t in timestamps_list]) + if any(t is not None for t in timestamps_list) + else None + ) eq = self.analyze_episode_arrays( episode_id=episode.episode_id, @@ -307,12 +373,8 @@ def analyze_dataset( # Aggregate scores if report.per_episode: - scores = [ - eq.overall_score - for eq in report.per_episode - if eq.overall_score is not None - ] - report.overall_score = float(np.mean(scores)) if scores else 0.0 + scores = [eq.overall_score for eq in report.per_episode if eq.overall_score is not None] + report.overall_score = float(np.mean(scores)) if scores else None # Aggregate subscores all_subscore_keys = set() @@ -320,18 +382,12 @@ def analyze_dataset( all_subscore_keys.update(eq.subscores.keys()) for key in all_subscore_keys: - vals = [ - eq.subscores[key] - for eq in report.per_episode - if key in eq.subscores - ] + vals = [eq.subscores[key] for eq in report.per_episode if key in eq.subscores] if vals: report.subscores[key] = float(np.mean(vals)) # Generate flags and recommendations - report.flags, report.recommendations = _generate_recommendations( - report, self.config - ) + report.flags, report.recommendations = _generate_recommendations(report, self.config) return report @@ -353,21 +409,19 @@ def _generate_recommendations( if "gripper_chatter" in flagged: n = len(flagged["gripper_chatter"]) - flags.append( - f"{n} episodes with gripper chatter (rate > {config.chatter_threshold}/sec)" - ) + flags.append(f"{n} episodes with gripper chatter (rate > {config.chatter_threshold}/sec)") recs.append( - f"Review gripper threshold or filter: forge filter --max-gripper-chatter {config.chatter_threshold}" + "Review the gripper threshold, or filter: forge filter --exclude-flags gripper_chatter" ) if "mostly_static" in flagged: n = len(flagged["mostly_static"]) - flags.append(f"{n} episodes mostly static (>50% idle)") - recs.append("Run: forge filter --min-active-fraction 0.5") + flags.append(f"{n} episodes with sustained position holds (>50% observed time)") + recs.append("Review motion-pause events; waiting and contact may be intentional.") if "dead_actions" in flagged: n = len(flagged["dead_actions"]) - flags.append(f"{n} episodes with dead actions (>10% zero-action frames)") + flags.append(f"{n} episodes with zero/repeated commands (>10% of frames)") if "timestamp_jitter" in flagged: n = len(flagged["timestamp_jitter"]) @@ -381,6 +435,14 @@ def _generate_recommendations( n = len(flagged["saturated"]) flags.append(f"{n} episodes with action saturation (>30% at bounds)") + if "tracking_stall_candidate" in flagged: + flags.append( + f"{len(flagged['tracking_stall_candidate'])} episodes with position-tracking stall candidates" + ) + recs.append( + "Review command/state mapping, controller latency, and contact before rejecting data." + ) + if "psd_high_band_chatter" in flagged: n = len(flagged["psd_high_band_chatter"]) flags.append( @@ -388,7 +450,7 @@ def _generate_recommendations( f"(>{int(config.psd_high_flag * 100)}% energy above {config.psd_high_hz:g} Hz)" ) - if report.overall_score < 6.0 and report.num_episodes > 0: + if report.overall_score is not None and report.overall_score < 6.0 and report.num_episodes > 0: recs.append( f"Dataset quality is low ({report.overall_score:.1f}/10). Consider: forge filter --min-quality 6.0" ) diff --git a/forge/quality/config.py b/forge/quality/config.py index b2950a9..59ea191 100644 --- a/forge/quality/config.py +++ b/forge/quality/config.py @@ -6,6 +6,7 @@ from __future__ import annotations +import math from dataclasses import dataclass @@ -21,40 +22,59 @@ class QualityConfig: """ # ── Input / data access ── - gripper_dim: int = -1 + gripper_dim: int | None = None + gripper_dims: tuple[int, ...] | None = None fps: float = 30.0 action_bounds: tuple[float, float] | None = None + action_limits: tuple[tuple[float, float], ...] | None = None min_frames: int = 5 + # States supplied for motion analysis must be positions (not velocities). + # Scales have one positive value per original state column; thresholds below + # are in scaled units, so mixed radians/metres need explicit scales. + state_dims: tuple[int, ...] | None = None + state_scales: tuple[float, ...] | None = None + motion_speed_threshold: float = 1e-3 + event_min_duration_s: float = 0.5 + max_gap_factor: float = 2.5 + reversal_min_duration_s: float = 0.1 + + # Tracking is opt-in: absolute position commands and explicit (action,state) + # column pairs with compatible units. Never infer this from vector shape. + action_semantics: str = "unknown" + tracking_pairs: tuple[tuple[int, int], ...] | None = None + tracking_error_threshold: float = 0.05 + tracking_lag_s: float = 0.0 + # ── Metric parameters ── dead_action_eps: float = 1e-6 static_threshold_percentile: float = 95 - saturation_margin: float = 0.05 # 5% when inferring bounds, use 0.01 with --action-bounds + saturation_margin: float = 0.05 # 5% when inferring bounds, use 0.01 with --action-bounds # ── Flag thresholds (when to flag an episode) ── dead_fraction_flag: float = 0.10 - chatter_threshold: float = 2.0 # transitions/sec - jitter_warn_ratio: float = 0.1 # dt_std / dt_mean - saturation_flag: float = 0.30 # overall saturation fraction - saturation_dim_flag: float = 0.05 # per-dimension saturation - static_fraction_flag: float = 0.50 # fraction of episode that is static - entropy_low_flag: float = 0.20 # normalized entropy below this = repetitive - entropy_high_flag: float = 0.95 # normalized entropy above this = random - ldlj_flag: float = -25.0 # LDLJ below this = jerky + chatter_threshold: float = 2.0 # transitions/sec + jitter_warn_ratio: float = 0.1 # dt_std / dt_mean + saturation_flag: float = 0.30 # overall saturation fraction + saturation_dim_flag: float = 0.05 # per-dimension saturation + static_fraction_flag: float = 0.50 # fraction of episode that is static + entropy_low_flag: float = 0.20 # normalized entropy below this = repetitive + entropy_high_flag: float = 0.95 # normalized entropy above this = random + ldlj_flag: float = -25.0 # LDLJ below this = jerky # ── New metric parameters ── - psd_low_hz: float = 2.0 # upper edge of low band - psd_high_hz: float = 8.0 # lower edge of high band ("chatter") - psd_high_flag: float = 0.20 # >20% of action energy above high_hz = flagged - state_action_k: int = 5 # neighbors for state-conditioned variance + psd_low_hz: float = 2.0 # upper edge of low band + psd_high_hz: float = 8.0 # lower edge of high band ("chatter") + psd_high_flag: float = 0.20 # >20% of action energy above high_hz = flagged + state_action_k: int = 5 # neighbors for state-conditioned variance # ── Smoothness scoring (sigmoid) ── ldlj_sigmoid_center: float = -18.0 ldlj_sigmoid_scale: float = 4.0 # ── Entropy scoring (bell curve) ── - entropy_expected: float = 0.7 # expected normalized entropy - entropy_width: float = 0.3 # width of the bell curve + entropy_expected: float = 0.7 # expected normalized entropy + entropy_width: float = 0.3 # width of the bell curve # ── Composite score weights ── weight_smoothness: float = 0.25 @@ -64,3 +84,46 @@ class QualityConfig: weight_timestamp_regularity: float = 0.10 weight_action_saturation: float = 0.10 weight_action_diversity: float = 0.10 + + def __post_init__(self) -> None: + for name in ("fps", "event_min_duration_s", "max_gap_factor", "reversal_min_duration_s"): + value = getattr(self, name) + if not math.isfinite(value) or value <= 0: + raise ValueError(f"{name} must be finite and positive") + for name in ( + "motion_speed_threshold", + "tracking_error_threshold", + "tracking_lag_s", + "dead_action_eps", + ): + value = getattr(self, name) + if not math.isfinite(value) or value < 0: + raise ValueError(f"{name} must be finite and nonnegative") + if self.max_gap_factor <= 1: + raise ValueError("max_gap_factor must exceed 1") + if self.action_semantics not in {"unknown", "position", "velocity", "delta"}: + raise ValueError("action_semantics must be unknown, position, velocity, or delta") + if self.tracking_pairs is not None and ( + not self.tracking_pairs or self.action_semantics != "position" + ): + raise ValueError("tracking_pairs requires position semantics and at least one pair") + if self.gripper_dims is not None and self.gripper_dim is not None: + raise ValueError("Use gripper_dim or gripper_dims, not both") + if self.state_dims is not None and not self.state_dims: + raise ValueError("state_dims cannot be empty") + if self.state_scales is not None and ( + not self.state_scales or any(not math.isfinite(x) or x <= 0 for x in self.state_scales) + ): + raise ValueError("state_scales must be finite and positive") + if self.action_bounds is not None and self.action_limits is not None: + raise ValueError("Use action_bounds or action_limits, not both") + limits = ( + self.action_limits + if self.action_limits is not None + else (() if self.action_bounds is None else (self.action_bounds,)) + ) + if self.action_limits == (): + raise ValueError("action_limits cannot be empty") + for lo, hi in limits: + if not math.isfinite(lo) or not math.isfinite(hi) or lo >= hi: + raise ValueError("Action limits must be finite with lower < upper") diff --git a/forge/quality/diagnostics.py b/forge/quality/diagnostics.py new file mode 100644 index 0000000..dc3e51d --- /dev/null +++ b/forge/quality/diagnostics.py @@ -0,0 +1,182 @@ +"""Proprioception-only diagnostics. Events are evidence, not task verdicts. + +All motion uses position differences and real elapsed time. Long timestamp gaps +break events; no interpolation bridges missing observations. Tracking requires +explicit absolute-position action/state mappings. Cyclic motion is not a retry. +""" + +from __future__ import annotations + +import numpy as np + +from forge.quality.config import QualityConfig +from forge.quality.models import QualityEvent, StaticResult + + +def indices(values, width: int, name: str) -> list[int]: + result = [] + for value in values: + if not isinstance(value, (int, np.integer)) or not -width <= value < width: + raise ValueError(f"{name} index {value} is outside {width} columns") + result.append(int(value) % width) + if len(set(result)) != len(result): + raise ValueError(f"{name} contains duplicate columns") + return result + + +def runs(mask): + edges = np.diff(np.r_[False, mask, False].astype(int)) + return list(zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True)) + + +def interval_events(mask, timestamps, kind, min_duration, channels=()): + """A transition run [a,b) covers samples a through b inclusive.""" + out = [] + for a, b in runs(mask): + if timestamps[b] - timestamps[a] + 1e-9 >= min_duration: + out.append( + QualityEvent( + kind, + int(a), + int(b + 1), + float(timestamps[a]), + float(timestamps[b]), + list(channels), + ) + ) + return out + + +def diagnose(actions, states, timestamps, config: QualityConfig, fps: float): + """Return metrics, timestamped events, and applicability descriptions.""" + dt = np.diff(timestamps) + valid = (dt > 0) & (dt <= config.max_gap_factor / fps) + observed_s = float(dt[valid].sum()) + metrics = { + "valid_duration_s": observed_s, + "time_coverage": observed_s / float(dt.sum()) if dt.sum() > 0 else 0.0, + } + events = interval_events(~valid, timestamps, "timestamp_gap", 0.0) + status = {"tracking": "not_applicable: requires position semantics and explicit tracking_pairs"} + if actions is not None: + held = np.all(np.abs(np.diff(actions, axis=0)) <= config.dead_action_eps, axis=1) & valid + holds = interval_events(held, timestamps, "held_command", config.event_min_duration_s) + events.extend(holds) + metrics["held_command_fraction"] = ( + sum(e.duration_s for e in holds) / observed_s if observed_s else None + ) + static = None + if states is not None: + dims = indices( + config.state_dims if config.state_dims is not None else range(states.shape[1]), + states.shape[1], + "state_dims", + ) + scales = ( + np.ones(states.shape[1]) + if config.state_scales is None + else np.asarray(config.state_scales) + ) + if scales.shape != (states.shape[1],): + raise ValueError("state_scales must have one value per original state column") + position = states[:, dims] / scales[dims] + delta = np.diff(position, axis=0) + speed = np.max(np.abs(delta), axis=1) / dt + pauses = interval_events( + (speed <= config.motion_speed_threshold) & valid, + timestamps, + "motion_pause", + config.event_min_duration_s, + dims, + ) + events.extend(pauses) + fraction = sum(e.duration_s for e in pauses) / observed_s if observed_s else 0.0 + static = StaticResult( + fraction, + fraction > config.static_fraction_flag, + max((e.end_frame - e.start_frame for e in pauses), default=0), + [(e.start_frame, e.end_frame, e.duration_s) for e in pauses], + ) + metrics["path_length_scaled"] = float(np.linalg.norm(delta[valid], axis=1).sum()) + # A global efficiency ratio is undefined across gaps and for no motion. + length = metrics["path_length_scaled"] + metrics["net_to_path_ratio"] = ( + float(np.clip(np.linalg.norm(position[-1] - position[0]) / length, 0, 1)) + if valid.all() and length > 1e-12 + else None + ) + reversals = 0 + # Require sustained signs, with a deadband; reset the history at gaps. + for j, dim in enumerate(dims): + velocity = delta[:, j] / dt + sign = np.where(np.abs(velocity) > config.motion_speed_threshold, np.sign(velocity), 0) + previous = 0 + begin = 0 + while begin < len(sign): + if not valid[begin]: + previous = 0 + begin += 1 + continue + end = begin + 1 + while end < len(sign) and valid[end] and sign[end] == sign[begin]: + end += 1 + if sign[begin] and dt[begin:end].sum() + 1e-9 >= config.reversal_min_duration_s: + if previous and previous != sign[begin]: + reversals += 1 + events.append( + QualityEvent( + "direction_reversal", + begin, + end + 1, + float(timestamps[begin]), + float(timestamps[end]), + [dim], + ) + ) + previous = sign[begin] + begin = end + metrics["direction_reversal_count"] = reversals + status["motion"] = ( + "available: position-state assumption; pauses/reversals are not task failures" + ) + if actions is not None and config.action_semantics == "position" and config.tracking_pairs: + ad = indices([p[0] for p in config.tracking_pairs], actions.shape[1], "tracking action") + sd = indices([p[1] for p in config.tracking_pairs], states.shape[1], "tracking state") + # Last command available at the configured lag; never select a future sample. + command_index = ( + np.searchsorted(timestamps, timestamps - config.tracking_lag_s, side="right") - 1 + ) + available = command_index >= 0 + command_index = np.maximum(command_index, 0) + gaps = np.r_[0, np.cumsum(~valid)] + available &= gaps == gaps[command_index] + error = np.abs(actions[command_index][:, ad] - states[:, sd]) / scales[sd] + residual = np.max(error, axis=1) + if available.any(): + metrics["tracking_error_mean"] = float(np.mean(residual[available])) + metrics["tracking_error_p95"] = float(np.percentile(residual[available], 95)) + state_speed = ( + np.max(np.abs(np.diff(states[:, sd] / scales[sd], axis=0)), axis=1) / dt + ) + supported = valid & available[:-1] & available[1:] + mask = ( + supported + & (state_speed <= config.motion_speed_threshold) + & (np.minimum(residual[:-1], residual[1:]) > config.tracking_error_threshold) + ) + stalls = interval_events( + mask, timestamps, "tracking_stall_candidate", config.event_min_duration_s, sd + ) + events.extend(stalls) + duration = float(dt[supported].sum()) + metrics["tracking_stall_fraction"] = ( + sum(e.duration_s for e in stalls) / duration if duration else None + ) + status["tracking"] = ( + "available: mapped absolute position commands; contact may also cause mismatch" + ) + else: + status["tracking"] = "unavailable: lag exceeds observed timeline" + else: + status["motion"] = "unavailable: no valid position-state data" + return metrics, sorted(events, key=lambda e: (e.start_time_s, e.kind)), status, static diff --git a/forge/quality/metrics.py b/forge/quality/metrics.py index e64f616..2d0e96c 100644 --- a/forge/quality/metrics.py +++ b/forge/quality/metrics.py @@ -16,13 +16,14 @@ from __future__ import annotations +from typing import Any + import numpy as np from numpy.typing import NDArray from forge.quality.config import QualityConfig from forge.quality.models import StaticResult, TimestampResult - # ── Metric 1: Dead Action Detection ───────────────────────────── @@ -44,8 +45,11 @@ def dead_action_detection( # Zero actions is_zero = np.all(np.abs(actions) < eps, axis=1) - # Constant actions (same as first timestep) - is_constant = np.all(np.abs(actions - actions[0:1]) < eps, axis=1) + # Repeated neighboring commands, including plateaus later in the episode. + is_constant = np.zeros(len(actions), dtype=bool) + repeated = np.all(np.abs(np.diff(actions, axis=0)) <= eps, axis=1) + is_constant[:-1] |= repeated + is_constant[1:] |= repeated is_dead = is_zero | is_constant dead_fraction = float(np.mean(is_dead)) @@ -59,9 +63,7 @@ def dead_action_detection( # ── Metric 2: Log Dimensionless Jerk (LDLJ) ──────────────────── -def log_dimensionless_jerk( - positions: NDArray, dt: float -) -> float | None: +def log_dimensionless_jerk(positions: NDArray, dt: float) -> float | None: """Compute LDLJ smoothness metric. More negative = jerkier (higher jerk relative to velocity). @@ -112,6 +114,10 @@ def gripper_chatter( Tuple of (chatter_count, chatter_rate, is_chattery). """ gripper_dim = config.gripper_dim + if gripper_dim is None: + raise ValueError("Gripper dimension must be explicitly configured") + if not -actions.shape[1] <= gripper_dim < actions.shape[1]: + raise ValueError("Gripper dimension is outside action columns") gripper = actions[:, gripper_dim] # Auto-detect binarization threshold: midpoint of observed range @@ -150,9 +156,7 @@ def path_length(positions: NDArray) -> float: # ── Metric 5: Timestamp Regularity ────────────────────────────── -def timestamp_regularity( - timestamps: NDArray, expected_fps: float -) -> TimestampResult: +def timestamp_regularity(timestamps: NDArray, expected_fps: float) -> TimestampResult: """Analyze timestamp regularity and detect dropped frames. Args: @@ -187,9 +191,7 @@ def timestamp_regularity( # ── Metric 6: Action Range Saturation ─────────────────────────── -def action_saturation( - actions: NDArray, config: QualityConfig -) -> tuple[NDArray, float, list[int]]: +def action_saturation(actions: NDArray, config: QualityConfig) -> tuple[NDArray, float, list[int]]: """Detect timesteps where actions hit their min/max bounds. Args: @@ -199,7 +201,12 @@ def action_saturation( Returns: Tuple of (saturation_per_dim, overall_saturation, saturated_dims). """ - if config.action_bounds is not None: + if config.action_limits is not None: + limits = np.asarray(config.action_limits) + if limits.shape != (actions.shape[1], 2): + raise ValueError("action_limits must have one (lower, upper) pair per action column") + a_min, a_max = limits[:, 0], limits[:, 1] + elif config.action_bounds is not None: a_min = np.full(actions.shape[1], config.action_bounds[0]) a_max = np.full(actions.shape[1], config.action_bounds[1]) else: @@ -229,41 +236,22 @@ def action_saturation( # ── Metric 7: Static Episode Detection ────────────────────────── -def static_detection( - actions: NDArray, fps: float, config: QualityConfig -) -> StaticResult: - """Detect periods where the robot is not moving. +def static_detection(actions: NDArray, fps: float, config: QualityConfig) -> StaticResult: + """Detect sustained position holds (legacy argument name: actions). Args: - actions: Shape (T, D) action array. + actions: Shape (T, D) position-state array, not raw velocity commands. fps: Recording frequency (for duration calculation). config: Quality configuration. Returns: StaticResult with static segments and statistics. """ - action_norms = np.linalg.norm(actions, axis=1) - - pct_value = np.percentile(action_norms, config.static_threshold_percentile) - threshold = 0.01 * pct_value if pct_value > 1e-10 else 1e-6 + from forge.quality.diagnostics import diagnose - is_static = action_norms < threshold - static_fraction = float(np.mean(is_static)) - - # Find contiguous static runs - runs = _find_runs(is_static) - longest = max((end - start for start, end in runs), default=0) - - # Convert to segments with duration - dt = 1.0 / fps if fps > 0 else 1.0 - segments = [(s, e, (e - s) * dt) for s, e in runs] - - return StaticResult( - static_fraction=static_fraction, - is_mostly_static=static_fraction > config.static_fraction_flag, - longest_static_run=longest, - static_segments=segments, - ) + positions = np.asarray(actions, dtype=float) + _, _, _, result = diagnose(None, positions, np.arange(len(positions)) / fps, config, fps) + return result # ── Metric 8: Action Distribution Entropy ─────────────────────── @@ -341,9 +329,7 @@ def spectral_arc_length( return None velocity = np.gradient(positions, dt, axis=0) - speed = ( - np.linalg.norm(velocity, axis=1) if velocity.ndim == 2 else np.abs(velocity) - ) + speed = np.linalg.norm(velocity, axis=1) if velocity.ndim == 2 else np.abs(velocity) if speed.size < 4 or float(np.max(speed)) < 1e-12: return None diff --git a/forge/quality/models.py b/forge/quality/models.py index 0db23d2..e6bae58 100644 --- a/forge/quality/models.py +++ b/forge/quality/models.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from dataclasses import dataclass, field +from dataclasses import asdict, dataclass, field, fields from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING @@ -34,12 +34,35 @@ class StaticResult: static_segments: list[tuple[int, int, float]] +@dataclass +class QualityEvent: + """Review candidate on [start_frame, end_frame), with absolute data times.""" + + kind: str + start_frame: int + end_frame: int + start_time_s: float + end_time_s: float + channels: list[int] = field(default_factory=list) + + @property + def duration_s(self) -> float: + return self.end_time_s - self.start_time_s + + @dataclass class EpisodeQuality: """Quality metrics for a single episode.""" episode_id: str num_frames: int = 0 + scorer_version: str = "q-v2-proprio" + metric_status: dict[str, str] = field(default_factory=dict) + provenance: dict = field(default_factory=dict) + events: list[QualityEvent] = field(default_factory=list) + diagnostics: dict[str, float | int | None] = field(default_factory=dict) + grippers: dict[str, dict] = field(default_factory=dict) + observed_range_edge_fraction: float | None = None # Metric 1: Dead actions dead_fraction: float | None = None @@ -88,36 +111,53 @@ class EpisodeQuality: flags: list[str] = field(default_factory=list) # Video modality (Tier 0 pixel metrics) — populated only with --video. - video: "VideoQuality | None" = None + video: VideoQuality | None = None @property def is_flagged(self) -> bool: return len(self.flags) > 0 def to_dict(self) -> dict: - d: dict = { - "episode_id": self.episode_id, - "num_frames": self.num_frames, - "overall_score": self.overall_score, - "ldlj": self.ldlj, - "sparc": self.sparc, - "dead_fraction": self.dead_fraction, - "gripper_chatter_rate": self.gripper_chatter_rate, - "joint_path_length": self.joint_path_length, - "overall_saturation": self.overall_saturation, - "mean_entropy": self.mean_entropy, - "psd_high_fraction": self.psd_high_fraction, - "state_action_consistency": self.state_action_consistency, - "flags": self.flags, - } + d = asdict(self) + d.pop("video") if self.static is not None: d["static_fraction"] = self.static.static_fraction if self.timestamps is not None: d["jitter_ratio"] = self.timestamps.jitter_ratio if self.video is not None: d.update(self.video.to_flat_dict()) + d["video"] = self.video.to_dict() return d + @classmethod + def from_dict(cls, data: dict) -> EpisodeQuality: + nested = {"static", "timestamps", "video", "events"} + kwargs = { + f.name: data[f.name] for f in fields(cls) if f.name in data and f.name not in nested + } + kwargs.setdefault("scorer_version", "q-v1") + eq = cls(**kwargs) + if data.get("static") is not None: + values = dict(data["static"]) + values["static_segments"] = [tuple(x) for x in values["static_segments"]] + eq.static = StaticResult(**values) + elif data.get("static_fraction") is not None: + value = data["static_fraction"] + eq.static = StaticResult(value, value > 0.5, 0, []) + if data.get("timestamps") is not None: + eq.timestamps = TimestampResult(**data["timestamps"]) + eq.events = [QualityEvent(**event) for event in data.get("events", [])] + if eq.dead_ranges is not None: + eq.dead_ranges = [tuple(x) for x in eq.dead_ranges] + from forge.quality.video.models import VideoQuality + + eq.video = ( + VideoQuality.from_dict(data["video"]) + if data.get("video") is not None + else VideoQuality.from_flat_dict(data) + ) + return eq + @dataclass class QualityReport: @@ -125,7 +165,7 @@ class QualityReport: dataset_path: str num_episodes: int = 0 - overall_score: float = 0.0 + overall_score: float | None = None computed_at: str = "" subscores: dict[str, float] = field(default_factory=dict) @@ -142,7 +182,9 @@ def to_dict(self) -> dict: return { "dataset_path": self.dataset_path, "num_episodes": self.num_episodes, - "overall_score": round(self.overall_score, 2), + "overall_score": round(self.overall_score, 2) + if self.overall_score is not None + else None, "computed_at": self.computed_at, "subscores": {k: round(v, 3) for k, v in self.subscores.items()}, "per_episode": [ep.to_dict() for ep in self.per_episode], @@ -177,24 +219,6 @@ def from_dict(cls, data: dict) -> QualityReport: report.recommendations = data.get("recommendations", []) for ep_data in data.get("per_episode", []): - eq = EpisodeQuality( - episode_id=ep_data["episode_id"], - num_frames=ep_data.get("num_frames", 0), - overall_score=ep_data.get("overall_score"), - dead_fraction=ep_data.get("dead_fraction"), - ldlj=ep_data.get("ldlj"), - sparc=ep_data.get("sparc"), - gripper_chatter_rate=ep_data.get("gripper_chatter_rate"), - joint_path_length=ep_data.get("joint_path_length"), - overall_saturation=ep_data.get("overall_saturation"), - mean_entropy=ep_data.get("mean_entropy"), - psd_high_fraction=ep_data.get("psd_high_fraction"), - state_action_consistency=ep_data.get("state_action_consistency"), - flags=ep_data.get("flags", []), - ) - from forge.quality.video.models import VideoQuality - - eq.video = VideoQuality.from_flat_dict(ep_data) - report.per_episode.append(eq) + report.per_episode.append(EpisodeQuality.from_dict(ep_data)) return report diff --git a/forge/quality/video/README.md b/forge/quality/video/README.md index 8d57080..9a4f6f3 100644 --- a/forge/quality/video/README.md +++ b/forge/quality/video/README.md @@ -1,122 +1,103 @@ -# Forge Video Quality (Tier 0) +# Inspectable video quality -Pixel-statistic quality metrics for the **video modality**, computed on a -downscaled grayscale frame. This is **Tier 0** of the video extension: pure numpy, -no model, no GPU, and no new dependencies beyond whatever the dataset reader -already uses to decode frames. The metrics run in a single decode pass, so cost is -dominated by the decode, not the math. - -`forge quality` stays **proprio-only by default** — Tier 0 is opt-in behind -`--video`. - -## Metrics - -| Metric | What it catches | Flag | -|---|---|---| -| **Sharpness** (variance of Laplacian) | motion blur, defocus, compression mush | `blurry` | -| **Exposure** (per-frame luma + pixel clipping) | over/under-exposed clips | `over_exposed` / `under_exposed` | -| **Frozen frame** (consecutive-frame MAE) | encoder stalls, stuck streams, dead-static video | `frozen_frames` | -| **Colorfulness** (Hasler–Süsstrunk) | scene-diversity input (not flagged) | — | - -Metrics are computed **per camera**, then rolled up to worst-case episode-level -scalars for one-line filtering. - -## Usage - -### CLI +Video checks remain separate from the proprioception score. They describe image +health and observation integrity, not task success or training usefulness. +Results are versioned `video-v2-integrity`. ```bash -# Proprio + Tier 0 video -forge quality ./my_dataset --video - -# Subsample frames for speed (every 4th image-bearing frame) -forge quality ./my_dataset --video --video-stride 4 - -# Tune the analysis frame size and cap frames per camera -forge quality ./my_dataset --video --video-downscale 96 --video-max-frames 200 - -# Restrict to specific cameras -forge quality ./my_dataset --video --video-cameras observation.images.top - -# Export — video fields land in the same per-episode report rows -forge quality ./my_dataset --video --export report.json -``` - -### Library - -```python -from forge.quality.video import VideoQualityAnalyzer, VideoQualityConfig - -analyzer = VideoQualityAnalyzer(VideoQualityConfig(downscale=128, sample_stride=2)) -video = analyzer.analyze_episode(episode) # VideoQuality | None -print(video.min_sharpness, video.flags) -for name, cam in video.per_camera.items(): - print(name, cam.blurry_fraction, cam.frozen_fraction) -``` - -The `QualityAnalyzer` runs Tier 0 in the **same frame loop** as the proprio pass -(one decode per episode) when given a `video_config`: - -```python -from forge.quality import QualityAnalyzer -from forge.quality.video import VideoQualityConfig - -eq = QualityAnalyzer(video_config=VideoQualityConfig()).analyze_episode(episode) -eq.video # VideoQuality, attached to the EpisodeQuality -eq.flags # video flags are merged in alongside proprio flags +forge quality ./dataset --video --visualize --export quality.json +forge quality ./dataset --video --video-level motion --video-stride 4 \ + --video-max-frames 200 --visualize --export quality.json ``` -## Report integration - -`VideoQuality` attaches to `EpisodeQuality.video`. Headline scalars are flattened -into the per-episode report row (`video_min_sharpness`, `video_blurry_fraction`, -`video_frozen_fraction`, …), and video flags merge into `flags` — so they compose -with `forge filter` for free, both as flags and as numeric thresholds: - -```bash -# Flags -forge filter ./ds ./clean --exclude-flags blurry,frozen_frames - -# Numeric Tier 0 thresholds (trigger live video analysis automatically) -forge filter ./ds ./clean --min-sharpness 80 --max-frozen 0.5 -forge filter ./ds ./clean --max-overexposed 0.25 --max-underexposed 0.25 - -# Or read video fields straight from a report -forge quality ./ds --video --export report.json -forge filter ./ds ./clean --from-report report.json --min-sharpness 80 -``` - -`--min-motion` is a Tier 1 metric (see below) and auto-triggers optical-flow analysis. - -## Tier 1 — motion (`--video-level motion`) - -Classical optical flow (Farnebäck dense flow, opencv) on a small frame -(`motion_downscale`, default 64). Requires the `[video]` extra; without opencv the -metrics raise a helpful install error rather than a bare `ImportError`. - -| Metric | What it catches | Flag | -|---|---|---| -| **Motion magnitude** (mean flow, px/frame) | low-signal episodes where nothing moves | `no_motion` | -| **Motion smoothness** (pixel-space LDLJ of the global-motion path) | shaky / jittery video, frame-drop-then-jump | `shaky` | -| **Camera-vs-scene split** (global-affine fit; residual = object motion) | a moving wrist-cam vs an active scene | — | -| **Shot/cut detection** (histogram discontinuity **and** flow spike) | corrupted / concatenated episodes (a robot episode has no cuts) | `cut_detected` | - -`no_motion` is decided at the **episode** level (the most-active camera must be -below threshold), so one moving camera keeps the episode "in motion". A cut needs -**both** a luma-histogram drop and a flow spike relative to the episode's median, -so gradual content change isn't mistaken for a cut. Optical flow against a -blank/uniform frame is skipped (meaningless, and dodges occasional decoder black -frames). - -```bash -forge quality ./ds --video --video-level motion -forge filter ./ds ./clean --min-motion 0.1 # drop low-signal episodes -forge filter ./ds ./clean --exclude-flags cut_detected,shaky -``` - -## Roadmap - -- **Tier 2 (semantic)** — CLIP/SigLIP embeddings, semantic temporal coherence, - text–image alignment against the language instruction. `--video-level semantic`. - -See `VIDEO_QUALITY_PLAN.md` at the repo root for the full design. +## Integrity and frame-drop estimates + +Every episode observation is inspected for camera references and timestamps, +including observations skipped by image sampling or beyond the decode cap. +For each selected/declared camera, or a camera discovered during iteration: + +- `expected_frames`: episode observations on which camera references are expected. +- `present_frames`, `missing_frames`, `missing_fraction`: camera-reference availability. +- `decode_attempts`, `decode_failures`, `invalid_frames`: sampled decode outcomes. +- `num_frames`: valid decoded images included in pixel statistics. +- `sampled_out_frames`, `capped_frames`: intentionally unexamined images, never counted as failures. +- `decode_coverage`: valid decoded images divided by present references. This is analysis coverage, not a codec success rate; use failures/attempts for the latter. +- `timestamp_coverage`, `effective_fps`, `timestamp_jitter_ratio`: support and observed cadence of episode timestamps. +- `estimated_dropped_frames`, `estimated_drop_fraction`, `timestamp_gaps`, `max_frame_gap_s`: estimates from elapsed observation time and expected FPS. + +A gap exceeds 1.5 expected frame periods. Its estimated missing count is +`round(elapsed_seconds * expected_fps) - 1`. A `video_frame_drops` warning fires +when any gap represents at least 3 missing observations, at least 0.2 seconds of +missing time beyond one expected period, or when the estimated drop fraction +exceeds 5%. The fraction is missing estimates / (valid transitions + missing +estimates), and is withheld on incomplete/nonmonotonic timelines. + +Tune those alert criteria with `--video-drop-frames`, `--video-gap-seconds`, and +`--video-drop-fraction`. Episode FPS is used by default; `--video-fps` is an +explicit override. Python exposes `VideoQualityConfig.gap_factor` too. + +**These are observation-gap estimates, not verified camera capture drops.** +Forge generally receives episode timestamps rather than independent camera PTS. +Incorrect expected FPS or intentional lower-rate acquisition can also explain +gaps. Missing camera references are separate from missing timestamp intervals; +do not add those counts together. Asynchronous camera schemas need their own +availability expectations before treating missing references as faults. + +With no stored timestamps, FPS may supply an explicitly inferred event timebase, +but drop detection abstains. With incomplete timestamps, estimates cover only +supported pairs and are labeled partial. With no usable timebase, events retain +frame indices and unknown seconds. + +## Pixel and motion evidence + +Blur, exposure, near-identical images, cut candidates, missing references, decode +failures, invalid pixels, resolution changes, invalid timestamps, and time gaps +produce camera-scoped events. Frame indices are zero-based; `end_frame` is +exclusive. Time boundaries are the first and last supporting sample, so an +isolated sampled frame has a zero-length time span. + +Pixel events on strided input describe sampled evidence, not verified continuous +faults in the intervening images. Freeze durations use elapsed seconds when +available (`--video-freeze-seconds`, default 0.5); the legacy sampled-run threshold +is only a fallback without a timebase. A stationary scene can still look frozen. + +Gaps, camera absence, invalid data, decode errors, and resolution changes reset +temporal comparisons. Blank/low-texture observations also reset optical flow. +Motion magnitudes use actual elapsed time where supported; `mean_motion_px_s` +provides pixels/second on the downscaled analysis frame. The existing +`mean_motion` retains pixels per expected frame. Motion smoothness abstains when +flow sequences are interrupted or irregular rather than joining disjoint motion. + +Invalid/nonfinite pixels are excluded, never converted to black. Supported inputs +are uint8 or floating grayscale/RGB/RGBA intensity images; depth/integer formats +outside uint8 need separate metrics. The LeRobot v3 reader now raises on missing +requested video frames rather than substituting black/nearby/last-frame images. +Other readers that synthesize images can still hide failures before analysis. + +Whole-image thresholds remain heuristics. Downscaling, image texture, dark +backgrounds, noise, and camera placement affect them. Calibrate per camera and +analysis resolution; select cameras with `--video-cameras`. These changes do not +add task-region masks, learned visibility, or camera/proprioception clock alignment. + +## Reports and viewer + +Episode JSON retains the nested `video` result: per-camera metrics, flags, +events, configuration, timebase provenance, and availability. Flat `video_*` +rollups remain for compatibility. Older flat reports load as `video-v1` without +invented camera detail. `video_min_sharpness` now means the true minimum sampled +sharpness across cameras, rather than the minimum camera-average value; recalibrate +thresholds that depended on the old meaning. + +The viewer shows camera integrity summaries, camera-filtered event cards and +lanes, and click-to-seek playback. Missing time is labeled explicitly. A failed +image request displays an unavailable-frame placeholder. Video diagnostics do +not contribute to the numeric proprioception score. + +Existing worst-camera defect rollups remain, with their aggregation documented +in provenance. The `no_motion` rollup requires evaluable motion for every selected +camera, and still describes only the analyzed sample. Review camera relevance +and coverage before filtering episodes. + +## Performance + +See the [CPU benchmark and reproduction command](../../../docs/reports/README.md#video-cpu-benchmark). diff --git a/forge/quality/video/__init__.py b/forge/quality/video/__init__.py index b1899fc..a9efac4 100644 --- a/forge/quality/video/__init__.py +++ b/forge/quality/video/__init__.py @@ -16,11 +16,12 @@ from forge.quality.video.analyzer import VideoQualityAnalyzer from forge.quality.video.config import VideoQualityConfig -from forge.quality.video.models import CameraVideoQuality, VideoQuality +from forge.quality.video.models import CameraVideoQuality, VideoEvent, VideoQuality __all__ = [ "VideoQualityAnalyzer", "VideoQualityConfig", "VideoQuality", "CameraVideoQuality", + "VideoEvent", ] diff --git a/forge/quality/video/analyzer.py b/forge/quality/video/analyzer.py index 485cc58..af64c5b 100644 --- a/forge/quality/video/analyzer.py +++ b/forge/quality/video/analyzer.py @@ -1,86 +1,145 @@ -"""Video quality analyzer — Tier 0 (pixel statistics). +"""Camera-scoped diagnostics with explicit observation and decode coverage. -Streams frames through a per-camera accumulator so the whole episode is scored -in a single decode pass. The accumulator API (``new_accumulators`` / -``consume_frame`` / ``finalize``) lets the proprio analyzer share the same frame -loop instead of decoding the episode twice. +Timing describes episode observations, not independent camera capture PTS. +Unobserved samples never become trustworthy pixels or bridge motion estimates. """ from __future__ import annotations +from dataclasses import asdict + import numpy as np from forge.quality.video.config import VideoQualityConfig -from forge.quality.video.models import CameraVideoQuality, VideoQuality +from forge.quality.video.models import CameraVideoQuality, VideoEvent, VideoQuality from forge.quality.video.pixel import ( clip_fractions, colorfulness, frame_mae, laplacian_variance, - longest_true_run, prepare, ) class _CameraAccumulator: - """Per-camera streaming accumulator for Tier 0 (and optional Tier 1) metrics.""" - - def __init__(self, camera: str, config: VideoQualityConfig) -> None: - self.camera = camera - self.config = config - self.num_frames = 0 - self.width: int | None = None - self.height: int | None = None - - self._sharp: list[float] = [] - self._luma: list[float] = [] - self._over: list[bool] = [] - self._under: list[bool] = [] - self._color: list[float] = [] - self._frozen: list[bool] = [] - self._prev_gray: np.ndarray | None = None - - # Tier 1 motion state (used only when config.level == "motion") - self._motion_mag: list[float] = [] - self._global_vel: list[tuple[float, float]] = [] - self._scene_frac: list[float] = [] - self._hist_corr: list[float] = [] - self._prev_motion_u8: np.ndarray | None = None - self._motion_design: np.ndarray | None = None - - def update(self, img) -> None: - cfg = self.config - a = np.asarray(img) - if self.height is None and a.ndim >= 2: - self.height = int(a.shape[0]) - self.width = int(a.shape[1]) - - gray, rgb_small = prepare(a, cfg.downscale) - - self._sharp.append(laplacian_variance(gray)) - - luma = float(gray.mean()) - self._luma.append(luma) - frac_low, frac_high = clip_fractions(gray, cfg.clip_low, cfg.clip_high) - self._over.append(frac_high > cfg.clip_pixel_fraction) - self._under.append( - frac_low > cfg.clip_pixel_fraction or luma < cfg.dark_luma_flag + def __init__(self, camera, config, fps=None): + self.camera, self.config = camera, config + self.fps = config.expected_fps or fps + self.result = CameraVideoQuality(camera=camera) + self.result.provenance = { + "config": asdict(config), + "expected_fps": self.fps, + "timestamp_source": "episode observations, not camera capture PTS", + "pixel_time_support": "analyzed samples only", + } + self.attempts = 0 + self.records = [] # (ordinal, timestamp, outcome); metadata on ALL observations + self.samples = [] # (ordinal, time, sharpness, luma, over, under, color) + self.prev = None + self.motion_prev = None + self.motion = [] # (start, end, start_time, end_time, magnitude/frame, px/s, residual, hist, displacement) + self.frozen = [] + self._last_events = {} + self._continuous = True + + def reset(self): + self.prev = self.motion_prev = None + self._last_events.clear() + if self.samples: + self._continuous = False + + def event(self, kind, start, end, t0, t1, evidence=None, merge=False): + previous = self._last_events.get(kind) + if merge and previous: + previous.end_frame, previous.end_time_s = end, t1 + else: + previous = VideoEvent(kind, self.camera, start, end, t0, t1, evidence or {}) + self.result.events.append(previous) + self._last_events[kind] = previous + return previous + + def record(self, index, timestamp, outcome): + self.records.append((index, timestamp, outcome)) + self.attempts += outcome in ("decoded", "decode_failure", "invalid") + + def update(self, img, index=None, timestamp=None): + # Retain the internal direct-update API used by the original audit scripts. + index = len(self.samples) if index is None else index + if timestamp is None and self.fps: + timestamp = index / self.fps + cfg, cam = self.config, self.result + gray, rgb = prepare(img, cfg.downscale) # raises on invalid pixels/unsupported formats + shape = np.asarray(img).shape + if cam.height is not None and (cam.height, cam.width) != shape[:2]: + cam.resolution_changes += 1 + self.event("video_resolution_change", index, index + 1, timestamp, timestamp) + self.reset() + cam.height, cam.width = map(int, shape[:2]) + sharp, luma = laplacian_variance(gray), float(gray.mean()) + low, high = clip_fractions(gray, cfg.clip_low, cfg.clip_high) + over, under = ( + high > cfg.clip_pixel_fraction, + low > cfg.clip_pixel_fraction or luma < cfg.dark_luma_flag, ) - - if rgb_small is not None: - self._color.append(colorfulness(rgb_small)) - - if self._prev_gray is not None and self._prev_gray.shape == gray.shape: - self._frozen.append(frame_mae(gray, self._prev_gray) < cfg.frozen_mae) - self._prev_gray = gray - + self.samples.append( + ( + index, + timestamp, + sharp, + luma, + over, + under, + colorfulness(rgb) if rgb is not None else None, + ) + ) + cam.num_frames += 1 + for kind, flagged in ( + ("video_blur", sharp < cfg.sharpness_flag), + ("video_overexposure", over), + ("video_underexposure", under), + ): + if flagged: + previous = self._last_events.get(kind) + adjacent = ( + previous is not None and index - (previous.end_frame - 1) == cfg.sample_stride + ) + # With sparse analysis these spans identify sampled evidence only. + self.event( + kind, + index, + index + 1, + timestamp, + timestamp, + {"sample_stride": cfg.sample_stride, "support": "sampled pixels"}, + merge=adjacent, + ) + else: + self._last_events.pop(kind, None) + if self.prev is not None: + pi, pt, pg = self.prev + if pg.shape == gray.shape: + is_frozen = frame_mae(gray, pg) < cfg.frozen_mae + self.frozen.append((pi, index, pt, timestamp, is_frozen)) + if is_frozen: + self.event( + "video_frozen_candidate", + pi, + index + 1, + pt, + timestamp, + { + "sample_stride": cfg.sample_stride, + "interpretation": "near-identical samples; stationary scenes also qualify", + }, + merge=True, + ) + else: + self._last_events.pop("video_frozen_candidate", None) + self.prev = index, timestamp, gray if cfg.level == "motion": - self._update_motion(a) - - self.num_frames += 1 + self._update_motion(img, index, timestamp) - def _update_motion(self, img) -> None: - """Compute optical-flow metrics against the previous frame.""" + def _update_motion(self, img, index, timestamp): from forge.quality.video.motion import ( affine_design, camera_scene_split, @@ -90,189 +149,410 @@ def _update_motion(self, img) -> None: to_uint8_gray, ) - cfg = self.config - gray_m, _ = prepare(img, cfg.motion_downscale) - cur = to_uint8_gray(gray_m) - # Optical flow against a blank/uniform frame is meaningless (and dodges a - # decoder that hands back the occasional black frame): keep the last good - # frame as the reference and skip this pair entirely. - if float(cur.std()) < 1.0: + gray, _ = prepare(img, self.config.motion_downscale) + cur = to_uint8_gray(gray) + if cur.std() < 1: + self.motion_prev = None # Never bridge a blank/low-texture observation. + self._continuous = False return - prev = self._prev_motion_u8 - self._prev_motion_u8 = cur - if prev is None or prev.shape != cur.shape: + prev = self.motion_prev + self.motion_prev = index, timestamp, cur + if prev is None or prev[2].shape != cur.shape: return - - stride = max(1, cfg.sample_stride) - flow = dense_flow(prev, cur) - # Normalize by stride so magnitude is per original frame, not per sample. - self._motion_mag.append(float(flow_magnitude(flow).mean()) / stride) - self._global_vel.append((float(flow[..., 0].mean()), float(flow[..., 1].mean()))) - self._hist_corr.append(histogram_correlation(prev, cur)) - - if self._motion_design is None: - self._motion_design = affine_design(cur.shape[0], cur.shape[1]) - resid, total = camera_scene_split(flow, self._motion_design) - self._scene_frac.append(resid / (total + 1e-6)) - - def finalize(self) -> CameraVideoQuality: - cfg = self.config - cam = CameraVideoQuality( - camera=self.camera, - num_frames=self.num_frames, - width=self.width, - height=self.height, + pi, pt, pg = prev + elapsed = timestamp - pt if timestamp is not None and pt is not None else None + flow = dense_flow(pg, cur) + magnitude = float(flow_magnitude(flow).mean()) + resid, total = camera_scene_split(flow, affine_design(*cur.shape)) + frames = elapsed * self.fps if elapsed is not None and self.fps else index - pi + self.motion.append( + ( + pi, + index, + pt, + timestamp, + magnitude / frames, + magnitude / elapsed if elapsed is not None else None, + resid / (total + 1e-6), + histogram_correlation(pg, cur), + (float(flow[..., 0].mean()), float(flow[..., 1].mean())), + ) ) - if not self._sharp: - return cam - - sharp = np.asarray(self._sharp) - cam.mean_sharpness = float(sharp.mean()) - cam.min_sharpness = float(sharp.min()) - cam.blurry_fraction = float(np.mean(sharp < cfg.sharpness_flag)) - - cam.mean_luma = float(np.mean(self._luma)) - cam.overexposed_fraction = float(np.mean(self._over)) - cam.underexposed_fraction = float(np.mean(self._under)) - - if self._color: - cam.mean_colorfulness = float(np.mean(self._color)) - - if self._frozen: - cam.frozen_fraction = float(np.mean(self._frozen)) - cam.longest_frozen_run = longest_true_run(self._frozen) - - # ── Tier 0 flags ── - if cam.blurry_fraction > cfg.blurry_fraction_flag: - cam.flags.append("blurry") - if cam.overexposed_fraction > cfg.exposure_flag: - cam.flags.append("over_exposed") - if cam.underexposed_fraction > cfg.exposure_flag: - cam.flags.append("under_exposed") - if ( - cam.longest_frozen_run > cfg.frozen_run_flag - or (cam.frozen_fraction is not None and cam.frozen_fraction > cfg.frozen_fraction_flag) - ): - cam.flags.append("frozen_frames") - # ── Tier 1 motion ── - if self._motion_mag: - mags = np.asarray(self._motion_mag) - cam.mean_motion = float(mags.mean()) - cam.scene_motion_fraction = float(np.mean(self._scene_frac)) - # A cut needs both a histogram discontinuity and a flow spike relative - # to the episode's own motion — neither alone is enough. - corr = np.asarray(self._hist_corr) - median_mag = float(np.median(mags)) if mags.size else 0.0 - # Spike must clear both a relative (×median) and an absolute floor. - spike_thresh = max(cfg.cut_flow_factor * median_mag, cfg.cut_flow_min) - spike = mags > spike_thresh - cam.cut_count = int(np.count_nonzero((corr < cfg.cut_hist_corr) & spike)) - if len(self._global_vel) >= 3: - # LDLJ of the cumulative global-motion path (camera trajectory). - from forge.quality.metrics import log_dimensionless_jerk - - path = np.cumsum(np.asarray(self._global_vel), axis=0) - cam.motion_smoothness = log_dimensionless_jerk(path, dt=1.0) - - # 'shaky' and 'cut_detected' are per-camera; 'no_motion' is decided at - # the episode level (rollup), since one moving camera means the - # episode is not motionless. - if ( - cam.motion_smoothness is not None - and cam.motion_smoothness < cfg.motion_smoothness_flag + def finalize(self): + cam, cfg = self.result, self.config + n = len(self.records) + if n: + counts = { + kind: sum(r[2] == kind for r in self.records) + for kind in ("missing", "decoded", "decode_failure", "invalid", "stride", "cap") + } + cam.expected_frames = n + cam.missing_frames = counts["missing"] + cam.present_frames = n - cam.missing_frames + cam.decode_failures, cam.invalid_frames = counts["decode_failure"], counts["invalid"] + cam.decode_attempts = counts["decoded"] + cam.decode_failures + cam.invalid_frames + cam.sampled_out_frames, cam.capped_frames = counts["stride"], counts["cap"] + cam.missing_fraction = cam.missing_frames / n + cam.decode_coverage = ( + cam.num_frames / cam.present_frames if cam.present_frames else None + ) + # Collapse integrity failures only across adjacent observation ordinals. + for outcome, kind in ( + ("missing", "video_camera_missing"), + ("decode_failure", "video_decode_failure"), + ("invalid", "video_invalid_pixels"), + ): + active = None + for index, timestamp, status in self.records: + if status == outcome: + if active is not None: + active.end_frame, active.end_time_s = index + 1, timestamp + active.evidence["observations"] += 1 + else: + active = VideoEvent( + kind, + self.camera, + index, + index + 1, + timestamp, + timestamp, + {"observations": 1}, + ) + cam.events.append(active) + else: + active = None + for count, flag in ( + (cam.missing_frames, "video_camera_missing"), + (cam.decode_failures, "video_decode_failure"), + (cam.invalid_frames, "video_invalid_pixels"), + (cam.resolution_changes, "video_resolution_change"), ): - cam.flags.append("shaky") - if cam.cut_count and cam.cut_count > 0: + if count: + cam.flags.append(flag) + cam.metric_status["coverage"] = ( + "decode_coverage = valid decoded / present references; stride and cap are reported separately" + ) + cam.metric_status["pixels"] = ( + "available: sampled whole-image heuristics; calibrate per camera and resolution" + if self.samples + else "unavailable: no valid decoded samples" + ) + cam.metric_status["frozen"] = "near-identical sampled images; not proof of an encoder stall" + cam.metric_status["motion"] = ( + "not_requested" + if cfg.level != "motion" + else ( + "available: approximate global-affine decomposition" + if self.motion + else "unavailable: no supported textured frame pairs" + ) + ) + cam.metric_status["motion_smoothness"] = ( + "unavailable: insufficient, interrupted, or irregular flow sequence" + ) + if self.samples: + sharp = [s[2] for s in self.samples] + cam.mean_sharpness, cam.min_sharpness = float(np.mean(sharp)), float(min(sharp)) + cam.blurry_fraction = float(np.mean(np.asarray(sharp) < cfg.sharpness_flag)) + cam.mean_luma = float(np.mean([s[3] for s in self.samples])) + cam.overexposed_fraction, cam.underexposed_fraction = [ + float(np.mean([s[i] for s in self.samples])) for i in (4, 5) + ] + colors = [s[6] for s in self.samples if s[6] is not None] + cam.mean_colorfulness = float(np.mean(colors)) if colors else None + for value, threshold, flag in ( + (cam.blurry_fraction, cfg.blurry_fraction_flag, "blurry"), + (cam.overexposed_fraction, cfg.exposure_flag, "over_exposed"), + (cam.underexposed_fraction, cfg.exposure_flag, "under_exposed"), + ): + if value > threshold: + cam.flags.append(flag) + if self.frozen: + cam.frozen_fraction = float(np.mean([r[4] for r in self.frozen])) + run, last_end = 0, None + for start, end, _, _, frozen in self.frozen: + run = (run + 1 if last_end == start else 1) if frozen else 0 + cam.longest_frozen_run = max(cam.longest_frozen_run, run) + last_end = end + spans = [e for e in cam.events if e.kind == "video_frozen_candidate"] + durations = [ + e.end_time_s - e.start_time_s + for e in spans + if e.start_time_s is not None and e.end_time_s is not None + ] + cam.max_frozen_duration_s = ( + max(durations, default=0.0) if any(s[1] is not None for s in self.samples) else None + ) + long = ( + cam.max_frozen_duration_s >= cfg.frozen_duration_s + if cam.max_frozen_duration_s is not None + else cam.longest_frozen_run > cfg.frozen_run_flag + ) + if long or cam.frozen_fraction > cfg.frozen_fraction_flag: + cam.flags.append("frozen_frames") + if self.motion: + mags = np.array([r[4] for r in self.motion]) + cam.mean_motion = float(mags.mean()) + per_second = [r[5] for r in self.motion if r[5] is not None] + cam.mean_motion_px_s = float(np.mean(per_second)) if per_second else None + cam.scene_motion_fraction = float(np.mean([r[6] for r in self.motion])) + threshold = max(cfg.cut_flow_factor * float(np.median(mags)), cfg.cut_flow_min) + cuts = [r for r in self.motion if r[7] < cfg.cut_hist_corr and r[4] > threshold] + cam.cut_count = len(cuts) + for r in cuts: + cam.events.append( + VideoEvent("video_cut_candidate", self.camera, r[0], r[1] + 1, r[2], r[3]) + ) + if cuts: cam.flags.append("cut_detected") + times = [r[3] - r[2] for r in self.motion if r[2] is not None and r[3] is not None] + regular = not times or ( + len(times) == len(self.motion) and np.std(times) / np.mean(times) < 0.1 + ) + if self._continuous and regular and len(self.motion) >= 3: + from forge.quality.metrics import log_dimensionless_jerk + path = np.cumsum([r[8] for r in self.motion], axis=0) + cam.motion_smoothness = log_dimensionless_jerk( + path, dt=float(np.mean(times)) if times else 1.0 + ) + cam.metric_status["motion_smoothness"] = ( + "available: image-space heuristic, not isolated physical camera motion" + if cam.motion_smoothness is not None + else "unavailable: degenerate image motion" + ) + if ( + cam.motion_smoothness is not None + and cam.motion_smoothness < cfg.motion_smoothness_flag + ): + cam.flags.append("shaky") + cam.events.sort(key=lambda e: (e.start_frame, e.kind)) return cam -class VideoQualityAnalyzer: - """Computes Tier 0 video quality metrics for an episode. - - Usage:: +class _Accumulators(dict): + def __init__(self, fps): + super().__init__() + self.fps = fps + self.history = [] + self.all_stored = True + self.any_stored = False - analyzer = VideoQualityAnalyzer(VideoQualityConfig(downscale=128)) - video = analyzer.analyze_episode(episode) # VideoQuality | None - """ - def __init__(self, config: VideoQualityConfig | None = None, **kwargs) -> None: +class VideoQualityAnalyzer: + def __init__(self, config=None, **kwargs): self.config = config if config is not None else VideoQualityConfig(**kwargs) - def new_accumulators(self) -> dict[str, _CameraAccumulator]: - return {} - - def consume_frame( - self, - frame, - accums: dict[str, _CameraAccumulator], - frame_index: int, - ) -> None: - """Feed one frame's images into the per-camera accumulators. - - ``frame_index`` is the running index over image-bearing frames, used for - striding. Decode failures on a single camera are skipped, not fatal. - """ + def new_accumulators(self, fps=None, cameras=None): + fps = self.config.expected_fps or fps + if fps is not None and (not np.isfinite(fps) or fps <= 0): + raise ValueError("Video expected FPS must be finite and positive") + accums = _Accumulators(fps) + for name in self.config.cameras if self.config.cameras is not None else (cameras or []): + accums[name] = _CameraAccumulator(name, self.config, fps) + return accums + + def consume_frame(self, frame, accums, frame_index): + """Observe EVERY episode frame, including those without camera entries.""" cfg = self.config - if not frame.images: - return - if frame_index % max(1, cfg.sample_stride) != 0: - return - - for name, lazy in frame.images.items(): + raw_time = frame.timestamp + timestamp = float(raw_time) if raw_time is not None and np.isfinite(raw_time) else None + previous = accums.history[-1] if accums.history else None + # Only infer times when missing; integrity estimates below require stored time. + display_time = ( + timestamp if timestamp is not None else frame_index / accums.fps if accums.fps else None + ) + for name in frame.images: if cfg.cameras is not None and name not in cfg.cameras: continue - acc = accums.get(name) - if acc is None: - acc = _CameraAccumulator(name, cfg) - accums[name] = acc - if cfg.max_frames and acc.num_frames >= cfg.max_frames: + if name not in accums: + acc = accums[name] = _CameraAccumulator(name, cfg, accums.fps) + for i, t, _ in accums.history: + acc.record(i, t, "missing") + accums.history.append((frame_index, display_time, timestamp)) + accums.all_stored &= timestamp is not None + accums.any_stored |= timestamp is not None + for name, acc in accums.items(): + cam = acc.result + cam.provenance["timebase"] = ( + "stored_episode_timestamps" if accums.all_stored else "missing_or_inferred_times" + ) + bad_time = raw_time is not None and timestamp is None + gap = False + if previous is not None: + if timestamp is None or previous[2] is None: + bad_time = True + else: + dt = timestamp - previous[2] + bad_time = dt <= 0 + if accums.fps and dt > cfg.gap_factor / accums.fps: + gap = True + if bad_time: + # Entirely timestamp-free data can still use a declared FPS grid. + entirely_absent = not accums.any_stored and raw_time is None + if not entirely_absent: + cam.timestamp_invalid_count += 1 + if "video_invalid_timestamps" not in cam.flags: + cam.flags.append("video_invalid_timestamps") + acc.event("video_invalid_timestamps", frame_index, frame_index + 1, None, None) + if not entirely_absent: + acc.reset() + if gap: + acc.reset() + if frame.images.get(name) is None: + acc.record(frame_index, display_time, "missing") + acc.reset() + continue + if frame_index % cfg.sample_stride: + acc.record(frame_index, display_time, "stride") + continue + if cfg.max_frames and acc.attempts >= cfg.max_frames: + acc.record(frame_index, display_time, "cap") + acc.reset() continue try: - img = lazy.load() + img = frame.images[name].load() except Exception: + acc.record(frame_index, display_time, "decode_failure") + acc.reset() + continue + try: + acc.update(img, frame_index, display_time) + except (ValueError, TypeError, IndexError): + acc.record(frame_index, display_time, "invalid") + acc.reset() continue - acc.update(img) + acc.record(frame_index, display_time, "decoded") + if bad_time and not entirely_absent: + acc.reset() - def finalize(self, accums: dict[str, _CameraAccumulator]) -> VideoQuality | None: + def finalize(self, accums): if not accums: return None - per_camera = {name: acc.finalize() for name, acc in accums.items()} - return _build_rollup(per_camera, self.config) - - def analyze_episode(self, episode) -> VideoQuality | None: - """Score an episode's camera streams in a single pass. - - Returns None if the episode carries no (selected) camera images. - """ - accums = self.new_accumulators() - idx = -1 - for frame in episode.frames(): - if frame.images: - idx += 1 - self.consume_frame(frame, accums, idx) + cameras = {name: acc.finalize() for name, acc in accums.items()} + for cam in cameras.values(): + _finalize_timing(cam, accums.history, accums.fps, self.config) + return _build_rollup(cameras, self.config) + + def analyze_episode(self, episode): + accums = self.new_accumulators(episode.fps, episode.cameras) + for index, frame in enumerate(episode.frames()): + self.consume_frame(frame, accums, index) return self.finalize(accums) +def _finalize_timing(cam, history, fps, config): + """Use the full metadata timeline, including time before a camera first appears.""" + cam.events = [e for e in cam.events if e.kind != "video_frame_gap"] + cam.flags = [f for f in cam.flags if f != "video_frame_drops"] + cam.timestamp_gaps = 0 + cam.max_frame_gap_s = None + stored = sum(t is not None for _, _, t in history) + cam.timestamp_coverage = stored / len(history) if history else None + complete = stored == len(history) and len(history) > 1 + positive = [] + invalid_indices = set() + dropped = 0 + significant = False + for previous, current in zip(history, history[1:]): + i, _, t0 = previous + j, _, t1 = current + if t0 is None or t1 is None or t1 <= t0: + complete = False + if stored: + invalid_indices.add(j) + continue + dt = t1 - t0 + positive.append(dt) + if fps and dt > config.gap_factor / fps: + count = max(0, int(round(dt * fps)) - 1) + dropped += count + cam.timestamp_gaps += 1 + cam.max_frame_gap_s = max(cam.max_frame_gap_s or 0.0, dt) + large = ( + count >= config.significant_drop_frames + or dt - 1 / fps >= config.significant_gap_s - 1e-9 + ) + significant |= large + cam.events.append( + VideoEvent( + "video_frame_gap", + cam.camera, + i, + j + 1, + t0, + t1, + { + "estimated_missing_observations": count, + "gap_s": dt, + "significant": large, + "source": "episode timestamp gap; not independent camera PTS", + }, + ) + ) + if invalid_indices: + existing = {e.start_frame for e in cam.events if e.kind == "video_invalid_timestamps"} + for index in sorted(invalid_indices - existing): + cam.events.append( + VideoEvent("video_invalid_timestamps", cam.camera, index, index + 1, None, None) + ) + cam.timestamp_invalid_count = len(existing | invalid_indices) + if "video_invalid_timestamps" not in cam.flags: + cam.flags.append("video_invalid_timestamps") + if positive: + cam.effective_fps = 1 / float(np.mean(positive)) + cam.timestamp_jitter_ratio = float(np.std(positive) / np.mean(positive)) + cam.estimated_dropped_frames = dropped if fps and len(positive) else None + cam.estimated_drop_fraction = dropped / (len(positive) + dropped) if complete and fps else None + if significant or ( + cam.estimated_drop_fraction is not None + and cam.estimated_drop_fraction > config.drop_fraction_flag + ): + cam.flags.append("video_frame_drops") + cam.metric_status["frame_drops"] = ( + "available: estimated missing observation intervals from episode timestamps and declared FPS; uniform rate mismatch can also explain gaps; camera capture drops may be invisible" + if complete and fps + else "partial: counts are a lower bound over supported timestamp pairs; unknown intervals omitted" + if fps and positive + else "unavailable: at least two stored timestamps and declared FPS required" + ) + if (stored and not complete) or cam.timestamp_invalid_count: + for e in cam.events: + if e.kind != "video_frame_gap": + e.start_time_s = e.end_time_s = None + cam.provenance["timebase"] = ( + "stored_episode_timestamps" + if complete + else "inferred_from_fps" + if not stored and fps and not cam.timestamp_invalid_count + else "incomplete_or_unknown" + ) + cam.provenance["camera_reference_expectation"] = ( + "selected or discovered cameras are expected on each episode observation; asynchronous schemas require interpretation" + ) + cam.events.sort(key=lambda e: (e.start_frame, e.kind)) + + def _build_rollup( per_camera: dict[str, CameraVideoQuality], config: VideoQualityConfig, ) -> VideoQuality: """Combine per-camera results into episode-level worst-case rollups.""" - vq = VideoQuality(per_camera=per_camera) + vq = VideoQuality( + per_camera=per_camera, + provenance={ + "config": asdict(config), + "aggregation": "worst-camera defect fractions; inspect camera relevance before filtering", + }, + ) def _vals(attr: str) -> list[float]: - return [ - getattr(c, attr) - for c in per_camera.values() - if getattr(c, attr) is not None - ] + return [getattr(c, attr) for c in per_camera.values() if getattr(c, attr) is not None] mean_sharp = _vals("mean_sharpness") if mean_sharp: - vq.min_sharpness = float(min(mean_sharp)) + vq.min_sharpness = float(min(_vals("min_sharpness"))) vq.mean_sharpness = float(np.mean(mean_sharp)) blurry = _vals("blurry_fraction") @@ -319,7 +599,11 @@ def _vals(attr: str) -> list[float]: # 'no_motion' is episode-level: flag only if the most-active camera is below # the threshold (so a single moving camera keeps the episode "in motion"). - if vq.mean_motion is not None and vq.mean_motion < config.motion_low_flag: + if ( + len(motion) == len(per_camera) + and vq.mean_motion is not None + and vq.mean_motion < config.motion_low_flag + ): if "no_motion" not in seen: vq.flags.append("no_motion") diff --git a/forge/quality/video/config.py b/forge/quality/video/config.py index 01bdf4d..ad281d2 100644 --- a/forge/quality/video/config.py +++ b/forge/quality/video/config.py @@ -1,18 +1,18 @@ """Configuration for video (pixel) quality metrics. -Tier 0 only for now — pure pixel statistics computed on a downscaled -grayscale frame. All tunable thresholds live here, mirroring +Pixel and optical-flow checks with explicit observation integrity. All tunable thresholds live here, mirroring ``forge/quality/config.py``. """ from __future__ import annotations +import math from dataclasses import dataclass @dataclass class VideoQualityConfig: - """Configuration for Tier 0 video quality analysis. + """Configuration for pixel, motion, and video integrity analysis. Groups: Decode / sampling: how frames are pulled and downscaled before metrics. @@ -22,46 +22,103 @@ class VideoQualityConfig: """ # ── Tier selection ── - level: str = "pixel" # "pixel" (Tier 0) | "motion" (Tier 0 + Tier 1) + level: str = "pixel" # "pixel" (Tier 0) | "motion" (Tier 0 + Tier 1) # ── Decode / frame sampling ── - downscale: int = 128 # longest side (px) of the analysis frame - sample_stride: int = 1 # analyze every Nth frame that carries images - max_frames: int = 0 # cap analyzed frames per camera (0 = no cap) - cameras: list[str] | None = None # restrict to these camera names (None = all) + downscale: int = 128 # longest side (px) of the analysis frame + sample_stride: int = 1 # analyze every Nth episode observation + max_frames: int = 0 # cap decode attempts per camera (0 = no cap) + cameras: list[str] | None = None # restrict to these camera names (None = all) # ── Sharpness (variance of Laplacian, on 0–255 grayscale) ── - sharpness_flag: float = 100.0 # per-frame var-of-Laplacian below this = blurry - blurry_fraction_flag: float = 0.30 # >30% blurry frames => 'blurry' flag + sharpness_flag: float = 100.0 # per-frame var-of-Laplacian below this = blurry + blurry_fraction_flag: float = 0.30 # >30% blurry frames => 'blurry' flag # ── Exposure (per-frame luma + pixel clipping, 0–255) ── # Clipping means detail lost at the sensor floor/ceiling, where pixels peg at # 0 / 255 — NOT merely a dark or bright scene. So the thresholds sit at the # extremes: a uniformly bright (e.g. white-background) frame is not clipped # unless its highlights actually saturate. - clip_low: float = 4.0 # luma <= this counts as crushed-black - clip_high: float = 254.0 # luma >= this counts as blown-white - clip_pixel_fraction: float = 0.20 # frame is clipped if >20% of pixels are clipped - dark_luma_flag: float = 32.0 # mean luma below this = underexposed frame - exposure_flag: float = 0.25 # >25% over/under-exposed frames => exposure flag + clip_low: float = 4.0 # luma <= this counts as crushed-black + clip_high: float = 254.0 # luma >= this counts as blown-white + clip_pixel_fraction: float = 0.20 # frame is clipped if >20% of pixels are clipped + dark_luma_flag: float = 32.0 # mean luma below this = underexposed frame + exposure_flag: float = 0.25 # >25% over/under-exposed frames => exposure flag # ── Frozen frame / encoder stall (consecutive-frame MAE, 0–255) ── # A stalled encoder or duplicated/held frame is ~pixel-identical to its # predecessor (MAE ≈ 0). A slow-but-moving scene has small-yet-nonzero MAE # and is a Tier 1 (optical-flow / low-motion) concern, not a frozen frame — # so the bar is near-zero, detecting near-exact duplicates only. - frozen_mae: float = 0.1 # MAE below this between consecutive frames = frozen - frozen_run_flag: int = 10 # longest frozen run above this => 'frozen_frames' - frozen_fraction_flag: float = 0.50 # or >50% frozen transitions => 'frozen_frames' + frozen_mae: float = 0.1 # MAE below this between consecutive frames = frozen + frozen_run_flag: int = 10 # longest frozen run above this => 'frozen_frames' + frozen_fraction_flag: float = 0.50 # or >50% frozen transitions => 'frozen_frames' # ── Tier 1: motion (Farnebäck dense optical flow; opencv) ── - motion_downscale: int = 64 # flow is O(pixels); analyze on a small frame - motion_low_flag: float = 0.05 # mean flow (px/frame) below this => 'no_motion' + motion_downscale: int = 64 # flow is O(pixels); analyze on a small frame + motion_low_flag: float = 0.05 # mean flow (px/frame) below this => 'no_motion' motion_smoothness_flag: float = -28.0 # pixel-space LDLJ below this => 'shaky' # A shot cut needs a luma-histogram discontinuity AND a flow spike that clears # BOTH a relative (×median) and an absolute floor — so a gradual content change # isn't a cut, and a mere exposure/lighting jump on an otherwise-static camera # (small absolute flow, large only relative to a near-zero median) isn't either. - cut_hist_corr: float = 0.3 # histogram correlation below this, AND ... - cut_flow_factor: float = 5.0 # ... flow above this × the episode median, AND ... - cut_flow_min: float = 1.5 # ... flow above this absolute floor (px/frame) + cut_hist_corr: float = 0.3 # histogram correlation below this, AND ... + cut_flow_factor: float = 5.0 # ... flow above this × the episode median, AND ... + cut_flow_min: float = 1.5 # ... flow above this absolute floor (px/frame) + + # Integrity uses episode observation timestamps, not independently measured camera PTS. + expected_fps: float | None = None # overrides episode FPS when explicitly supplied + gap_factor: float = 1.5 + drop_fraction_flag: float = 0.05 + significant_drop_frames: int = 3 + significant_gap_s: float = 0.2 # missing time beyond the expected one-frame interval + frozen_duration_s: float = 0.5 # requires known elapsed time + + def __post_init__(self) -> None: + if self.level not in {"pixel", "motion"}: + raise ValueError("video level must be pixel or motion") + for name in ("downscale", "motion_downscale", "sample_stride", "significant_drop_frames"): + value = getattr(self, name) + if not isinstance(value, int) or isinstance(value, bool) or value < 1: + raise ValueError(f"{name} must be a positive integer") + if not isinstance(self.max_frames, int) or self.max_frames < 0: + raise ValueError("max_frames must be a nonnegative integer") + for name in ("gap_factor", "significant_gap_s", "frozen_duration_s"): + if not math.isfinite(getattr(self, name)) or getattr(self, name) <= 0: + raise ValueError(f"{name} must be finite and positive") + if self.gap_factor <= 1: + raise ValueError("gap_factor must exceed 1") + if self.expected_fps is not None and ( + not math.isfinite(self.expected_fps) or self.expected_fps <= 0 + ): + raise ValueError("expected_fps must be finite and positive") + for name in ( + "blurry_fraction_flag", + "clip_pixel_fraction", + "exposure_flag", + "frozen_fraction_flag", + "drop_fraction_flag", + ): + if not math.isfinite(getattr(self, name)) or not 0 <= getattr(self, name) <= 1: + raise ValueError(f"{name} must be in [0, 1]") + for name in ( + "sharpness_flag", + "frozen_mae", + "motion_low_flag", + "cut_flow_factor", + "cut_flow_min", + ): + if not math.isfinite(getattr(self, name)) or getattr(self, name) < 0: + raise ValueError(f"{name} must be finite and nonnegative") + if not 0 <= self.clip_low < self.clip_high <= 255 or not 0 <= self.dark_luma_flag <= 255: + raise ValueError("exposure thresholds must be ordered within [0, 255]") + if not math.isfinite(self.motion_smoothness_flag) or not -1 <= self.cut_hist_corr <= 1: + raise ValueError( + "motion thresholds must be finite and histogram correlation in [-1, 1]" + ) + if not isinstance(self.frozen_run_flag, int) or self.frozen_run_flag < 0: + raise ValueError("frozen_run_flag must be a nonnegative integer") + if self.cameras is not None and ( + not self.cameras or len(set(self.cameras)) != len(self.cameras) + ): + raise ValueError("cameras must be nonempty and unique") diff --git a/forge/quality/video/models.py b/forge/quality/video/models.py index ce452f1..23a8951 100644 --- a/forge/quality/video/models.py +++ b/forge/quality/video/models.py @@ -9,7 +9,24 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import asdict, dataclass, field, fields + + +@dataclass +class VideoEvent: + """Camera-scoped observation evidence; frame end is exclusive. + + Times are None when neither timestamps nor FPS support a timebase. + Sparse pixel events describe analyzed samples, not unseen intervening frames. + """ + + kind: str + camera: str + start_frame: int + end_frame: int + start_time_s: float | None + end_time_s: float | None + evidence: dict = field(default_factory=dict) @dataclass @@ -21,6 +38,31 @@ class CameraVideoQuality: width: int | None = None height: int | None = None + expected_frames: int = 0 + present_frames: int = 0 + missing_frames: int = 0 + decode_attempts: int = 0 + decode_failures: int = 0 + invalid_frames: int = 0 + sampled_out_frames: int = 0 + capped_frames: int = 0 + missing_fraction: float | None = None + decode_coverage: float | None = None + timestamp_coverage: float | None = None + effective_fps: float | None = None + timestamp_jitter_ratio: float | None = None + estimated_drop_fraction: float | None = None + timestamp_gaps: int = 0 + estimated_dropped_frames: int | None = None + max_frame_gap_s: float | None = None + timestamp_invalid_count: int = 0 + resolution_changes: int = 0 + max_frozen_duration_s: float | None = None + mean_motion_px_s: float | None = None + metric_status: dict[str, str] = field(default_factory=dict) + provenance: dict = field(default_factory=dict) + events: list[VideoEvent] = field(default_factory=list) + # Sharpness (variance of Laplacian) mean_sharpness: float | None = None min_sharpness: float | None = None @@ -39,34 +81,23 @@ class CameraVideoQuality: mean_colorfulness: float | None = None # Tier 1: motion (None unless level="motion") - mean_motion: float | None = None # mean flow magnitude, px/frame - motion_smoothness: float | None = None # pixel-space LDLJ (more negative = jerkier) + mean_motion: float | None = None # mean flow magnitude, px/frame + motion_smoothness: float | None = None # pixel-space LDLJ (more negative = jerkier) scene_motion_fraction: float | None = None # residual / total flow (object vs camera) cut_count: int | None = None flags: list[str] = field(default_factory=list) def to_dict(self) -> dict: - return { - "camera": self.camera, - "num_frames": self.num_frames, - "width": self.width, - "height": self.height, - "mean_sharpness": _round(self.mean_sharpness), - "min_sharpness": _round(self.min_sharpness), - "blurry_fraction": _round(self.blurry_fraction), - "mean_luma": _round(self.mean_luma), - "overexposed_fraction": _round(self.overexposed_fraction), - "underexposed_fraction": _round(self.underexposed_fraction), - "frozen_fraction": _round(self.frozen_fraction), - "longest_frozen_run": self.longest_frozen_run, - "mean_colorfulness": _round(self.mean_colorfulness), - "mean_motion": _round(self.mean_motion), - "motion_smoothness": _round(self.motion_smoothness), - "scene_motion_fraction": _round(self.scene_motion_fraction), - "cut_count": self.cut_count, - "flags": self.flags, - } + return asdict(self) + + @classmethod + def from_dict(cls, data: dict) -> CameraVideoQuality: + cam = cls( + **{f.name: data[f.name] for f in fields(cls) if f.name in data and f.name != "events"} + ) + cam.events = [VideoEvent(**e) for e in data.get("events", [])] + return cam @dataclass @@ -74,6 +105,8 @@ class VideoQuality: """Episode-level video quality, with per-camera detail and rollups.""" per_camera: dict[str, CameraVideoQuality] = field(default_factory=dict) + scorer_version: str = "video-v2-integrity" + provenance: dict = field(default_factory=dict) # Episode rollups (worst-case across cameras, for one-line filtering) min_sharpness: float | None = None @@ -114,8 +147,23 @@ def to_flat_dict(self) -> dict: def to_dict(self) -> dict: d = self.to_flat_dict() d["per_camera"] = {n: c.to_dict() for n, c in self.per_camera.items()} + d["scorer_version"] = self.scorer_version + d["provenance"] = self.provenance + d["flags"] = self.flags return d + @classmethod + def from_dict(cls, data: dict) -> VideoQuality: + video = cls.from_flat_dict(data) or cls() + video.per_camera = { + name: CameraVideoQuality.from_dict(cam) + for name, cam in data.get("per_camera", {}).items() + } + video.scorer_version = data.get("scorer_version", "video-v1") + video.provenance = data.get("provenance", {}) + video.flags = data.get("flags", []) + return video + @classmethod def from_flat_dict(cls, data: dict) -> VideoQuality | None: """Reconstruct rollup scalars from a flat report row (filter-side). @@ -126,6 +174,7 @@ def from_flat_dict(cls, data: dict) -> VideoQuality | None: if "video_min_sharpness" not in data and "video_num_cameras" not in data: return None return cls( + scorer_version="video-v1", min_sharpness=data.get("video_min_sharpness"), mean_sharpness=data.get("video_mean_sharpness"), blurry_fraction=data.get("video_blurry_fraction"), diff --git a/forge/quality/video/pixel.py b/forge/quality/video/pixel.py index 3d430fa..9b66299 100644 --- a/forge/quality/video/pixel.py +++ b/forge/quality/video/pixel.py @@ -24,6 +24,20 @@ def _to_float_image(img: NDArray) -> NDArray: Accepts uint8 HWC/HW arrays or float arrays in either 0–1 or 0–255. """ a = np.asarray(img) + if ( + a.ndim not in (2, 3) + or min(a.shape[:2]) < 1 + or (a.ndim == 3 and a.shape[2] not in (1, 3, 4)) + ): + raise ValueError("Expected a nonempty grayscale/RGB/RGBA image") + if a.dtype != np.uint8 and not np.issubdtype(a.dtype, np.floating): + raise ValueError( + "Only uint8 or float intensity images are supported; depth needs separate metrics" + ) + if not np.isfinite(a).all(): + raise ValueError("Nonfinite pixels are invalid observations") + if a.min() < 0 or a.max() > 255: + raise ValueError("Image intensities must be in [0, 1] or [0, 255]") if a.dtype == np.uint8: return a.astype(np.float64) a = a.astype(np.float64) @@ -31,7 +45,7 @@ def _to_float_image(img: NDArray) -> NDArray: finite = a[np.isfinite(a)] if finite.size and finite.max() <= 1.0 + 1e-6 and finite.min() >= -1e-6: a = a * 255.0 - return np.nan_to_num(a, nan=0.0, posinf=255.0, neginf=0.0) + return a def _downscale(arr: NDArray, target: int) -> NDArray: @@ -78,13 +92,7 @@ def laplacian_variance(gray: NDArray) -> float: if gray.shape[0] < 3 or gray.shape[1] < 3: return 0.0 center = gray[1:-1, 1:-1] - lap = ( - gray[:-2, 1:-1] - + gray[2:, 1:-1] - + gray[1:-1, :-2] - + gray[1:-1, 2:] - - 4.0 * center - ) + lap = gray[:-2, 1:-1] + gray[2:, 1:-1] + gray[1:-1, :-2] + gray[1:-1, 2:] - 4.0 * center return float(lap.var()) diff --git a/forge/visualize/README.md b/forge/visualize/README.md new file mode 100644 index 0000000..959d25b --- /dev/null +++ b/forge/visualize/README.md @@ -0,0 +1,53 @@ +# Web dataset explorer + +Open the general viewer with `forge visualize ./dataset --backend web`. +For localized quality review, run `forge quality ./dataset --visualize`. +Both use the same interface; quality panels appear only when a report is supplied. + +## Explore + +- Search episode IDs and task descriptions. Quality mode can filter episodes with review events or flags. +- Camera cards show camera names, preserve aspect ratio, and support focus/restore and fullscreen. Narrow screens provide a horizontally scrollable camera strip. +- Play, adjust speed, step frames, jump to a frame, or loop the current episode. Frame entry is one-based; exported event indices remain zero-based. +- Plot all action/state channels, toggle individual channels, and inspect current values. Click a plot to seek. Per-channel normalization changes display only; metrics are unchanged. +- Task descriptions, recording timestamps, and per-episode camera availability come from the dataset. Relative timestamp labels use stored timestamps when available; playback follows episode FPS. + +## Review + +The inspector shows the heuristic score, pause fraction, episode flags, and event cards. Cards explain why a span is worth reviewing without declaring task failure. Filter event types or navigate between events with the arrow buttons. Click a card or highlighted interval to seek to its start. + +Direction reversals are descriptive and hidden by default. Enable them to show blue intervals. Amber intervals are review candidates, red intervals are tracking-stall candidates, and gray intervals indicate timestamp gaps. Green regions mean no **visible** event; hidden event types and unavailable metrics still matter. Metric availability is expandable in the inspector. + +## Keyboard + +| Key | Action | +|---|---| +| Space | Play/pause | +| Left / right | Step one frame | +| Up / down | Switch episode | +| N / P | Next / previous visible event | +| [ / ] | Change playback speed | + +Keyboard shortcuts are inactive while editing inputs or using native controls. The `?` button opens the shortcut guide. + +## Verification + +Backend and CLI tests: `pytest tests/test_quality_visualize.py`. + +Optional browser integration (requires Chrome and `websocket-client` in the test environment): + +```bash +FORGE_TEST_CHROME=/path/to/chrome pytest tests/test_web_viewer_browser.py +``` + +The browser test uses a temporary profile and a local synthetic fixture. It covers quality and normal viewing, episode search, event seeking/filtering, camera focus, all-channel plots, normalization, playback, rapid episode changes, and mobile overflow. + +## Video integrity review + +Add `--video` to `forge quality ... --visualize` to include camera summaries and +video events. The inspector separates absent camera references, decode failures, +invalid images, intentional sampling, and analysis caps. Camera/source filtering +also applies to timeline lanes, event navigation, and plot overlays. Video gap +estimates use episode timestamps and declared FPS, not independent camera PTS; +unknown timing remains explicit. Camera decode errors display an unavailable-frame +placeholder. See [the video quality guide](../quality/video/README.md). diff --git a/forge/visualize/web_viewer.py b/forge/visualize/web_viewer.py index 4e19351..2e9798e 100644 --- a/forge/visualize/web_viewer.py +++ b/forge/visualize/web_viewer.py @@ -17,7 +17,7 @@ import socket import threading import webbrowser -from http.server import HTTPServer, BaseHTTPRequestHandler +from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path from typing import Any @@ -37,6 +37,7 @@ def _encode_jpeg(img_rgb: np.ndarray) -> bytes: # Try OpenCV try: import cv2 + img_bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR) ok, buf = cv2.imencode(".jpg", img_bgr, [cv2.IMWRITE_JPEG_QUALITY, 85]) if ok: @@ -47,6 +48,7 @@ def _encode_jpeg(img_rgb: np.ndarray) -> bytes: # Try PIL try: from PIL import Image + pil_img = Image.fromarray(img_rgb) bio = io.BytesIO() pil_img.save(bio, format="JPEG", quality=85) @@ -91,7 +93,13 @@ class WebBackend: on init. Frame images are loaded lazily on demand. """ - def __init__(self, dataset_path: Path, max_episodes: int = 50): + def __init__(self, dataset_path: Path, max_episodes: int = 50, quality_report=None): + self._quality = ( + {eq.episode_id: eq for eq in quality_report.per_episode} + if quality_report is not None + else {} + ) + self._quality_mode = quality_report is not None self.dataset_path = Path(dataset_path) self.format_name = FormatRegistry.detect_format(dataset_path) self.reader = FormatRegistry.get_reader(self.format_name) @@ -102,6 +110,8 @@ def __init__(self, dataset_path: Path, max_episodes: int = 50): self._camera_keys: list[str] = [] self._episode_actions: list[np.ndarray | None] = [] self._episode_states: list[np.ndarray | None] = [] + self._episode_timestamps: list[list[float | None]] = [] + self._episode_cameras: list[list[str]] = [] self._segmentations: list[dict | None] = [] # Cache for materialized frames (populated lazily) @@ -110,8 +120,10 @@ def __init__(self, dataset_path: Path, max_episodes: int = 50): print(f"Loading episodes from {self.format_name} dataset...") for i, episode in enumerate(self.reader.read_episodes(dataset_path)): - if i >= max_episodes: + if len(self._episode_objects) >= max_episodes: break + if self._quality_mode and episode.episode_id not in self._quality: + continue if (i + 1) % 10 == 0: print(f" Loaded {i + 1} episodes...") @@ -120,21 +132,38 @@ def __init__(self, dataset_path: Path, max_episodes: int = 50): # Extract only actions/states — iterate frames without storing them actions = [] states = [] + timestamps = [] + cameras = set() frame_count = 0 for frame in episode.frames(): frame_count += 1 - if frame.action is not None: - actions.append(frame.action) - if frame.state is not None: - states.append(frame.state) - # Detect cameras from first frame of first episode - if i == 0 and frame_count == 1: - for cam_name in frame.images.keys(): - self._camera_keys.append(cam_name) + actions.append(frame.action) + states.append(frame.state) + timestamps.append( + float(frame.timestamp) + if frame.timestamp is not None and np.isfinite(frame.timestamp) + else None + ) + cameras.update(frame.images) + + self._episode_timestamps.append(timestamps) + self._episode_cameras.append(sorted(cameras)) + self._camera_keys = sorted(set(self._camera_keys) | cameras) + + def aligned(values): + template = next((v for v in values if v is not None), None) + if template is None: + return None + return np.array( + [ + v if v is not None else np.full_like(template, np.nan, dtype=float) + for v in values + ] + ) self._episode_lengths.append(frame_count) - self._episode_actions.append(np.array(actions) if actions else None) - self._episode_states.append(np.array(states) if states else None) + self._episode_actions.append(aligned(actions)) + self._episode_states.append(aligned(states)) self._segmentations.append(None) print(f"Loaded {len(self._episode_objects)} episodes") @@ -159,7 +188,9 @@ def get_episode_length(self, episode_idx: int) -> int: return 0 return self._episode_lengths[episode_idx] - def get_frame_image(self, episode_idx: int, frame_idx: int, camera_key: str) -> np.ndarray | None: + def get_frame_image( + self, episode_idx: int, frame_idx: int, camera_key: str + ) -> np.ndarray | None: if episode_idx >= len(self._episode_objects): return None frames = self._get_frames(episode_idx) @@ -168,7 +199,10 @@ def get_frame_image(self, episode_idx: int, frame_idx: int, camera_key: str) -> frame = frames[frame_idx] if camera_key not in frame.images: return None - img = frame.images[camera_key].load() + try: + img = frame.images[camera_key].load() + except Exception: + return None if img.dtype != np.uint8: if img.max() <= 1.0: img = (img * 255).astype(np.uint8) @@ -198,7 +232,11 @@ def get_fps(self) -> float: return self.info.inferred_fps or 30.0 def get_name(self) -> str: - return f"{self.dataset_path.name} ({self.format_name})" + if self.dataset_path.parent.name == "snapshots": + cache_name = self.dataset_path.parent.parent.name + if cache_name.startswith("datasets--"): + return cache_name.removeprefix("datasets--").replace("--", "/") + return self.dataset_path.name def get_info_dict(self) -> dict: return { @@ -207,9 +245,37 @@ def get_info_dict(self) -> dict: "num_episodes": self.get_num_episodes(), "cameras": self.get_camera_keys(), "fps": self.get_fps(), - "total_frames": sum( - self.get_episode_length(i) for i in range(self.get_num_episodes()) - ), + "quality_mode": self._quality_mode, + "episode_ids": [ep.episode_id for ep in self._episode_objects], + "episodes": [ + { + "id": ep.episode_id, + "num_frames": self._episode_lengths[i], + "fps": ep.fps or self.get_fps(), + "task": ep.language_instruction, + "score": self._quality[ep.episode_id].overall_score + if ep.episode_id in self._quality + else None, + "flags": self._quality[ep.episode_id].flags + if ep.episode_id in self._quality + else [], + "event_count": sum( + e.kind != "direction_reversal" for e in self._quality[ep.episode_id].events + ) + + ( + sum( + len(c.events) + for c in self._quality[ep.episode_id].video.per_camera.values() + ) + if self._quality[ep.episode_id].video + else 0 + ) + if ep.episode_id in self._quality + else 0, + } + for i, ep in enumerate(self._episode_objects) + ], + "total_frames": sum(self.get_episode_length(i) for i in range(self.get_num_episodes())), } def get_episode_dict(self, episode_idx: int) -> dict: @@ -220,19 +286,30 @@ def get_episode_dict(self, episode_idx: int) -> dict: result: dict[str, Any] = { "num_frames": num_frames, + "episode_id": self._episode_objects[episode_idx].episode_id, + "task": self._episode_objects[episode_idx].language_instruction, + "timestamps": self._episode_timestamps[episode_idx], + "cameras": self._episode_cameras[episode_idx], "actions": None, "states": None, "segments": self.get_segmentation(episode_idx), + "quality": self._quality[self._episode_objects[episode_idx].episode_id].to_dict() + if self._episode_objects[episode_idx].episode_id in self._quality + else None, + "fps": self._episode_objects[episode_idx].fps or self.get_fps(), } if actions is not None and actions.size > 0: - # Limit to 8 dims, round for compact JSON - a = actions[:, :8] if actions.ndim > 1 and actions.shape[1] > 8 else actions - result["actions"] = np.round(a, 4).tolist() + a = actions + result["actions"] = np.where( + np.isfinite(a), np.round(a, 4).astype(object), None + ).tolist() if states is not None and states.size > 0: - s = states[:, :8] if states.ndim > 1 and states.shape[1] > 8 else states - result["states"] = np.round(s, 4).tolist() + s = states + result["states"] = np.where( + np.isfinite(s), np.round(s, 4).astype(object), None + ).tolist() return result @@ -340,8 +417,9 @@ def __init__( max_episodes: int = 50, port: int = 0, segment: bool = False, + quality_report=None, ): - self.backend = WebBackend(Path(dataset_path), max_episodes) + self.backend = WebBackend(Path(dataset_path), max_episodes, quality_report=quality_report) self.port = port if segment: @@ -378,18 +456,22 @@ def _run_segmentation(self) -> None: # Label phases if configured if config.label_phases and es.segments: labeler = PhaseLabeler() - labeler.label_segments(es.segments, states if states.ndim == 2 else states.reshape(-1, 1)) + labeler.label_segments( + es.segments, states if states.ndim == 2 else states.reshape(-1, 1) + ) segments_data = [] for seg in es.segments: color = PHASE_COLORS.get(seg.label, "#bdbdbd") - segments_data.append({ - "start": seg.start, - "end": seg.end, - "label": seg.label or "unknown", - "color": color, - "duration_frames": seg.duration_frames, - }) + segments_data.append( + { + "start": seg.start, + "end": seg.end, + "label": seg.label or "unknown", + "color": color, + "duration_frames": seg.duration_frames, + } + ) self.backend.set_segmentation(i, segments_data) except Exception as e: logger.warning("Segmentation failed for episode %d: %s", i, e) @@ -415,6 +497,7 @@ def show(self) -> None: # Open browser after a short delay def open_browser(): import time + time.sleep(0.3) webbrowser.open(url) @@ -432,6 +515,7 @@ def web_visualize( max_episodes: int = 50, segment: bool = False, port: int = 0, + quality_report=None, ) -> None: """Visualize a dataset in the browser. @@ -441,7 +525,13 @@ def web_visualize( segment: Run segmentation and show phase overlay. port: Server port (0 = auto). """ - viewer = WebViewer(dataset_path, max_episodes=max_episodes, segment=segment, port=port) + viewer = WebViewer( + dataset_path, + max_episodes=max_episodes, + segment=segment, + port=port, + quality_report=quality_report, + ) viewer.show() @@ -452,704 +542,170 @@ def web_visualize( HTML_TEMPLATE = r""" - - -Forge Viewer + +Forge · Dataset explorer - -
Loading dataset...
- -
-
-

Forge Viewer

- -
- -
- +
Opening dataset…
+
forge.
Dataset explorer

Dataset

+
+
-
- -
- - - -
-
- -
- 0 / 0 - -
-
- -
-
- - -
-
- - -
-
+ +
Episode workspace

Loading…

+

Camera views

+
+ +

Signals

Click a plot to seek · toggle channels below
+

Actions

States

- -
Space: Play/Pause   ←→: Frame   ↑↓: Episode   [/]: Speed
- + +
+

Move through your data

Space Play / pause
← → Step one frame
↑ ↓ Previous / next episode
N P Next / previous visible event
[ ] Playback speed

Click a camera’s Focus button to inspect one view. Signal values use native dataset units; normalization changes the plot only.

diff --git a/pyproject.toml b/pyproject.toml index d2e7d85..6a30b13 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -143,7 +143,6 @@ include = [ "/docs", "/scripts", "/README.md", - "/ROADMAP.md", "/LICENSE", "/pyproject.toml", ] diff --git a/requirements-dev.txt b/requirements-dev.txt deleted file mode 100644 index 0bcd0dd..0000000 --- a/requirements-dev.txt +++ /dev/null @@ -1,18 +0,0 @@ -# Development dependencies for Forge --r requirements.txt - -# Testing -pytest>=7.4.0 -pytest-cov>=4.1.0 - -# Type checking -mypy>=1.7.0 - -# Linting -ruff>=0.1.0 - -# Optional format support for testing -tensorflow>=2.13.0 -tensorflow-datasets>=4.9.0 -rosbags>=0.9.0 -av>=11.0.0 diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 8d7e3a7..0000000 --- a/requirements.txt +++ /dev/null @@ -1,12 +0,0 @@ -# Core dependencies for Forge -numpy>=1.24.0 -typer>=0.9.0 -rich>=13.0.0 -pyyaml>=6.0 - -# LeRobot format support (parquet) -pyarrow>=14.0.0 -datasets>=2.16.0 - -# Zarr format support -zarr>=2.16.0 diff --git a/scripts/benchmark_video_quality.py b/scripts/benchmark_video_quality.py new file mode 100644 index 0000000..c11a11c --- /dev/null +++ b/scripts/benchmark_video_quality.py @@ -0,0 +1,325 @@ +"""Reproducible CPU benchmark of Forge's video checks on a local 720p H.264 clip. + +Run from repo root: + PYTHONPATH=. .venv/bin/python scripts/benchmark_video_quality.py SOURCE.mp4 \ + --output /tmp/forge-video-benchmark/results.json + +The source's first N frames are resized and re-encoded as a controlled fixture. +Preparation/encoding is excluded from timings. End-to-end timings include local +file opening, decoding, RGB conversion, metrics, integrity, events and rollups; +exclude process startup, network I/O, dataset indexing, proprioception and UI. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import platform +import statistics +import time +from importlib.metadata import version +from pathlib import Path + +import av +import cv2 +import numpy as np + +from forge.core.models import Frame, LazyImage +from forge.quality.metrics import log_dimensionless_jerk +from forge.quality.video import VideoQualityAnalyzer, VideoQualityConfig +from forge.quality.video.motion import ( + affine_design, + camera_scene_split, + dense_flow, + flow_magnitude, + histogram_correlation, + to_uint8_gray, +) +from forge.quality.video.pixel import ( + clip_fractions, + colorfulness, + frame_mae, + laplacian_variance, + prepare, +) + + +def summary(seconds, units): + median = statistics.median(seconds) + return dict( + median_seconds=median, + min_seconds=min(seconds), + max_seconds=max(seconds), + median_ms_per_unit=median * 1000 / units, + units_per_second=units / median, + repetitions_seconds=seconds, + units_per_repetition=units, + ) + + +def micro(fn, iterations, repeats): + for i in range(10): + fn(i) + durations = [] + for _ in range(repeats): + start = time.perf_counter() + for i in range(iterations): + fn(i) + durations.append(time.perf_counter() - start) + return summary(durations, iterations) + + +def make_clip(source, output, count): + actual = 0 + with av.open(str(source)) as src, av.open(str(output), "w") as dst: + stream = dst.add_stream("libx264", rate=30) + stream.width, stream.height = 1280, 720 + stream.pix_fmt = "yuv420p" + stream.options = {"crf": "23", "preset": "fast"} + for i, frame in enumerate(src.decode(video=0)): + if i >= count: + break + rgb = cv2.resize( + frame.to_ndarray(format="rgb24"), (1280, 720), interpolation=cv2.INTER_LINEAR + ) + out = av.VideoFrame.from_ndarray(rgb, format="rgb24") + out.pts = i + for packet in stream.encode(out): + dst.mux(packet) + actual += 1 + for packet in stream.encode(): + dst.mux(packet) + if actual != count: + raise ValueError(f"Source has only {actual} frames; need {count}") + + +def run_pipeline(clip, mode, arrays=None, count=300): + analyzer = VideoQualityAnalyzer( + VideoQualityConfig(level=mode if mode != "decode_only" else "pixel") + ) + acc = analyzer.new_accumulators(fps=30, cameras=["camera"]) + start = time.perf_counter() + n = 0 + if arrays is None: + container = av.open(str(clip)) + frames = container.decode(video=0) + else: + container = None + frames = (arrays[i % len(arrays)] for i in range(count)) + try: + for i, img in enumerate(frames): + # Lazily decode RGB on the production analyzer's consume path. + if arrays is None: + + def loader(f=img): + return f.to_ndarray(format="rgb24") + else: + + def loader(f=img): + return f + + if mode == "decode_only": + loader() + else: + frame = Frame( + index=i, + timestamp=i / 30, + images={"camera": LazyImage(loader=loader, height=720, width=1280)}, + ) + analyzer.consume_frame(frame, acc, i) + n += 1 + if mode != "decode_only": + result = analyzer.finalize(acc) + assert result.per_camera["camera"].num_frames == n + finally: + if container: + container.close() + return time.perf_counter() - start, n + + +def run_forge_reader(clip, mode, count): + from forge.formats.lerobot_v3.reader import VideoFrameCache + + analyzer = VideoQualityAnalyzer(VideoQualityConfig(level=mode)) + acc = analyzer.new_accumulators(fps=30, cameras=["camera"]) + cache = VideoFrameCache(clip) + start = time.perf_counter() + try: + for i in range(count): + frame = Frame( + index=i, + timestamp=i / 30, + images={ + "camera": LazyImage( + loader=lambda idx=i: cache.get_frame(idx), height=720, width=1280 + ) + }, + ) + analyzer.consume_frame(frame, acc, i) + result = analyzer.finalize(acc) + assert result.per_camera["camera"].num_frames == count + finally: + cache.close() + return time.perf_counter() - start + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("source", type=Path) + p.add_argument("--output", type=Path, required=True) + p.add_argument("--frames", type=int, default=300) + p.add_argument("--repeats", type=int, default=5) + args = p.parse_args() + if args.frames < 16 or args.repeats < 1: + p.error("--frames must be at least 16 and --repeats must be positive") + args.output.parent.mkdir(parents=True, exist_ok=True) + clip = args.output.parent / "benchmark_720p_h264.mp4" + if args.source.resolve() == clip.resolve(): + p.error("The source must differ from the generated benchmark fixture path") + make_clip(args.source, clip, args.frames) + images = [] + with av.open(str(clip)) as src: + for i, f in enumerate(src.decode(video=0)): + if i >= 16: + break + images.append(f.to_ndarray(format="rgb24")) + prepared = [prepare(i, 128) for i in images] + motion = [to_uint8_gray(prepare(i, 64)[0]) for i in images] + design = affine_design(*motion[0].shape) + flows = [dense_flow(motion[i - 1], motion[i]) for i in range(1, len(motion))] + + def gray(i): + return prepared[i % len(prepared)][0] + + def rgb(i): + return prepared[i % len(prepared)][1] + + def flow(i): + return flows[i % len(flows)] + + funcs = { + "prepare_720p_to_128": lambda i: prepare(images[i % len(images)], 128), + "prepare_720p_to_64": lambda i: to_uint8_gray(prepare(images[i % len(images)], 64)[0]), + "blur_sharpness": lambda i: laplacian_variance(gray(i)), + "exposure_brightness": lambda i: (float(gray(i).mean()), clip_fractions(gray(i), 4, 254)), + "frozen_pixel_difference": lambda i: frame_mae(gray(i), gray(i + 1)), + "colorfulness": lambda i: colorfulness(rgb(i)), + "optical_flow_and_magnitude": lambda i: flow_magnitude( + dense_flow(motion[i % 16], motion[(i + 1) % 16]) + ).mean(), + "camera_scene_motion_split": lambda i: camera_scene_split(flow(i), design), + "cut_histogram_comparison": lambda i: histogram_correlation( + motion[i % 16], motion[(i + 1) % 16] + ), + } + result = dict( + hardware=dict( + platform=platform.platform(), + machine=platform.machine(), + opencv_threads=cv2.getNumThreads(), + ), + versions={x: version(x) for x in ("numpy", "av", "opencv-python")}, + fixture=dict( + source=str(args.source), + path=str(clip), + frames=args.frames, + width=1280, + height=720, + fps=30, + codec="H.264/libx264", + crf=23, + bytes=clip.stat().st_size, + sha256=hashlib.sha256(clip.read_bytes()).hexdigest(), + ), + settings=dict( + pixel_longest_side=128, motion_longest_side=64, sample_stride=1, repeats=args.repeats + ), + per_component={}, + pipelines={}, + ) + for name, fn in funcs.items(): + result["per_component"][name] = micro(fn, 200, args.repeats) + print(name, round(result["per_component"][name]["median_ms_per_unit"], 4), "ms", flush=True) + # Smoothness is an episode reduction, not a per-frame kernel. + trajectory = np.cumsum( + np.tile(np.array([f.mean(axis=(0, 1)) for f in flows]), (args.frames // len(flows) + 1, 1)), + axis=0, + )[: args.frames] + result["motion_smoothness_per_episode"] = micro( + lambda i: log_dimensionless_jerk(trajectory, 1 / 30), 100, args.repeats + ) + + # Integrity scheduling with no pixel decoding: every reference intentionally sampled out + # except the first. Subtracting timings is avoided; label the one-frame work included. + def integrity_run(): + analyzer = VideoQualityAnalyzer(VideoQualityConfig(sample_stride=args.frames + 1)) + acc = analyzer.new_accumulators(fps=30, cameras=["camera"]) + start = time.perf_counter() + for i in range(args.frames): + analyzer.consume_frame( + Frame( + index=i, + timestamp=i / 30, + images={"camera": LazyImage(loader=lambda: images[0], height=720, width=1280)}, + ), + acc, + i, + ) + analyzer.finalize(acc) + return time.perf_counter() - start + + integrity_run() + result["integrity_and_one_pixel_sample"] = summary( + [integrity_run() for _ in range(args.repeats)], args.frames + ) + jobs = [ + ("decode_only", None), + ("pixel", images), + ("motion", images), + ("pixel", None), + ("motion", None), + ] + timings = { + ( + "decode_only" + if mode == "decode_only" + else ("metrics_" if arrays is not None else "end_to_end_") + mode + ): [] + for mode, arrays in jobs + } + for mode, arrays in jobs: + run_pipeline(clip, mode, arrays, args.frames) + for repeat in range(args.repeats): + # Alternate order to reduce systematic warmup/thermal bias. + for mode, arrays in jobs if repeat % 2 == 0 else reversed(jobs): + key = ( + "decode_only" + if mode == "decode_only" + else ("metrics_" if arrays is not None else "end_to_end_") + mode + ) + elapsed, n = run_pipeline(clip, mode, arrays, args.frames) + assert n == args.frames + timings[key].append(elapsed) + for key, values in timings.items(): + result["pipelines"][key] = summary(values, args.frames) + print(key, result["pipelines"][key], flush=True) + for mode in ("pixel", "motion"): + run_forge_reader(clip, mode, args.frames) + values = [run_forge_reader(clip, mode, args.frames) for _ in range(args.repeats)] + result["pipelines"]["forge_reader_" + mode] = summary(values, args.frames) + print("forge_reader_" + mode, result["pipelines"]["forge_reader_" + mode], flush=True) + result["estimates"] = [] + for fps in (20, 30): + for duration in (10, 30, 60): + row = dict(input_fps=fps, duration_seconds=duration, frames=fps * duration) + for mode in ("pixel", "motion"): + ms = result["pipelines"]["forge_reader_" + mode]["median_ms_per_unit"] + row[mode + "_processing_seconds"] = fps * duration * ms / 1000 + result["estimates"].append(row) + args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + "\n") + print("Saved", args.output, flush=True) + + +if __name__ == "__main__": + main() diff --git a/setup.py b/setup.py deleted file mode 100644 index 21b2228..0000000 --- a/setup.py +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env python -"""Setup script for backwards compatibility with pip install -e .""" - -from setuptools import setup - -# All configuration is in pyproject.toml -# This file exists for editable installs with older pip versions -setup() diff --git a/tests/test_cli.py b/tests/test_cli.py index 030bbc2..b964f50 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -33,7 +33,7 @@ def test_version_command(self): """Test the version command.""" result = runner.invoke(app, ["version"]) assert result.exit_code == 0 - assert "0.1.0" in result.stdout + assert "0.2.0" in result.stdout def test_formats_command(self): """Test the formats command.""" diff --git a/tests/test_filter.py b/tests/test_filter.py index c744e39..8798041 100644 --- a/tests/test_filter.py +++ b/tests/test_filter.py @@ -225,7 +225,7 @@ def test_defaults(self): assert config.include_episodes is None assert config.exclude_episodes is None assert config.from_report is None - assert config.gripper_dim == -1 + assert config.gripper_dim is None assert config.fps == 30.0 def test_with_values(self): diff --git a/tests/test_gap_fixes.py b/tests/test_gap_fixes.py new file mode 100644 index 0000000..f96476b --- /dev/null +++ b/tests/test_gap_fixes.py @@ -0,0 +1,113 @@ +"""Regression tests for the bugs fixed from FORGE_GAPS.md (B2, B4, B7, B8, B20).""" + +import json +from pathlib import Path + +import pytest + +from forge.filter.engine import FilterConfig, FilterEngine +from forge.quality.models import EpisodeQuality + + +def test_b2_min_quality_rejects_unscored_episode(): + engine = FilterEngine(FilterConfig(min_quality=6.0)) + eq = EpisodeQuality(episode_id="ep_000", overall_score=None, flags=[]) + keep, reasons = engine._evaluate_episode("ep_000", eq) + assert not keep + assert any("no quality score" in r for r in reasons) + + +def test_b2_unscored_episode_kept_without_quality_gate(): + engine = FilterEngine(FilterConfig(exclude_flags=["jerky"])) + eq = EpisodeQuality(episode_id="ep_000", overall_score=None, flags=[]) + keep, _ = engine._evaluate_episode("ep_000", eq) + assert keep + + +def test_b7_chatter_recommendation_uses_existing_flag(): + import inspect + + from forge.quality import analyzer + + src = inspect.getsource(analyzer) + assert "--max-gripper-chatter" not in src + assert "--exclude-flags gripper_chatter" in src + + +def test_b20_version_matches_pyproject(): + import forge + + pyproject = (Path(__file__).parent.parent / "pyproject.toml").read_text() + assert f'version = "{forge.__version__}"' in pyproject + + +def _lerobot_dir(tmp_path: Path, codebase_version: str) -> Path: + root = tmp_path / "ds" + (root / "meta").mkdir(parents=True) + (root / "data").mkdir() + (root / "meta" / "info.json").write_text(json.dumps({"codebase_version": codebase_version, "fps": 30})) + (root / "meta" / "tasks.jsonl").write_text('{"task_index": 0, "task": "pick"}\n') + return root + + +def test_b8_v21_with_tasks_jsonl_is_not_v3(tmp_path: Path): + from forge.formats.lerobot_v3.reader import LeRobotV3Reader + + assert not LeRobotV3Reader.can_read(_lerobot_dir(tmp_path, "v2.1")) + + +def test_b8_v3_still_detected(tmp_path: Path): + from forge.formats.lerobot_v3.reader import LeRobotV3Reader + + assert LeRobotV3Reader.can_read(_lerobot_dir(tmp_path, "v3.0")) + + +def _writer_deps() -> bool: + try: + import av # noqa: F401 + import pyarrow # noqa: F401 + except ImportError: + return False + return True + + +def _episodes(fps: float, n: int = 2): + import numpy as np + + from forge.core.models import CameraInfo, Episode, Frame, LazyImage + + def make(ep: int) -> Episode: + def frames(): + for i in range(10): + yield Frame( + index=i, + timestamp=i / fps, + images={"camera0": LazyImage(loader=lambda: np.zeros((32, 32, 3), np.uint8), height=32, width=32, channels=3)}, + state=np.zeros(3, np.float32), + action=np.zeros(3, np.float32), + ) + + return Episode( + episode_id=f"ep_{ep:03d}", + language_instruction="pick", + cameras={"camera0": CameraInfo(name="camera0", height=32, width=32)}, + fps=fps, + _frame_loader=frames, + ) + + return [make(i) for i in range(n)] + + +@pytest.mark.skipif(not _writer_deps(), reason="PyAV or PyArrow not installed") +@pytest.mark.parametrize("fps,expected", [(12.5, 12.5), (29.97, 29.97), (30.0, 30)]) +def test_b4_v3_writer_keeps_fractional_fps(tmp_path: Path, fps, expected): + from forge.formats.lerobot_v3.writer import LeRobotV3Writer, LeRobotV3WriterConfig + + sample_episodes = _episodes(fps) + + out = tmp_path / "out" + writer = LeRobotV3Writer(LeRobotV3WriterConfig(fps=fps, robot_type="test_robot")) + writer.write_dataset(iter(sample_episodes), out) + info = json.loads((out / "meta" / "info.json").read_text()) + assert info["fps"] == expected + assert isinstance(info["fps"], type(expected)) diff --git a/tests/test_lerobot_v3_reader_video.py b/tests/test_lerobot_v3_reader_video.py index 98e54a4..630a40d 100644 --- a/tests/test_lerobot_v3_reader_video.py +++ b/tests/test_lerobot_v3_reader_video.py @@ -107,3 +107,50 @@ def test_frame_offset_is_correct_within_episode(written_dataset: Path): assert m == pytest.approx(_expected_mean(N_EPISODES - 1, t), abs=10) # Strictly increasing content over time. assert means[0] < means[1] < means[2] + + +def test_unavailable_video_raises_instead_of_synthetic_pixels(tmp_path): + from forge.formats.lerobot_v3.reader import VideoFrameCache + + cache = VideoFrameCache(tmp_path / 'absent.mp4') + with pytest.raises(ValueError, match='Cannot open'): + cache.get_frame(0) + + +def test_exhausted_video_does_not_repeat_last_frame(written_dataset): + from forge.formats.lerobot_v3.reader import VideoFrameCache + + path = next((written_dataset / 'videos').rglob('*.mp4')) + cache = VideoFrameCache(path) + try: + assert cache.get_frame(0).size + with pytest.raises(ValueError, match='Cannot decode'): + cache.get_frame(100000) + finally: + cache.close() + + +def test_declared_cameras_survive_missing_video_files(written_dataset): + import shutil + from forge.quality.video import VideoQualityAnalyzer + + shutil.rmtree(written_dataset / 'videos') + ep = next(LeRobotV3Reader().read_episodes(written_dataset)) + assert 'cam' in ep.cameras + video = VideoQualityAnalyzer().analyze_episode(ep) + assert video.per_camera['cam'].missing_frames == T + + +def test_missing_requested_index_does_not_return_nearby_pixels(monkeypatch, tmp_path): + from types import SimpleNamespace + from forge.formats.lerobot_v3.reader import VideoFrameCache + + cache = VideoFrameCache(tmp_path / 'fixture.mp4') + pixels = np.full((4, 4, 3), 91, dtype=np.uint8) + cache._decoder = iter([SimpleNamespace(index=2, to_ndarray=lambda **kwargs: pixels)]) + cache._current_frame_idx = 0 + monkeypatch.setattr(cache, '_open', lambda: True) + monkeypatch.setattr(cache, '_frame_index_of', lambda frame: frame.index) + with pytest.raises(ValueError, match='absent'): + cache.get_frame(1) + np.testing.assert_array_equal(cache.get_frame(2), pixels) diff --git a/tests/test_lerobot_v3_roundtrip.py b/tests/test_lerobot_v3_roundtrip.py index 553ef24..ad2f676 100644 --- a/tests/test_lerobot_v3_roundtrip.py +++ b/tests/test_lerobot_v3_roundtrip.py @@ -157,6 +157,10 @@ def test_image_mode_frames_survive_round_trip(self, tmp_path: Path): assert image.shape == (32, 32, 3) # _make_episode paints frame N with value (N * 10) % 256; frame 3 -> 30. assert float(image.mean()) == pytest.approx(30.0, abs=1.0) + # Declared cameras drive video quality analysis, so inline image + # cameras must be declared alongside MP4 ones. + camera = episode.cameras["camera0"] + assert (camera.height, camera.width, camera.storage) == (32, 32, "image") @pytest.mark.skipif( not _check_dependencies_available(), diff --git a/tests/test_proprio_diagnostics.py b/tests/test_proprio_diagnostics.py new file mode 100644 index 0000000..a870609 --- /dev/null +++ b/tests/test_proprio_diagnostics.py @@ -0,0 +1,186 @@ +"""Semantic regressions from the October survey, including event alignment.""" + +import json + +import numpy as np +import pytest + +from forge.quality import QualityAnalyzer, QualityConfig, QualityReport +from forge.quality.metrics import dead_action_detection + + +def trajectory(fps=30, seconds=6): + t = np.arange(int(fps * seconds) + 1) / fps + q = np.column_stack([1 + t * 0.2, 2 + t * 0.1]) + return t, q + + +def test_later_nonzero_hold_detected_and_localized(): + t, q = trajectory() + q[60:] = q[60] + eq = QualityAnalyzer().analyze_episode_arrays("hold", q, q, t) + pauses = [e for e in eq.events if e.kind == "motion_pause"] + assert len(pauses) == 1 + assert pauses[0].start_time_s == pytest.approx(2) + assert pauses[0].end_time_s == pytest.approx(6) + assert pauses[0].end_frame == len(t) + assert eq.static.static_fraction == pytest.approx(4 / 6) + assert eq.dead_fraction > 0.6 + assert any(e.kind == "held_command" for e in eq.events) + + +def test_initial_frame_is_not_a_dead_command(): + _, q = trajectory() + fraction, ranges = dead_action_detection(q, QualityConfig()) + assert fraction == 0 and ranges == [] + + +@pytest.mark.parametrize("fps", [10, 30, 50]) +def test_pause_duration_invariant_to_rate_and_position_origin(fps): + t, q = trajectory(fps) + q[2 * fps :] = q[2 * fps] + first = QualityAnalyzer(fps=fps).analyze_episode_arrays("a", q, q, t) + shifted = QualityAnalyzer(fps=fps).analyze_episode_arrays("b", q + 100, q + 100, t) + assert first.static.static_fraction == pytest.approx(2 / 3) + assert shifted.static == first.static + + +def test_stationary_state_never_falls_back_to_moving_commands(): + t, commands = trajectory() + state = np.repeat(commands[:1], len(t), axis=0) + eq = QualityAnalyzer().analyze_episode_arrays("stuck", commands, state, t) + assert eq.ldlj is None and eq.sparc is None + assert eq.overall_score is None + assert eq.static.static_fraction == pytest.approx(1) + assert "tracking_stall_candidate" not in eq.flags # No semantic mapping yet. + eq = QualityAnalyzer( + action_semantics="position", tracking_pairs=((0, 0), (1, 1)) + ).analyze_episode_arrays("stuck", commands, state, t) + assert eq.diagnostics["tracking_error_p95"] > 1 + assert eq.diagnostics["tracking_stall_fraction"] > 0.8 + assert "tracking_stall_candidate" in eq.flags + + +def test_tracking_lag_uses_past_commands(): + t, commands = trajectory() + states = np.column_stack([1 + np.maximum(0, t - 0.2) * 0.2, 2 + np.maximum(0, t - 0.2) * 0.1]) + eq = QualityAnalyzer( + action_semantics="position", tracking_pairs=((0, 0), (1, 1)), tracking_lag_s=0.2 + ).analyze_episode_arrays("lag", commands, states, t) + assert eq.diagnostics["tracking_error_p95"] < 0.01 + assert not any(e.kind == "tracking_stall_candidate" for e in eq.events) + + +def test_gap_never_becomes_a_pause_or_tracking_event(): + t, q = trajectory() + t[60:] += 30 + q[:] = 2 + eq = QualityAnalyzer().analyze_episode_arrays("gap", q, q, t) + assert eq.overall_score is None + assert any(e.kind == "timestamp_gap" for e in eq.events) + assert all(e.duration_s < 6 for e in eq.events if e.kind != "timestamp_gap") + assert eq.diagnostics["time_coverage"] < 0.2 + + +@pytest.mark.parametrize("broken", ["reverse", "duplicate", "nan"]) +def test_invalid_timestamps_abstain(broken): + t, q = trajectory() + t[20] = {"reverse": t[19] - 1, "duplicate": t[19], "nan": np.nan}[broken] + eq = QualityAnalyzer().analyze_episode_arrays("bad", q, q, t) + assert eq.overall_score is None + assert eq.events == [] + json.dumps(eq.to_dict(), allow_nan=False) + + +def test_missing_state_does_not_invent_motion(): + t, q = trajectory() + eq = QualityAnalyzer().analyze_episode_arrays("actions", actions=q, timestamps=t) + assert eq.static is None and eq.ldlj is None + assert "net_to_path_ratio" not in eq.diagnostics + + +def test_range_edges_are_not_hardware_saturation(): + t, q = trajectory() + eq = QualityAnalyzer().analyze_episode_arrays("edges", q, q, t) + assert eq.overall_saturation is None + assert eq.observed_range_edge_fraction is not None + assert "saturated" not in eq.flags + eq = QualityAnalyzer(action_limits=((0, 1), (0, 2))).analyze_episode_arrays("limits", q, q, t) + assert eq.overall_saturation > 0.9 + assert "saturated" in eq.flags + + +def test_gripper_opt_in_and_two_gripper_channels(): + t, q = trajectory() + q[:, 0] = np.arange(len(t)) % 2 + eq = QualityAnalyzer().analyze_episode_arrays("none", q, q, t) + assert eq.is_chattery is None and eq.grippers == {} + eq = QualityAnalyzer(gripper_dims=(0, 1)).analyze_episode_arrays("both", q, q, t) + assert eq.grippers["0"]["is_chattery"] + assert not eq.grippers["1"]["is_chattery"] + assert eq.is_chattery + + +def test_reversal_is_diagnostic_not_semantic_retry(): + t, q = trajectory() + q[:, 0] = np.sin(t * 2 * np.pi) + q[:, 1] = 2 + eq = QualityAnalyzer().analyze_episode_arrays("cycles", q, q, t) + assert eq.diagnostics["direction_reversal_count"] >= 10 + assert eq.diagnostics["net_to_path_ratio"] < 0.01 + assert all("retry" not in e.kind for e in eq.events) + + +def test_roundtrip_preserves_events_status_and_static(tmp_path): + t, q = trajectory() + q[60:] = q[60] + eq = QualityAnalyzer().analyze_episode_arrays("held", q, q, t) + report = QualityReport("example", num_episodes=1, per_episode=[eq]) + path = tmp_path / "quality.json" + report.to_json(path) + loaded = QualityReport.from_json(path).per_episode[0] + assert loaded.events == eq.events + assert loaded.static == eq.static + assert loaded.metric_status == eq.metric_status + assert loaded.subscores == eq.subscores + assert loaded.scorer_version == "q-v2-proprio" + + +def test_legacy_report_loads_without_inventing_intervals(): + report = QualityReport.from_dict( + {"dataset_path": "old", "per_episode": [{"episode_id": "old", "static_fraction": 0.8}]} + ) + eq = report.per_episode[0] + assert eq.scorer_version == "q-v1" and eq.events == [] + assert eq.static.static_fraction == 0.8 + + +@pytest.mark.parametrize( + "kwargs", + [ + dict(fps=0), + dict(tracking_lag_s=-1), + dict(state_scales=(0,)), + dict(action_limits=((1, 0),)), + dict(tracking_pairs=((0, 0),)), + dict(action_semantics="torque"), + dict(gripper_dims=(0,), gripper_dim=1), + ], +) +def test_invalid_configuration(kwargs): + with pytest.raises(ValueError): + QualityConfig(**kwargs) + + +def test_misaligned_arrays_rejected(): + t, q = trajectory() + with pytest.raises(ValueError, match="matching frame counts"): + QualityAnalyzer().analyze_episode_arrays("bad", q[:-1], q, t) + + +def test_state_scaling_compensates_for_unit_conversion(): + t, q = trajectory() + a = QualityAnalyzer().analyze_episode_arrays("radians", q, q, t) + b = QualityAnalyzer(state_scales=(100, 100)).analyze_episode_arrays("scaled", q, q * 100, t) + assert b.diagnostics["path_length_scaled"] == pytest.approx(a.diagnostics["path_length_scaled"]) + assert b.ldlj == pytest.approx(a.ldlj, abs=1e-6) diff --git a/tests/test_quality.py b/tests/test_quality.py index 4cc5f80..1c91e82 100644 --- a/tests/test_quality.py +++ b/tests/test_quality.py @@ -205,7 +205,7 @@ class TestGripperChatter: def test_no_chatter(self): actions = np.zeros((100, 7)) actions[:, -1] = np.where(np.arange(100) < 50, 0.0, 1.0) # One transition - config = QualityConfig() + config = QualityConfig(gripper_dim=-1) count, rate, is_chat = gripper_chatter(actions, 100 / 30.0, config) assert count == 1 assert not is_chat @@ -214,14 +214,14 @@ def test_high_chatter(self): actions = np.zeros((100, 7)) # Toggle every frame actions[:, -1] = np.tile([0.0, 1.0], 50) - config = QualityConfig() + config = QualityConfig(gripper_dim=-1) count, rate, is_chat = gripper_chatter(actions, 100 / 30.0, config) assert count == 99 assert is_chat def test_constant_gripper(self): actions = np.zeros((100, 7)) - config = QualityConfig() + config = QualityConfig(gripper_dim=-1) count, rate, is_chat = gripper_chatter(actions, 100 / 30.0, config) assert count == 0 assert not is_chat @@ -501,7 +501,7 @@ def test_jerky_episode_flagged(self): def test_chattery_episode_flagged(self): ep = make_chattery_episode() - analyzer = QualityAnalyzer() + analyzer = QualityAnalyzer(gripper_dim=-1) eq = analyzer.analyze_episode_arrays(**ep) assert eq.is_chattery assert "gripper_chatter" in eq.flags @@ -549,7 +549,7 @@ def test_nan_handling(self): fps=30.0, ) assert "nan_in_actions" in eq.flags - assert eq.overall_score is not None + assert eq.overall_score is None class TestQualityReport: diff --git a/tests/test_quality_visualize.py b/tests/test_quality_visualize.py new file mode 100644 index 0000000..1e07739 --- /dev/null +++ b/tests/test_quality_visualize.py @@ -0,0 +1,189 @@ +"""Quality review must preserve episode identities and frame alignment.""" + +import json +from types import SimpleNamespace +from unittest.mock import Mock + +import numpy as np +from typer.testing import CliRunner + +from forge.cli import app +from forge.core.models import Episode, Frame +from forge.formats.registry import FormatRegistry +from forge.quality import QualityAnalyzer, QualityReport +from forge.visualize.web_viewer import WebBackend + + +def episode(name, missing=False): + frames = [ + Frame( + index=i, + timestamp=i / 30, + action=np.array([1.0]), + state=None if missing and i == 7 else np.array([1.0]), + ) + for i in range(40) + ] + return Episode(episode_id=name, fps=30, _frames_cache=frames) + + +def reader_fixture(monkeypatch, episodes): + reader = SimpleNamespace( + read_episodes=lambda path: iter(episodes), + inspect=lambda path: SimpleNamespace(inferred_fps=30), + ) + monkeypatch.setattr(FormatRegistry, "detect_format", lambda path: "test") + monkeypatch.setattr(FormatRegistry, "get_reader", lambda name: reader) + + +def test_backend_joins_report_by_id_and_preserves_missing_frames(monkeypatch, tmp_path): + selected = episode("chosen", missing=True) + reader_fixture(monkeypatch, [episode("skip"), selected]) + eq = QualityAnalyzer().analyze_episode(selected) + assert "nan_in_states" in eq.flags + report = QualityReport(str(tmp_path), num_episodes=1, per_episode=[eq]) + backend = WebBackend(tmp_path, max_episodes=1, quality_report=report) + assert backend.get_info_dict()["episode_ids"] == ["chosen"] + payload = backend.get_episode_dict(0) + assert payload["quality"]["episode_id"] == "chosen" + assert len(payload["states"]) == 40 + assert payload["states"][7] == [None] + assert payload["states"][8] == [1.0] + json.dumps(payload, allow_nan=False) + + +def test_cli_visualize_passes_analyzed_report_and_exports_events(monkeypatch, tmp_path): + reader_fixture(monkeypatch, [episode("chosen"), episode("skip")]) + viewer = Mock() + monkeypatch.setattr("forge.visualize.web_viewer.web_visualize", viewer) + export = tmp_path / "report.json" + result = CliRunner().invoke( + app, ["quality", str(tmp_path), "--sample", "1", "--visualize", "--export", str(export)] + ) + assert result.exit_code == 0, result.output + str(result.exception) + viewer.assert_called_once() + report = viewer.call_args.kwargs["quality_report"] + assert [q.episode_id for q in report.per_episode] == ["chosen"] + assert viewer.call_args.kwargs["max_episodes"] == 1 + saved = json.loads(export.read_text()) + assert saved["per_episode"][0]["events"] + assert report.per_episode[0].grippers == {} + + +def test_cli_rejects_unmapped_tracking_semantics(tmp_path): + result = CliRunner().invoke(app, ["quality", str(tmp_path), "--tracking-pairs", "0:0"]) + assert result.exit_code != 0 + assert "position" in result.output + + +def test_lerobot_reader_preserves_metadata_fps_for_quality(tmp_path): + import pandas as pd + + from forge.formats.lerobot_v3.reader import LeRobotV3Reader + + meta = tmp_path / "meta" + meta.mkdir() + (meta / "info.json").write_text(json.dumps({"fps": 15, "features": {}})) + t = np.arange(60) / 15 + df = pd.DataFrame( + { + "timestamp": t, + "index": np.arange(60), + "observation.state": [np.array([x]) for x in t], + "action": [np.array([x]) for x in t], + } + ) + ep = LeRobotV3Reader()._build_episode( + tmp_path, tmp_path / "data.parquet", df, 0, "episode_000000", None + ) + assert ep.fps == 15 + eq = QualityAnalyzer().analyze_episode(ep) + assert eq.provenance["fps"] == 15 + assert eq.overall_score is not None + assert "timestamp_gaps" not in eq.flags + assert "sample_rate_mismatch" not in eq.flags + + +def test_explorer_metadata_and_all_channels_are_preserved(monkeypatch, tmp_path): + from forge.core.models import LazyImage + + first = episode("first") + second = episode("second") + second.language_instruction = "Place the cup on the tray" + for f in second._frames_cache: + f.action = np.arange(14, dtype=float) + f.images = { + "wrist": LazyImage( + loader=lambda: np.zeros((8, 8, 3), dtype=np.uint8), height=8, width=8 + ) + } + reader_fixture(monkeypatch, [first, second]) + backend = WebBackend(tmp_path) + info = backend.get_info_dict() + assert info["cameras"] == ["wrist"] + assert info["episodes"][1]["task"] == "Place the cup on the tray" + assert info["episodes"][1]["num_frames"] == 40 + assert info["quality_mode"] is False + assert backend.get_episode_dict(0)["cameras"] == [] + payload = backend.get_episode_dict(1) + assert payload["cameras"] == ["wrist"] + assert payload["quality"] is None + assert len(payload["actions"][0]) == 14 + assert payload["timestamps"][7] == 7 / 30 + json.dumps(payload, allow_nan=False) + + +def test_episode_overview_counts_review_events_not_reversals(monkeypatch, tmp_path): + from forge.quality import EpisodeQuality, QualityEvent + + ep = episode("review") + reader_fixture(monkeypatch, [ep]) + eq = EpisodeQuality( + "review", + num_frames=40, + overall_score=7.5, + flags=["dead_actions"], + events=[ + QualityEvent("direction_reversal", 1, 5, 0.03, 0.13), + QualityEvent("held_command", 10, 40, 0.33, 1.3), + ], + ) + backend = WebBackend(tmp_path, quality_report=QualityReport(str(tmp_path), per_episode=[eq])) + summary = backend.get_info_dict()["episodes"][0] + assert summary["event_count"] == 1 + assert summary["score"] == 7.5 + assert summary["flags"] == ["dead_actions"] + + +def test_cli_passes_video_integrity_options_and_exports_camera_events(monkeypatch, tmp_path): + reader_fixture(monkeypatch, [episode("chosen")]) + viewer = Mock() + monkeypatch.setattr("forge.visualize.web_viewer.web_visualize", viewer) + result = CliRunner().invoke( + app, + [ + "quality", + str(tmp_path), + "--video", + "--video-cameras", + "absent", + "--video-drop-frames", + "4", + "--video-gap-seconds", + ".4", + "--video-fps", + "15", + "--visualize", + ], + ) + assert result.exit_code == 0, result.output + str(result.exception) + video = viewer.call_args.kwargs["quality_report"].per_episode[0].video + assert video.per_camera["absent"].missing_frames == 40 + assert video.provenance["config"]["significant_drop_frames"] == 4 + assert video.provenance["config"]["expected_fps"] == 15 + + +def test_cli_rejects_invalid_video_sampling(tmp_path): + result = CliRunner().invoke(app, ["quality", str(tmp_path), "--video", "--video-stride", "0"]) + assert result.exit_code != 0 + assert "sample_stride" in result.output diff --git a/tests/test_streaming.py b/tests/test_streaming.py index 1603ddf..0be4430 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -214,7 +214,7 @@ def _write_lerobot_v3(fs, root: str, *, episodes=2, frames=10) -> None: { "episode_index": [e for e in range(episodes) for _ in range(frames)], "index": list(range(n)), - "timestamp": [float(i % frames) / 10 for i in range(n)], + "timestamp": [float(i % frames) / info["fps"] for i in range(n)], "observation.state": [rng.randn(7).tolist() for _ in range(n)], "action": [rng.randn(7).tolist() for _ in range(n)], } diff --git a/tests/test_video_integrity.py b/tests/test_video_integrity.py new file mode 100644 index 0000000..a4104aa --- /dev/null +++ b/tests/test_video_integrity.py @@ -0,0 +1,274 @@ +"""Evidence and abstention regressions for camera quality.""" + +import json + +import numpy as np +import pytest + +from forge.core.models import Episode, Frame, LazyImage +from forge.quality import QualityAnalyzer, QualityReport +from forge.quality.video import VideoQualityAnalyzer, VideoQualityConfig + + +def fixture(count=30, fps=30, timestamps=True): + img = np.random.default_rng(1).integers(30, 220, (24, 24, 3), dtype=np.uint8) + frames = [ + Frame( + index=i, + timestamp=i / fps if timestamps else None, + state=np.array([i * 0.1]), + action=np.array([i * 0.1]), + images={"wrist": lazy(img)}, + ) + for i in range(count) + ] + return Episode("test", fps=fps, _frames_cache=frames) + + +def lazy(img): + return LazyImage(loader=lambda: img, height=24, width=24) + + +def analyze(ep, **kwargs): + return ( + VideoQualityAnalyzer(VideoQualityConfig(**kwargs)).analyze_episode(ep).per_camera["wrist"] + ) + + +def test_gap_estimates_use_original_observation_times_even_with_striding(): + ep = fixture() + for f in ep._frames_cache[10:]: + f.timestamp += 0.3 + for stride in (1, 4): + cam = analyze(ep, sample_stride=stride) + assert cam.estimated_dropped_frames == 9 + assert cam.timestamp_gaps == 1 + assert "video_frame_drops" in cam.flags + event = next(e for e in cam.events if e.kind == "video_frame_gap") + assert (event.start_frame, event.end_frame) == (9, 11) + assert event.evidence["significant"] + assert event.evidence["estimated_missing_observations"] == 9 + assert all( + not (e.start_frame < 10 < e.end_frame) + for e in cam.events + if e.kind == "video_frozen_candidate" + ) + + +def test_sampling_and_cap_are_not_dropped_frames(): + cam = analyze(fixture(40), sample_stride=4, max_frames=3) + assert cam.num_frames == cam.decode_attempts == 3 + assert cam.sampled_out_frames == 30 + assert cam.capped_frames == 7 + assert cam.estimated_dropped_frames == 0 + assert cam.missing_frames == cam.decode_failures == 0 + assert cam.decode_coverage == pytest.approx(3 / 40) + assert "video_frame_drops" not in cam.flags + + +def test_decode_failures_are_observable_and_break_frozen_sequences(): + ep = fixture(20) + + def broken(): + raise OSError("codec failed") + + for f in ep._frames_cache[7:10]: + f.images["wrist"] = LazyImage(loader=broken, height=24, width=24) + cam = analyze(ep) + assert cam.decode_attempts == 20 and cam.decode_failures == 3 + assert "video_decode_failure" in cam.flags + e = next(e for e in cam.events if e.kind == "video_decode_failure") + assert (e.start_frame, e.end_frame) == (7, 10) + assert all( + not (e.start_frame < 7 and e.end_frame > 10) + for e in cam.events + if e.kind == "video_frozen_candidate" + ) + + +def test_all_decode_failures_never_look_healthy(): + ep = fixture(10) + + def broken(): + raise OSError("codec failed") + + for f in ep._frames_cache: + f.images["wrist"] = LazyImage(loader=broken, height=24, width=24) + cam = analyze(ep, max_frames=3) + assert cam.decode_attempts == cam.decode_failures == 3 + assert cam.num_frames == 0 and cam.blurry_fraction is None + assert cam.capped_frames == 7 + assert cam.metric_status["pixels"].startswith("unavailable") + + +@pytest.mark.parametrize( + "image", + [ + np.full((24, 24, 3), np.nan), + np.zeros((24, 24), dtype=np.uint16), + np.full((24, 24, 3), 300.0), + np.zeros((0, 4, 3)), + ], +) +def test_invalid_pixels_are_not_exposure_observations(image): + ep = fixture(1) + ep._frames_cache[0].images["wrist"] = lazy(image) + cam = analyze(ep) + assert cam.invalid_frames == 1 and cam.num_frames == 0 + assert cam.underexposed_fraction is None + assert cam.flags == ["video_invalid_pixels"] + + +def test_missing_cameras_include_leading_and_trailing_absence(): + ep = fixture(20) + for i in [0, 1, 2, 9, 10, 19]: + ep._frames_cache[i].images = {} + cam = analyze(ep) + assert cam.expected_frames == 20 and cam.missing_frames == 6 + assert [ + (e.start_frame, e.end_frame) for e in cam.events if e.kind == "video_camera_missing" + ] == [(0, 3), (9, 11), (19, 20)] + assert cam.estimated_dropped_frames == 0 + + +def test_explicit_camera_absent_entirely_is_reported(): + ep = fixture(10) + result = VideoQualityAnalyzer(cameras=["overhead"]).analyze_episode(ep) + cam = result.per_camera["overhead"] + assert cam.missing_frames == 10 and cam.num_frames == 0 + assert cam.flags == ["video_camera_missing"] + + +def test_frozen_duration_uses_seconds_not_sample_count(): + for fps, stride in [(15, 1), (30, 1), (30, 3)]: + ep = fixture(fps + 1, fps) + cam = analyze(ep, sample_stride=stride) + assert cam.max_frozen_duration_s == pytest.approx(1.0) + assert "frozen_frames" in cam.flags + + +def test_no_stored_timestamps_abstains_on_drop_detection(): + cam = analyze(fixture(timestamps=False)) + assert cam.estimated_dropped_frames is None + assert cam.metric_status["frame_drops"].startswith("unavailable") + assert "video_invalid_timestamps" not in cam.flags + assert cam.max_frozen_duration_s > 0 + + +def test_invalid_time_breaks_flow_and_abstains_on_smoothness(): + ep = fixture() + ep._frames_cache[10].timestamp = ep._frames_cache[9].timestamp + cam = analyze(ep, level="motion") + assert "video_invalid_timestamps" in cam.flags + assert cam.motion_smoothness is None + json.dumps(cam.to_dict(), allow_nan=False) + + +def test_blank_frames_do_not_bridge_flow(): + ep = fixture(3) + ep._frames_cache[1].images["wrist"] = lazy(np.zeros((24, 24, 3), dtype=np.uint8)) + cam = analyze(ep, level="motion") + assert cam.mean_motion is None + assert cam.underexposed_fraction == pytest.approx(1 / 3) + + +def test_resolution_change_breaks_flow_without_crashing(): + ep = fixture(4) + ep._frames_cache[2].images["wrist"] = lazy( + np.random.default_rng(3).integers(0, 255, (12, 30, 3), dtype=np.uint8) + ) + cam = analyze(ep, level="motion") + assert cam.resolution_changes == 2 + assert "video_resolution_change" in cam.flags + assert cam.motion_smoothness is None + + +def test_report_roundtrip_keeps_camera_events_coverage_and_configuration(tmp_path): + ep = fixture() + ep._frames_cache[10].images = {} + eq = QualityAnalyzer(video_config=VideoQualityConfig()).analyze_episode(ep) + assert eq.video.per_camera["wrist"].missing_frames == 1 + report = QualityReport("fixture", per_episode=[eq]) + path = tmp_path / "report.json" + report.to_json(path) + loaded = QualityReport.from_json(path).per_episode[0] + assert loaded.video.to_dict() == eq.video.to_dict() + assert loaded.video.scorer_version == "video-v2-integrity" + assert "video_camera_missing" in loaded.flags + json.dumps(loaded.to_dict(), allow_nan=False) + + +@pytest.mark.parametrize( + "kw", + [ + {"sample_stride": 0}, + {"downscale": 0}, + {"gap_factor": 1}, + {"expected_fps": -1}, + {"max_frames": -1}, + {"level": "semantic"}, + {"frozen_duration_s": float("nan")}, + ], +) +def test_config_validation(kw): + with pytest.raises(ValueError): + VideoQualityConfig(**kw) + + +def test_late_camera_still_gets_full_observation_gap_evidence(): + ep = fixture(30) + for f in ep._frames_cache[:12]: + f.images = {} + for f in ep._frames_cache[5:]: + f.timestamp += 0.3 + cam = analyze(ep) + assert cam.estimated_dropped_frames == 9 + assert any(e.kind == "video_frame_gap" and e.start_frame == 4 for e in cam.events) + + +def test_repeated_small_drops_have_a_fraction_and_warning(): + ep = fixture(20) + for f in ep._frames_cache: + f.timestamp = (f.index + f.index // 3) / 30 + cam = analyze(ep, significant_drop_frames=3, significant_gap_s=1) + assert cam.estimated_dropped_frames == 6 + assert cam.estimated_drop_fraction == pytest.approx(6 / 25) + assert "video_frame_drops" in cam.flags + + +def test_timestamp_free_unknown_fps_has_no_invented_seconds(): + ep = fixture(timestamps=False) + ep.fps = None + cam = analyze(ep) + assert cam.estimated_dropped_frames is None + assert cam.max_frozen_duration_s is None + assert all(e.start_time_s is None and e.end_time_s is None for e in cam.events) + + +def test_min_sharpness_is_a_true_minimum_and_legacy_reports_still_load(): + from forge.quality.models import EpisodeQuality + from forge.quality.video.analyzer import _build_rollup + from forge.quality.video.models import CameraVideoQuality + + video = _build_rollup( + { + "a": CameraVideoQuality("a", min_sharpness=2, mean_sharpness=100), + "b": CameraVideoQuality("b", min_sharpness=5, mean_sharpness=80), + }, + VideoQualityConfig(), + ) + assert video.min_sharpness == 2 + legacy = EpisodeQuality.from_dict( + {"episode_id": "old", "video_num_cameras": 2, "video_min_sharpness": 80} + ) + assert legacy.video.min_sharpness == 80 + assert legacy.video.scorer_version == "video-v1" + assert legacy.video.per_camera == {} + + +def test_no_motion_does_not_hide_an_unavailable_camera(): + ep = fixture() + video = VideoQualityAnalyzer(level="motion", cameras=["wrist", "absent"]).analyze_episode(ep) + assert video.per_camera["wrist"].mean_motion < 0.05 + assert "no_motion" not in video.flags + assert "video_camera_missing" in video.flags diff --git a/tests/test_web_viewer_browser.py b/tests/test_web_viewer_browser.py new file mode 100644 index 0000000..6901b7a --- /dev/null +++ b/tests/test_web_viewer_browser.py @@ -0,0 +1,247 @@ +"""Opt-in real-browser regression: FORGE_TEST_CHROME=/path/to/chrome pytest this_file. + +Requires websocket-client in the test environment. No browser package is needed +by Forge itself. The test uses a temporary Chrome profile and a local fixture. +""" + +import base64 +import json +import os +import subprocess +import threading +import time +import urllib.request +from http.server import HTTPServer + +import numpy as np +import pytest + +from forge.visualize.web_viewer import _make_handler + + +@pytest.mark.skipif(not os.environ.get("FORGE_TEST_CHROME"), reason="Opt-in Chrome integration") +def test_explorer_in_browser(tmp_path): + websocket = pytest.importorskip("websocket") + + class Backend: + quality_mode = True + + def get_info_dict(self): + return dict( + name="Fixture", + format="test", + num_episodes=2, + total_frames=200, + fps=15, + cameras=["wrist"], + quality_mode=self.quality_mode, + episode_ids=["episode_000000", "episode_000001"], + episodes=[ + dict( + id=f"episode_{i:06d}", + num_frames=100, + task="Pick a cup", + score=8.0, + event_count=1, + flags=[], + ) + for i in range(2) + ], + ) + + def get_episode_dict(self, idx): + events = [ + dict( + kind="held_command", + start_frame=50, + end_frame=100, + start_time_s=50 / 15, + end_time_s=99 / 15, + channels=[], + ), + dict( + kind="direction_reversal", + start_frame=20, + end_frame=30, + start_time_s=20 / 15, + end_time_s=29 / 15, + channels=[0], + ), + ] + quality = dict( + num_frames=100, + overall_score=8.0, + flags=[], + events=events, + static=None, + metric_status={"score": "heuristic"}, + video={ + "per_camera": { + "wrist": { + "num_frames": 95, + "present_frames": 100, + "expected_frames": 100, + "missing_frames": 0, + "decode_failures": 5, + "invalid_frames": 0, + "sampled_out_frames": 0, + "capped_frames": 0, + "estimated_dropped_frames": 3, + "timestamp_coverage": 1.0, + "metric_status": {"pixels": "available"}, + "events": [ + dict( + kind="video_frame_gap", + camera="wrist", + start_frame=10, + end_frame=12, + start_time_s=10 / 15, + end_time_s=14 / 15, + evidence={"estimated_missing_observations": 3}, + ) + ], + } + } + }, + ) + data = [[i / 100 + d for d in range(12)] for i in range(100)] + return dict( + episode_id=f"episode_{idx:06d}", + num_frames=100, + fps=15, + cameras=["wrist"], + timestamps=[i / 15 for i in range(100)], + task="Pick a cup", + actions=data, + states=data, + segments=None, + quality=quality if self.quality_mode else None, + ) + + def get_frame_image(self, *args): + return np.full((40, 60, 3), 90, dtype=np.uint8) + + backend = Backend() + server = HTTPServer(("127.0.0.1", 0), _make_handler(backend)) + threading.Thread(target=server.serve_forever, daemon=True).start() + chrome = subprocess.Popen( + [ + os.environ["FORGE_TEST_CHROME"], + "--headless", + "--disable-gpu", + "--no-first-run", + "--remote-debugging-port=0", + "--remote-allow-origins=*", + f"--user-data-dir={tmp_path / 'profile'}", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + ws = None + try: + port_file = tmp_path / "profile" / "DevToolsActivePort" + for _ in range(100): + if port_file.exists(): + break + time.sleep(0.1) + port = port_file.read_text().splitlines()[0] + with urllib.request.urlopen(f"http://127.0.0.1:{port}/json") as response: + targets = json.load(response) + ws = websocket.create_connection( + next(t["webSocketDebuggerUrl"] for t in targets if t["type"] == "page"), timeout=15 + ) + seq = 0 + + def call(method, **params): + nonlocal seq + seq += 1 + ws.send(json.dumps(dict(id=seq, method=method, params=params))) + while True: + result = json.loads(ws.recv()) + if result.get("id") == seq: + assert "error" not in result, result + return result.get("result", {}) + + def js(expression): + result = call( + "Runtime.evaluate", expression=expression, awaitPromise=True, returnByValue=True + ) + assert "exceptionDetails" not in result, result + return result.get("result", {}).get("value") + + def ready(): + for _ in range(100): + if js("!!document.getElementById('loading')?.hidden && !!state.epData"): + return + time.sleep(0.1) + pytest.fail("Viewer did not initialize") + + call("Page.enable") + call( + "Emulation.setDeviceMetricsOverride", + width=1500, + height=1000, + deviceScaleFactor=1, + mobile=False, + ) + call("Page.navigate", url=f"http://127.0.0.1:{server.server_port}/") + ready() + assert js("""(async()=>{ + const assert=(v,m)=>{if(!v)throw Error(m);}; + assert(qualityEvents().length===2,'default reversal visibility'); + assert(!$('video-camera-summary').hidden,'camera summary'); + $('event-camera-filter').value='wrist';$('event-camera-filter').onchange(); + assert(qualityEvents().length===1&&qualityEvents()[0].camera==='wrist','camera filter'); + seekQualityEvent(qualityEvents()[0]);assert(state.frame===10,'video event seek'); + assert($('quality-current').textContent.includes('wrist'),'camera-scoped evidence'); + $('event-camera-filter').value='proprio';$('event-camera-filter').onchange(); + seekQualityEvent(qualityEvents()[0]);assert(state.frame===50,'event seeking'); + $('episode-search').value='000001';renderEpisodeList(); + assert($('episode-list').children.length===1,'episode search'); + $('quality-show-reversals').checked=true;$('quality-show-reversals').onchange(); + assert(qualityEvents().length===2,'reversal toggle'); + $('event-filter').value='direction_reversal'; + $('event-filter').onchange({target:$('event-filter')}); + assert(qualityEvents().length===1,'event filtering'); + document.querySelector('.camera-caption button').click(); + assert(document.querySelector('.camera-card.focused'),'camera focus'); + $('camera-reset').click();assert(!document.querySelector('.focused'),'restore camera'); + assert($('action-legend').children.length===12,'all channels'); + $('action-legend').firstChild.click();assert(state.hidden.action.has(0),'channel toggle'); + $('state-scale').value='normalized';$('state-scale').onchange(); + assert($('state-chart')._chartParams,'normalized plot'); + seek(2);togglePlay();await new Promise(r=>setTimeout(r,250));stopPlayback(); + assert(state.frame>2,'playback'); + await Promise.all([loadEpisode(0),loadEpisode(1)]); + assert(state.ep===1,'episode loading order'); + return true; + })()""") + call( + "Emulation.setDeviceMetricsOverride", + width=390, + height=844, + deviceScaleFactor=1, + mobile=False, + ) + time.sleep(0.2) + assert js("document.documentElement.scrollWidth <= innerWidth") + # An image artifact helps diagnose CI/browser failures when retained. + (tmp_path / "mobile.png").write_bytes( + base64.b64decode(call("Page.captureScreenshot", format="png")["data"]) + ) + backend.quality_mode = False + call("Page.reload") + ready() + assert js("$('inspector').hidden && $('quality-panel').hidden && state.cameras.length===1") + assert js("!$('error-banner').textContent") + finally: + if ws: + ws.close() + chrome.terminate() + try: + chrome.wait(timeout=5) + except subprocess.TimeoutExpired: + chrome.kill() + chrome.wait() + server.shutdown() + server.server_close()