Download RHD/shared-v1.1/script/rhd_v1_1/validate.py from ParityLab/Hand-Datasets-Raw: direct link, hf CLI and curl.
- Browser
- Download file 19.1 kB
-
https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/RHD/shared-v1.1/script/rhd_v1_1/validate.py
- Command line
-
hf download hf://datasets/ParityLab/Hand-Datasets-Raw/RHD/shared-v1.1/script/rhd_v1_1/validate.py
-
curl -L -o validate.py https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/RHD/shared-v1.1/script/rhd_v1_1/validate.py
19.1 kB
| """Validate the adjacent RHD shared-v1.1 tree and fingerprint its current bytes. | |
| Adapted from the shared-v1.0 version: numeric components are read through their | |
| registered bundle keys instead of one ``.pt`` per component, media/JSONL validity | |
| must still be a standalone bool Tensor, and a merged field may not leave a | |
| standalone ``*_valid.pt`` behind (CONTRACT 6.1, 6.5). RHD's own rules are added on | |
| top: | |
| * 87 views -- 81 ``training_*`` and 6 ``evaluation_*``, 512 independent images each, | |
| the official training/evaluation split restated in every view's ``split``; | |
| * ``frames.jsonl`` is one row per released image in source order, and | |
| ``annotation_index`` names the row of the official annotation array the frame | |
| draws from, which for RHD is the source image id itself; | |
| * the ``visibility`` attribute is a single bundled field shared by both keypoint | |
| components, so it is checked once per component and its validity is all true | |
| (CONTRACT 3). | |
| Scope: this checks the released content and layout. It does not independently prove | |
| official source correctness, and it is not human visual acceptance (CONTRACT 6). | |
| Run: python shared-v1.1/script/rhd_v1_1/validate.py --expect-views 87 \ | |
| --report shared-v1.1/doc/validation/validate_report.json | |
| ``--views``/``--limit`` are for checking a corner of the tree while working on it, and | |
| a run that uses either is a *subset* run: it asserts only what its selected views can | |
| support, marks its report partial, writes it to tmp rather than over the acceptance | |
| report, and leaves the release manifest alone. Run it with no selection for the | |
| acceptance pass -- that is the one that checks the 87-view count and the 41,258/2,728 | |
| frame census. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from rhd_common import ( # noqa: E402 | |
| REGISTRY, | |
| REGISTRY_READER, | |
| RELEASE_ROOT, | |
| TMP_ROOT, | |
| View, | |
| check_view, | |
| load, | |
| save, | |
| sha256, | |
| stray_validity, | |
| ) | |
| #: the manifest is written outside the release tree. A file inside the tree cannot | |
| #: describe its own final bytes, and a copy that excludes itself leaves one release | |
| #: file that no digest covers; H2O, dex-ycb and ARCTIC keep theirs in | |
| #: ``tmp/<dataset>-tools/`` for the same reason. | |
| MANIFEST_PATH = TMP_ROOT / "PUBLISH_MANIFEST.json" | |
| #: the expected frame census, keyed by the split the view metadata declares: the | |
| #: official 41,258 training images and 2,728 evaluation images, sharded 512 at a time | |
| EXPECTED_COUNTS = {"train": 41258, "test": 2728} | |
| #: the full release's view count. Both of these are claims about the *whole* release, | |
| #: so they are asserted on a full run only: a --views/--limit run validates the views it | |
| #: selected and reports itself as partial, because three sound views say nothing about | |
| #: whether the other 84 exist. The two scopes below keep that distinction in the report | |
| #: the manifest is built from. | |
| EXPECTED_VIEWS = 87 | |
| SCOPE = ("released content and layout; does not independently prove official source " | |
| "correctness or visual quality") | |
| PARTIAL_SCOPE = (SCOPE + "; this run covered a selected subset of the release, so it is " | |
| "not the release-wide acceptance run") | |
| #: where a subset run writes instead of the release's own report path. The name is load | |
| #: bearing: it must not be the acceptance report, which describes the whole release and is | |
| #: what FULL_MIGRATION_SUMMARY.json cites. | |
| PARTIAL_REPORT = TMP_ROOT / "validate-partial.json" | |
| ACCEPTANCE_REPORT = RELEASE_ROOT / "doc/validation/validate_report.json" | |
| FRAMES_REF = "camera/frames.jsonl" | |
| #: RHD's official split, as the sample id's directory and the frame's ``split`` | |
| SOURCE_DIRECTORY_SPLIT = {"training": "train", "evaluation": "test"} | |
| def release_files(): | |
| """Every file of the release, in path order -- one definition, used twice. | |
| Both the report (written before the manifest) and the manifest itself need this | |
| set. Two filters that could drift apart would let the report name a file count | |
| the manifest it cites does not have. | |
| """ | |
| for path in sorted(RELEASE_ROOT.rglob("*")): | |
| #: bytecode caches are not release content. Nothing else is skipped: the | |
| #: manifest lives outside the tree, so it never has to exclude itself and the | |
| #: release's byte total is the manifest's own total. | |
| if not path.is_file() or ".cache" in path.parts or "__pycache__" in path.parts: | |
| continue | |
| yield path | |
| def check_frames(view_dir, meta): | |
| """RHD's frames.jsonl: one row per released image, in source order. | |
| ``source_frame_id`` is the source image id the row descends from, and | |
| ``annotation_index`` names the row of the official annotation array it draws | |
| from -- for RHD the two coincide, and a divergence means the frame was matched | |
| to the wrong annotation record. | |
| """ | |
| rows = [ | |
| json.loads(line) | |
| for line in (view_dir / FRAMES_REF).read_text(encoding="utf-8").splitlines() | |
| if line.strip() | |
| ] | |
| assert len(rows) == meta["num_frames"], (view_dir, len(rows), meta["num_frames"]) | |
| sample_ids, previous = set(), None | |
| for index, row in enumerate(rows): | |
| assert row["frame_index"] == index, (view_dir, index, row["frame_index"]) | |
| assert row["sample_id"] not in sample_ids, (view_dir, "duplicate sample_id", row["sample_id"]) | |
| sample_ids.add(row["sample_id"]) | |
| source_frame = int(row["source_frame_id"]) | |
| if previous is not None: | |
| assert source_frame > previous, (view_dir, "source frames out of order", index) | |
| previous = source_frame | |
| assert row["source_locator"]["annotation_index"] == source_frame, ( | |
| view_dir, index, row["source_locator"]["annotation_index"], source_frame) | |
| #: sample_id carries the dataset, the source directory and the image id; the | |
| #: directory has to agree with the split the view metadata declares | |
| dataset, directory, image = row["sample_id"].split("/") | |
| assert dataset == meta["dataset_id"], (view_dir, index, row["sample_id"]) | |
| assert SOURCE_DIRECTORY_SPLIT[directory] == meta["split"], ( | |
| view_dir, index, row["sample_id"], meta["split"]) | |
| return rows | |
| def check_shard(meta): | |
| """The split bookkeeping has to name the shard this view actually came from.""" | |
| locator = meta["split_source_locator"] | |
| assert meta["split_scheme"] == "RHD_official_training_evaluation", meta["split_scheme"] | |
| directory = locator["member_prefix"].rstrip("/").split("/")[-1] | |
| assert SOURCE_DIRECTORY_SPLIT[directory] == meta["split"], (meta["sequence_id"], locator) | |
| assert meta["sequence_id"].startswith(directory + "_"), meta["sequence_id"] | |
| def rewrite_check(view_dir, meta, tmp): | |
| """Rebuild a view's bundles with the adapted writer and compare field bytes.""" | |
| view = View("RHD", meta["sequence_id"], meta["camera_id"], range(meta["num_frames"]), | |
| list(meta["camera"]["image_size"]), | |
| {"archive": "raw/data/RHD_v1-1.zip", "annotation": "rewrite-check"}, | |
| split=meta["split"], root=tmp) | |
| written = set() | |
| #: pass 1 -- register every numeric component; pass 2 -- attach attributes, which | |
| #: may name a component registered later in the metadata's own ordering. | |
| for name, component in meta["components"].items(): | |
| if "data_key" not in component: | |
| continue | |
| data, valid = REGISTRY_READER.field(view_dir, component) | |
| view.bundled(name, component["data_ref"], component["data_key"][:-1], | |
| component["schema_id"], data.numpy(), valid.numpy(), component["axes"]) | |
| for name, component in meta["components"].items(): | |
| for attribute, spec in (component.get("attributes") or {}).items(): | |
| if (attribute, spec["data_ref"]) in written: | |
| continue | |
| written.add((attribute, spec["data_ref"])) | |
| owners = [n for n, c in meta["components"].items() | |
| if (c.get("attributes") or {}).get(attribute, {}).get("data_ref") == spec["data_ref"]] | |
| attribute_data = REGISTRY_READER.get(view_dir, spec["data_ref"], spec["data_key"]) | |
| view.attribute_bundled(owners, attribute, spec["data_ref"], spec["data_key"][:-1], | |
| spec["axes"], attribute_data.numpy()) | |
| view.finish() | |
| compared = 0 | |
| bundles = sorted({c["data_ref"] for c in meta["components"].values() if "data_key" in c}) | |
| for bundle in bundles: | |
| released = REGISTRY_READER.bundle(view_dir, bundle) | |
| rebuilt = REGISTRY_READER.bundle(view.path, bundle) | |
| def leaves(node, prefix=()): | |
| for key, value in node.items(): | |
| if isinstance(value, dict) and set(value) == {"data", "valid"}: | |
| yield prefix + (key,), value | |
| elif isinstance(value, dict): | |
| yield from leaves(value, prefix + (key,)) | |
| got = dict(leaves(rebuilt)) | |
| assert set(got) == set(dict(leaves(released))), (meta["sequence_id"], bundle, sorted(got)) | |
| for keys, leaf in leaves(released): | |
| for terminal in ("data", "valid"): | |
| left, right = leaf[terminal], got[keys][terminal] | |
| assert left.dtype == right.dtype and left.shape == right.shape, (bundle, keys, terminal) | |
| assert left.contiguous().numpy().tobytes() == right.contiguous().numpy().tobytes(), ( | |
| bundle, keys, terminal) | |
| compared += 1 | |
| return {"sequence_id": meta["sequence_id"], "camera_id": meta["camera_id"], | |
| "bundles": bundles, "tensors_compared": compared} | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--views", nargs="*", default=None, help="restrict to these sequences") | |
| parser.add_argument("--limit", type=int, default=None, help="validate at most N views") | |
| parser.add_argument("--rewrite-check", type=int, default=0, metavar="N", | |
| help="also re-serialise N views with the adapted writer and compare field bytes") | |
| parser.add_argument("--expect-views", type=int, default=None, metavar="N", | |
| help=f"fail unless exactly N views were checked (default: {EXPECTED_VIEWS}, " | |
| "the full RHD release, for a run with no --views/--limit; a subset run " | |
| "defaults to the number of views it selected). Without it a run that " | |
| "silently covered a fraction of the tree would still report a pass.") | |
| parser.add_argument("--report", type=Path, default=None, | |
| help="where the structural report is written (default: the release's " | |
| "doc/validation/validate_report.json for a full run, " | |
| f"{PARTIAL_REPORT} for a subset run, which must not overwrite " | |
| "the acceptance report)") | |
| parser.add_argument("--no-manifest", action="store_true", | |
| help=f"do not rebuild the release manifest ({MANIFEST_PATH}). It " | |
| "hashes the whole release tree whatever --views says, so an " | |
| "incremental check would pay for a manifest the final run " | |
| "overwrites anyway. The accepting run must not pass this " | |
| "(CONTRACT 6.4).") | |
| args = parser.parse_args(argv) | |
| all_views = sorted((RELEASE_ROOT / "data").glob("*/*/metainfo.json")) | |
| wanted = set(args.views) if args.views else None | |
| if wanted is not None: | |
| #: a name that matches nothing is a typo, and silently checking the other views | |
| #: would let it pass as a green run over the wrong set | |
| known = {view.parent.parent.name for view in all_views} | |
| assert wanted <= known, ("no such view", sorted(wanted - known)) | |
| views = [view for view in all_views if view.parent.parent.name in wanted] | |
| else: | |
| views = all_views | |
| if args.limit: | |
| views = views[: args.limit] | |
| #: "is this release complete?" and "is this view sound?" are different questions. | |
| #: The frame census and the view count only mean anything over the whole tree, so a | |
| #: run with --views/--limit checks its own selection instead and says so everywhere | |
| #: its result is reported (see SCOPE/PARTIAL_SCOPE, the report's ``coverage``, and | |
| #: the manifest it deliberately does not rebuild). | |
| full = wanted is None and not args.limit | |
| expect_views = args.expect_views if args.expect_views is not None else ( | |
| EXPECTED_VIEWS if full else len(views)) | |
| counts, frames_total, files_total, rewrites = {}, 0, 0, [] | |
| #: the whole-tree sample census: an id released twice anywhere is a defect a | |
| #: per-view check cannot see, so it is taken over one shared set | |
| samples = set() | |
| for position, path in enumerate(views, 1): | |
| view_dir, meta = path.parent, load(path) | |
| if position % 20 == 1 or position == len(views): | |
| print(f" view {position}/{len(views)}: {view_dir.relative_to(RELEASE_ROOT)}", flush=True) | |
| for key in ("dataset_id", "split_scheme", "split_source_locator", "sampling", | |
| "camera", "components", "view_type", "storage_revision"): | |
| assert key in meta, (path, key) | |
| assert meta["dataset_id"] == "RHD", meta["dataset_id"] | |
| assert meta["view_type"] == "exo", meta["view_type"] | |
| assert meta["camera_id"] == view_dir.name, (path, meta["camera_id"]) | |
| assert meta["schema_version"] == "hand-warehouse/1.1", meta["schema_version"] | |
| assert meta["release_id"] == "shared-v1.1", meta["release_id"] | |
| check_shard(meta) | |
| rows = check_frames(view_dir, meta) | |
| counts[meta["split"]] = counts.get(meta["split"], 0) + len(rows) | |
| frames_total += len(rows) | |
| #: the same sample id may not appear twice anywhere in the release | |
| for row in rows: | |
| assert row["sample_id"] not in samples, (view_dir, "sample id released twice", row["sample_id"]) | |
| samples.add(row["sample_id"]) | |
| check_view(view_dir, meta, REGISTRY) | |
| present = sorted(p.relative_to(view_dir).as_posix() | |
| for p in view_dir.rglob("*") if p.is_file()) | |
| files_total += len(present) | |
| stray = [name for name in present if stray_validity(name)] | |
| assert not stray, (view_dir, "merged field left a standalone validity file", stray) | |
| if len(rewrites) < args.rewrite_check: | |
| rewrites.append(rewrite_check(view_dir, meta, TMP_ROOT / "rewrite-check")) | |
| if full: | |
| #: the release-wide census, asserted only where it can hold: a subset's counts | |
| #: are a fraction of these by construction, and comparing them would fail a | |
| #: working check for a reason that has nothing to do with the views it read | |
| assert counts == EXPECTED_COUNTS, counts | |
| #: per-view contract: the parts that hold release-wide rather than per view | |
| assert len(views) == expect_views, (len(views), expect_views) | |
| assert len(samples) == frames_total, (len(samples), frames_total) | |
| result = { | |
| "passed": True, | |
| "coverage": "full release" if full else "partial subset", | |
| "views": len(views), "counts": counts, | |
| "frames": frames_total, | |
| "files_per_view": files_total // len(views), | |
| "schema_version": REGISTRY.schema["view_metadata"]["schema_version"], | |
| "release_id": REGISTRY.schema["view_metadata"]["release_id"], | |
| "bundles_per_view": len({c["data_ref"] for c in load(views[0])["components"].values() | |
| if "data_key" in c}), | |
| "rewrite_check": rewrites, | |
| "scope": SCOPE if full else PARTIAL_SCOPE, | |
| } | |
| report_path = args.report or (ACCEPTANCE_REPORT if full else PARTIAL_REPORT) | |
| #: The tmp copy is a convenience for the migration loop, and its *name* is load | |
| #: bearing. It must not be "acceptance.json": the documented chain writes | |
| #: verify.py's byte-level acceptance report to tmp/rhd-tools/acceptance.json, so a | |
| #: structural report saved under that name silently destroys the evidence | |
| #: FULL_MIGRATION_SUMMARY.json is built from. | |
| save(TMP_ROOT / "validate-latest.json", result) | |
| save(report_path, result) | |
| skip_manifest = None | |
| if args.no_manifest: | |
| #: reported as skipped rather than as a manifest of 0 files, which would | |
| #: read like an empty release | |
| skip_manifest = "incremental check; not an acceptance run" | |
| elif not full: | |
| #: The manifest is a claim about the whole release -- it hashes every file -- and | |
| #: the documented chain reads it together with the acceptance report. A subset | |
| #: run must not leave the two disagreeing about what was accepted, so it reports | |
| #: the manifest as skipped instead of rebuilding one to sit beside a partial report. | |
| skip_manifest = "partial run; the release manifest is rebuilt by the full acceptance run" | |
| if skip_manifest: | |
| result["release_manifest"] = {"skipped": skip_manifest, "path": str(MANIFEST_PATH)} | |
| save(TMP_ROOT / "validate-latest.json", result) | |
| save(report_path, result) | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| return 0 if result["passed"] else 1 | |
| #: Named, and counted, here -- before the manifest is rebuilt -- because the | |
| #: manifest has to cover this report's final bytes, so the report cannot carry the | |
| #: manifest's digest. The count is exact all the same: nothing adds or removes a | |
| #: release file between this walk and the hash pass below. | |
| result["release_manifest"] = { | |
| "path": str(MANIFEST_PATH), | |
| "in_release_tree": False, | |
| "files": sum(1 for _ in release_files()), | |
| "note": "rebuilt by this run after this report was written, so it covers the " | |
| "report's final bytes; kept outside the release because a manifest " | |
| "inside it cannot hash itself", | |
| } | |
| save(TMP_ROOT / "validate-latest.json", result) | |
| save(report_path, result) | |
| manifest = [] | |
| for path in release_files(): | |
| rel = path.relative_to(RELEASE_ROOT).as_posix() | |
| manifest.append({"path": rel, "size": path.stat().st_size, "sha256": sha256(path)}) | |
| payload = { | |
| "release": REGISTRY.schema["view_metadata"]["release_id"], | |
| "scope": result["scope"], | |
| "location": f"{MANIFEST_PATH} (outside the release tree, as in the published " | |
| "H2O and dex-ycb sets)", | |
| "excludes": ["__pycache__/"], | |
| "files": manifest, | |
| "bytes": sum(entry["size"] for entry in manifest), | |
| } | |
| save(MANIFEST_PATH, payload) | |
| print(f"manifest: {len(manifest)} files, {payload['bytes']} B -> {MANIFEST_PATH}") | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.dont_write_bytecode = True | |
| raise SystemExit(main()) |