"""CONTRACT 6.5: read complete sequences through the v1.1 reader, every component. Acceptance item 5 asks for a check the byte-level ones cannot give. ``verify.py`` compares a view's bytes against its own v1.0 source, which proves repackaging preserved them, but it never decodes media and never crosses views -- a release whose bundles are each individually byte-perfect and whose RGB, camera and annotations no longer line up would pass it. ``validate.py`` crosses components, but per view and against the schema, on a tree whose media may not be materialised. So this opens the finished release the way a consumer would, through ``BundleReader`` and the registry, and checks the joins: frames the RGB's real packet count (ffprobe, demux only -- ``nb_frames`` is absent in Matroska) equals the metainfo ``num_frames``, and so does every field's ``T`` axis, the length of ``frames.jsonl`` and both standalone validities pixels where the media is materialised, its decoded width and height equal the view's declared ``camera.image_size``, which the contract defines as ``[W, H]`` -- so the ffprobe ``width`` is compared with the first element and ``height`` with the second, and the exo views' 667-wide by 1024-tall portrait frames are a match rather than a transposed declaration. What the file really is -- codec, pixel format -- is recorded. The declared ``rgb`` storage profile is one of the gaps ``DECLARED_MEDIA_SCHEMA_GAPS`` names, so the media has to be measured rather than believed camera the directory the view lives in, its ``camera_id``, its ``camera`` block and the intrinsic component's ``schema_id`` all name the same camera presence every declared file opens, or is absent exactly as the media declaration says. A half-pulled sequence fails from either side sequence the sequence-wide joins: one capture, one segment, one span, one split, and a sequence id that is exactly ``______`` cameras ReInterHand's own join -- what RHD's shared visibility attribute is for it. The cameras of a sequence have to agree about which source frames they saw. Measured over all 500 sequences: the per-segment cells store the same source frames in the same order from every camera, and the per-frame cells' exo renders are a strict subset of the ego render. That is why ``sync_id`` works as a join across cameras here, and why the ARCTIC rule ("every camera the same frame count") must not be copied: ego renders at 30 fps and exo at 5, so their frame counts differ by design. What it does not do: it never decodes pixels, compares an image to anything, or forms an opinion about whether a mask looks right. CONTRACT 6.5 keeps that -- human visual acceptance -- separate from this, and this tool is on the packaging side of that line. """ from __future__ import annotations import argparse import json import shutil import subprocess import sys from pathlib import Path import torch sys.path.insert(0, str(Path(__file__).resolve().parent)) from reinterhand_common import ( # noqa: E402 CAMERA_BY_VIEW_TYPE, CAMERA_FAMILY_BY_VIEW_TYPE, DATASET_ID, DEFAULT_MEDIA_DECLARATION, EXO_CAMERAS_BY_POLICY, FRAMES_REF, RELEASE_ID, RELEASE_ROOT, SCHEMA_VERSION, SPLIT_SCHEME, SPLIT_VALUES, TMP_ROOT, MediaDeclaration, check_frames, load, ) from warehouse import BundleReader, Registry # noqa: E402 #: The sweep the documented closing chain writes into the release (step 3). The #: summary's whole-release ``reader_acceptance`` -- 500 sequences, 6,750 views, none #: failed -- is read out of this report, so it is evidence about the release rather #: than about one sequence, and only a whole-release run may write it (see the #: refusal in ``main``). SWEEP_REPORT = RELEASE_ROOT / "doc" / "validation" / "read_sequence_sweep.json" def wildcard(segment: str) -> bool: return "<" in segment and ">" in segment def registered_entry(registry, bundle_rel: str, keys: list) -> bool: """Is ``bundle_rel`` + ``keys`` an entry the registry declares? ``Registry.resolve`` answers the migrator's question -- given a *v1.0* ref, where did those bytes go. A consumer asks the other direction: the v1.1 metainfo names a bundle and a key path, and that pair has to be a registered entry. Same templates, matched from the target side. """ ref = Path(bundle_rel).parts for bundle in registry.bundles.values(): template = Path(bundle["path"]).parts if len(ref) != len(template) or ref[-1] != template[-1]: continue if not all(wildcard(w) or w == g for w, g in zip(template[:-1], ref[:-1])): continue for name in bundle["entries"]: wanted = name.split("/") if len(wanted) == len(keys) and all(wildcard(w) or w == k for w, k in zip(wanted, keys)): return True return False def probe(path: Path): """Demux-only facts about a media file: packet count, shape, codec. Packets, not decoded frames, and ``nb_read_packets`` rather than ``nb_frames`` because Matroska does not carry the latter. Returns ``None`` where ffprobe is not installed, which the caller records as "not decoded" rather than as a pass. """ if shutil.which("ffprobe") is None: return None out = subprocess.run( ["ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=width,height,codec_name,pix_fmt,nb_read_packets", "-of", "json", str(path)], capture_output=True, text=True, check=True).stdout stream = (json.loads(out).get("streams") or [{}])[0] return {"frames": int(stream["nb_read_packets"]), "width": stream.get("width"), "height": stream.get("height"), "codec": stream.get("codec_name"), "pix_fmt": stream.get("pix_fmt")} def load_tensor(path: Path): """A standalone ``.pt`` outside the registry, read the way the release stores it.""" with path.open("rb") as stream: return torch.load(stream, map_location="cpu", weights_only=True) def view_dirs(root: Path, sequence: str) -> list: sequence_dir = root / "data" / sequence if not sequence_dir.is_dir(): raise SystemExit(f"no such sequence in the release: {sequence}") #: ego sorts after the numeric camera ids under a plain string sort, and a reader #: wants the cameras in a stable order rather than in ASCII order return sorted((p for p in sequence_dir.iterdir() if p.is_dir()), key=lambda p: (len(p.name), p.name)) def all_sequences(root: Path) -> list: return sorted(p.name for p in (root / "data").iterdir() if p.is_dir()) def read_media(media, view: Path, name: str, component: dict, meta: dict, record: dict, problem) -> None: """A preserved media file, its standalone validity, and what the file really is. The validity is checked whatever the media's own state is. ``rgb_valid.pt`` and ``mask_valid.pt`` belong to the numeric layer this working copy ships, so an absent ``rgb.mkv`` must not skip them -- returning early on the media is exactly the bug that would let a half-pulled sequence read as complete. """ ref = view / component["data_ref"] state = media.state(view, meta["sequence_id"], component["data_ref"]) entry = {"component": name, "ref": component["data_ref"], "state": state, "bytes": ref.stat().st_size if ref.is_file() else None, "frames": None, "declared_T_axis": (list(component["axes"]).index("T") if "T" in (component.get("axes") or []) else None)} #: the declared axes name the frame axis; it has to be one this tool can count, or #: the frame checks below would be silently comparing nothing if entry["declared_T_axis"] is None: problem(f"{name}: declares no T axis, so its frame count cannot be checked") if state == "missing": problem(f"{name}: declared file {component['data_ref']} is missing") elif state == "unexpected": problem(f"{name}: {component['data_ref']} is present although the declaration " f"says this copy ships no media for {meta['sequence_id']}") elif state == "present": facts = probe(ref) if facts is None: entry["probe"] = "ffprobe not installed; file present but not opened" else: entry.update(facts) if facts["frames"] != meta["num_frames"]: problem(f"{name}: {facts['frames']} packets in {component['data_ref']}, " f"metainfo declares {meta['num_frames']}") declared_size = list(meta["camera"]["image_size"]) #: CONTRACT: ``camera.image_size`` is the logical RGB size ``[W, H]``, so the #: first element is the frame *width*. Comparing it with the height instead #: passes silently on the ego views (1024x1024, square) and fails on every #: exo view, whose frames really are 667 wide by 1024 tall. if [facts["width"], facts["height"]] != declared_size: problem(f"{name}: {component['data_ref']} decodes as " f"{facts['width']}x{facts['height']}, metainfo declares " f"{declared_size} [W, H]") record["media"].append(entry) valid_ref = component.get("valid_ref") if not valid_ref: entry["valid"] = None return valid_path = view / valid_ref if not valid_path.is_file(): problem(f"{name}: declared validity {valid_ref} is missing") return if valid_ref.endswith(".pt"): #: CONTRACT 4: media validity stays a standalone bool Tensor. It is not #: registered as a bundle, so it cannot be addressed by key payload = load_tensor(valid_path) entry["valid"] = {"ref": valid_ref, "kind": "pt", "dtype": str(payload.dtype), "shape": list(payload.shape)} if payload.dtype != torch.bool: problem(f"{name}: validity {valid_ref} is {payload.dtype}, not bool") if payload.ndim != 1 or payload.shape[0] != meta["num_frames"]: problem(f"{name}: validity {valid_ref} is {list(payload.shape)}, metainfo " f"declares {meta['num_frames']} frames on a T axis") if list(component.get("valid_axes") or []) != ["T"]: problem(f"{name}: valid_axes {component.get('valid_axes')!r} is not ['T'], " f"so its length is not the frame count") else: frames = (probe(valid_path) or {}).get("frames") entry["valid"] = {"ref": valid_ref, "kind": "media", "frames": frames} if frames != meta["num_frames"]: problem(f"{name}: validity {valid_ref} holds {frames} packets, metainfo " f"declares {meta['num_frames']}") def read_view(registry, reader, media, view: Path): """Open every component of one view; return ``(meta, what the reader found)``.""" meta = load(view / "metainfo.json") where = f"{view.parent.name}/{view.name}" record = {"view": where, "camera_id": meta.get("camera_id"), "view_type": meta.get("view_type"), "num_frames": meta.get("num_frames"), "fields": [], "media": [], "absent": [], "problems": []} problem = record["problems"].append for key, want in (("schema_version", SCHEMA_VERSION), ("release_id", RELEASE_ID), ("dataset_id", DATASET_ID)): if meta.get(key) != want: problem(f"{key} is {meta.get(key)!r}, expected {want!r}") #: the view's own directory name and its declared camera must agree; the whole release #: is laid out as //, so a mismatch would mean the calibration #: and the pixels come from different cameras if meta.get("camera_id") != view.name: problem(f"directory {view.name} but camera_id {meta.get('camera_id')!r}") model, camera_schema = CAMERA_BY_VIEW_TYPE.get(meta.get("view_type"), (None, None)) if model is None: problem(f"view_type {meta.get('view_type')!r} is none of " f"{sorted(CAMERA_BY_VIEW_TYPE)}") else: #: the camera model follows from the view type -- ego is the fisheye, every exo #: view is pinhole -- and a view whose block disagrees cannot be opened as either camera = meta.get("camera") or {} if camera.get("model") != model or camera.get("schema_id") != camera_schema: problem(f"camera block is {camera.get('model')!r}/{camera.get('schema_id')!r}, " f"a {meta['view_type']} view is {model!r}/{camera_schema!r}") #: the camera family is the first two fields of every ``sample_id``, so a view that #: names the other family would file its frames under the wrong identity family = (meta.get("source_rendering") or {}).get("camera_family") if family != CAMERA_FAMILY_BY_VIEW_TYPE.get(meta.get("view_type")): problem(f"camera_family {family!r} is not " f"{CAMERA_FAMILY_BY_VIEW_TYPE.get(meta.get('view_type'))!r}") for name, component in meta["components"].items(): ref = component.get("data_ref") if not component.get("available", True): #: an omitted component must not leave a file claiming otherwise if ref and (view / ref).exists(): problem(f"{name}: available=false but {ref} exists") record["absent"].append(name) continue if not ref: problem(f"{name}: available but declares no data_ref") continue #: a component carrying ``data_key`` is bundled numeric data; one with only #: ``data_ref`` is a preserved media/JSONL file. The registry entry is matched #: from the target side. if "data_key" not in component: read_media(media, view, name, component, meta, record, problem) continue leaves = [(name, component["data_ref"], component["data_key"], component["valid_key"], list(component.get("axes") or []))] for attribute, spec in (component.get("attributes") or {}).items(): leaves.append((f"{name}.{attribute}", spec["data_ref"], spec["data_key"], spec["valid_key"], list(spec.get("axes") or []))) for owner, bundle, data_key, valid_key, axes in leaves: try: data = reader.get(view, bundle, data_key) valid = reader.get(view, bundle, valid_key) except (KeyError, TypeError, FileNotFoundError) as error: problem(f"{owner}: reader could not open {bundle}: {error}") continue if not isinstance(data, torch.Tensor) or valid.dtype != torch.bool: problem(f"{owner}: {bundle} does not hold (Tensor, bool Tensor)") continue frames = data.shape[axes.index("T")] if "T" in axes else None if frames is not None and frames != meta["num_frames"]: problem(f"{owner}: {frames} frames on its T axis, metainfo declares " f"{meta['num_frames']}") if valid.shape != tuple(data.shape[: valid.ndim]): problem(f"{owner}: valid {list(valid.shape)} is not a prefix of data " f"{list(data.shape)}") if not registered_entry(registry, bundle, data_key[:-1]): problem(f"{owner}: {bundle}:{'/'.join(data_key[:-1])} is not a registered " f"bundle entry") record["fields"].append({ "component": owner, "entry": f"{bundle}:{'/'.join(data_key)}", "dtype": str(data.dtype), "shape": list(data.shape), "T": frames, "valid_true": int(valid.sum()), "valid_false": int((~valid).sum())}) return meta, record def check_sequence(metas: dict, ids_by_camera: dict) -> list: """The joins that only exist across a sequence's views. Everything here is measured over the release (see the module docstring); nothing is a schema rule, which is why a copied ARCTIC or RHD version of this function fails. """ problems = [] #: every camera of a sequence states the same sequence id, so any of them can be the #: one this function reads it off -- the disagreement is itself checked below meta = metas[sorted(metas)[0]] sequence = meta["sequence_id"] #: one capture, one segment, one span, one split, one render setting -- a sequence is #: one rendered segment of one capture, so a second value anywhere means the views of #: this sequence come from different source material. The rest of ``source_rendering`` #: is *not* sequence-wide: ``camera_family`` and ``official_render_rate_fps`` differ #: between the ego and exo renders by design, so comparing the whole block would fail #: every sequence of the release. for key in ("source_capture_id", "source_segment_id", "source_frame_span", "split"): seen = {json.dumps(metas[name].get(key), sort_keys=True) for name in metas} if len(seen) > 1: problems.append(f"{key}: the cameras of {sequence} disagree ({sorted(seen)})") policies = {(metas[name].get("source_rendering") or {}).get("background_policy") for name in metas} if len(policies) > 1: problems.append(f"background_policy: the cameras of {sequence} disagree " f"({sorted(str(p) for p in policies)})") capture = meta.get("source_capture_id") or "" policy = (meta.get("source_rendering") or {}).get("background_policy") if policy not in EXO_CAMERAS_BY_POLICY: problems.append(f"render setting {policy!r} is none of " f"{sorted(EXO_CAMERAS_BY_POLICY)}") span = meta.get("source_frame_span") or [None, None] if capture: #: the sequence id is the capture, the render setting and the span, in that order: #: 500 of 500 sequences rebuild exactly, so this states the identity rather than #: merely agreeing with it rebuilt = f"{capture}__{policy}__{span[0]}__{span[1]}" if rebuilt != sequence: problems.append(f"sequence id {sequence!r} is not {rebuilt!r}") locator = meta.get("split_source_locator") or {} if locator.get("capture_id") != capture: problems.append(f"split_source_locator names capture " f"{locator.get('capture_id')!r}, metadata names {capture!r}") if not locator.get("url"): problems.append("split_source_locator names no url, so the split cannot be " "traced to the official scheme") if meta.get("split_scheme") != SPLIT_SCHEME: problems.append(f"split_scheme {meta.get('split_scheme')!r} is not {SPLIT_SCHEME!r}") if meta.get("split") not in SPLIT_VALUES: problems.append(f"split {meta.get('split')!r} is none of {list(SPLIT_VALUES)}") #: the camera set: one ego view, and the render setting's own number of exo cameras. #: A sequence missing a camera would otherwise read as a smaller sequence. ego = sorted(c for c in metas if metas[c].get("view_type") == "ego") exo = sorted(c for c in metas if metas[c].get("view_type") != "ego") if ego != ["ego"]: problems.append(f"expected exactly one ego view, found {ego}") if policy in EXO_CAMERAS_BY_POLICY and len(exo) != EXO_CAMERAS_BY_POLICY[policy]: problems.append(f"{len(exo)} exo camera(s), a {policy} sequence has " f"{EXO_CAMERAS_BY_POLICY[policy]}") #: ReInterHand's cross-camera join. Every camera of a per-segment sequence stores #: the same source frames in the same order; a per-frame sequence stores the ego #: render in full and samples it for exo, so the exo frames are a strict subset. #: Both are what makes ``sync_id`` (:) a usable join, and #: both were measured over all 500 sequences rather than inferred from the FPS. if ego and len(ego) == 1: reference = ids_by_camera.get(ego[0]) or [] if not reference: problems.append("the ego view stored no source frames to join the others to") for camera in exo: ids = ids_by_camera.get(camera) or [] if policy == "envmap_per_segment": if ids != reference: problems.append(f"{camera}: its source frames are not the ego view's " f"({len(ids)} vs {len(reference)} stored)") elif policy == "envmap_per_frame": if not set(ids) <= set(reference): extra = sorted(set(ids) - set(reference))[:5] problems.append(f"{camera}: stores source frames the ego view does " f"not, e.g. {extra}") if len(ids) >= len(reference): problems.append(f"{camera}: {len(ids)} frames is not fewer than the " f"ego view's {len(reference)}, so nothing was sampled") return problems def sweep(root: Path, registry, media, sequence: str, quiet: bool) -> dict: """Read every view of one sequence, then the joins that span them.""" reader = BundleReader() records, metas, ids_by_camera, frames_measurements = [], {}, {}, {} for view in view_dirs(root, sequence): meta, record = read_view(registry, reader, media, view) frames_ref = (meta.get("sampling") or {}).get("frames_ref") or FRAMES_REF frames_path = view / frames_ref rows = [json.loads(line) for line in frames_path.read_text(encoding="utf-8").splitlines() if line.strip()] if frames_path.is_file() else [] #: the frame table's own rules live in reinterhand_common, so this tool reads it #: once for the ids it needs to join cameras and asks the shared checker for the #: verdict -- two copies of those rules would drift, and the ARCTIC/RHD ones do #: not hold here (no annotation index, per-cell strides) try: frames_measurements[view.name] = check_frames(view, meta, rows) except AssertionError as error: record["problems"].append(f"frames.jsonl: {error}") ids_by_camera[view.name] = [int(row["source_frame_id"]) for row in rows] record["frames_source_span"] = [ids_by_camera[view.name][0], ids_by_camera[view.name][-1]] if rows else None record["frames_measurement"] = frames_measurements.get(view.name) records.append(record) metas[view.name] = meta sequence_problems = check_sequence(metas, ids_by_camera) per_view_problems = [(r["view"], p) for r in records for p in r["problems"]] if not quiet: print(f"{sequence}: {len(records)} view(s)") for record in records: print(f" {record['view']:<28} {str(record['view_type']):<4} " f"cam={record['camera_id']} frames={record['num_frames']} " f"fields={len(record['fields'])} media={len(record['media'])} " f"absent={len(record['absent'])}") for field in record["fields"]: print(f" {field['component']:<26} {field['dtype']:<14} " f"{str(field['shape']):<20} invalid={field['valid_false']}") for entry in record["media"]: shape = "" if entry.get("width") is None else f" {entry['width']}x{entry['height']}" codec = "" if entry.get("codec") is None else f" {entry['codec']}/{entry.get('pix_fmt')}" print(f" {entry['component']:<26} {entry['ref']:<28} " f"{entry['state']:<15} {entry['bytes']} B frames={entry['frames']}" f"{shape}{codec}") measurement = record.get("frames_measurement") if measurement: print(f" frames.jsonl{'':<15} rows={measurement['rows']} " f"modal_step={measurement['modal_step']} " f"source_gaps={measurement['source_gaps']} " f"stored={measurement['spans']} cell={measurement['cell']}") for view, issue in per_view_problems: print(f"FAIL {view}: {issue}", file=sys.stderr) for issue in sequence_problems: print(f"FAIL {sequence}: {issue}", file=sys.stderr) return { "sequence": sequence, "views": records, "sequence_problems": sequence_problems, "view_problems": {record["view"]: record["problems"] for record in records}, "accepted": not sequence_problems and not per_view_problems, "scope": "repackaging equivalent by reading the release; not visual acceptance", } def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("sequence", nargs="?", help="sequence id (omit with --all)") parser.add_argument("--all", action="store_true", help="walk every sequence in the release") parser.add_argument("--root", type=Path, default=RELEASE_ROOT) parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json", help="v1.1 schema.json (default /doc/schema.json)") parser.add_argument("--media-declaration", type=Path, default=DEFAULT_MEDIA_DECLARATION, help="where this copy of the tree declares which preserved media it " f"ships (default: {DEFAULT_MEDIA_DECLARATION})") parser.add_argument("--strict-media", action="store_true", help="ignore the media declaration and require every declared media " "file to exist") parser.add_argument("--report", type=Path, help="write the full record here as JSON " "(default: tmp/reinterhand-tools/read_sequence.json with --all)") parser.add_argument("--quiet", action="store_true") args = parser.parse_args(argv) if not args.sequence and not args.all: parser.error("name a sequence, or pass --all to walk the release") target = args.report or (TMP_ROOT / "read_sequence.json" if args.all else None) #: "does the release read back the way a consumer reads it?" is a question about #: the whole release, so one sequence's record may not be written over the sweep. #: Decided here, before the first sequence is read, and asserted rather than #: commented: an explicit ``--report`` does not make a one-sequence run the sweep, #: and the refusing run leaves the file untouched. assert target is None or args.all or target.resolve() != SWEEP_REPORT.resolve(), ( f"--report names the release's reader sweep ({SWEEP_REPORT}), which the summary " f"reads its release-wide reader_acceptance from, but this run reads only " f"{args.sequence}; point --report outside the release, or drop the sequence " "argument to sweep --all") registry = Registry.load(args.schema) media = MediaDeclaration("all") if args.strict_media else MediaDeclaration.load(args.media_declaration) sequences = all_sequences(args.root) if args.all else [args.sequence] records = [sweep(args.root, registry, media, sequence, args.quiet) for sequence in sequences] accepted = all(record["accepted"] for record in records) failed = [record["sequence"] for record in records if not record["accepted"]] report = { "release": RELEASE_ID, "sequences": len(records), "sequences_accepted": len(records) - len(failed), "failed": failed, "media_declaration": media.origin, "records": records if args.all else records[0], "accepted": accepted, "scope": "repackaging equivalent by reading the release; not visual acceptance", } if target: target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") print(f"wrote {target}") if not args.quiet and args.all: print(f"{len(records) - len(failed)}/{len(records)} sequence(s) accepted") print("ACCEPTANCE_PASS" if accepted else "ACCEPTANCE_FAIL") return 0 if accepted else 1 if __name__ == "__main__": sys.dont_write_bytecode = True raise SystemExit(main())