Download ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py from ParityLab/Hand-Datasets-Raw: direct link, hf CLI and curl.
- Browser
- Download file 35.1 kB
-
https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py
- Command line
-
hf download hf://datasets/ParityLab/Hand-Datasets-Raw/ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py
-
curl -L -o migrate.py https://huggingface.co/datasets/ParityLab/Hand-Datasets-Raw/resolve/main/ReInterHand/shared-v1.1/script/reinterhand_v1_1/migrate.py
35.1 kB
| #!/usr/bin/env python3 | |
| """Migrate the adjacent shared-v1.0 tree of this dataset to shared-v1.1. | |
| Only the tensor layout changes (CONTRACT 1-5): numeric tensors and their validity | |
| move into per-group bundles, metainfo references gain ``data_key``/``valid_key`` | |
| with ``pt/tensor_bundle/v1`` storage, and the two version fields are bumped. | |
| Sampling, frame counts, dtypes, values, NaN bit patterns, validity judgements, | |
| units, coordinate frames, hand slots, split and ``valid_policy`` are carried over | |
| untouched (CONTRACT 6.3). | |
| The source tree is never written to: this is a copy-out. Unchanged media and | |
| JSONL are hardlinked by default, so nothing is re-encoded and no bytes are | |
| duplicated (MIGRATION 2, 6). Every view is checkpointed with source and output | |
| digests so ``--resume`` re-verifies rather than trusting file existence | |
| (MIGRATION 4.4). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import fcntl | |
| import json | |
| import os | |
| import shutil | |
| import sys | |
| import time | |
| import traceback | |
| from contextlib import contextmanager | |
| from pathlib import Path | |
| import torch | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from warehouse import ( # noqa: E402 | |
| BUNDLE_PROFILE, | |
| DATA_TERMINAL, | |
| RELEASE_ID, | |
| SCHEMA_VERSION, | |
| VALID_TERMINAL, | |
| BundleWriter, | |
| Registry, | |
| expanded_all_known, | |
| sha256_bytes, | |
| sha256_file, | |
| same_tensor, | |
| ) | |
| V10_SCHEMA_VERSION = "hand-warehouse/1.0" | |
| TOOL_ID = "hw11-migrate" | |
| TOOL_REVISION = "1" | |
| #: this package lives in <dataset>/shared-v1.1/script/reinterhand_v1_1, so the | |
| #: release and the dataset root beside it need no arguments. | |
| RELEASE_ROOT = Path(__file__).resolve().parent.parent.parent | |
| DATASET_ROOT = RELEASE_ROOT.parent | |
| # -------------------------------------------------------------------------- | |
| # filesystem helpers | |
| # -------------------------------------------------------------------------- | |
| def migration_lock(work: Path): | |
| """MIGRATION 3: one migrator per dataset, held for the whole run. | |
| The lock file lives in ``tmp/`` beside the checkpoints it protects, outside | |
| the release tree. A second run is refused rather than interleaved: two | |
| processes writing the same destination view would each leave behind a | |
| checkpoint describing a tree the other had already overwritten, and a | |
| checkpoint that cannot be trusted is worse than none. | |
| """ | |
| work.mkdir(parents=True, exist_ok=True) | |
| path = work / "migration.lock" | |
| with path.open("a+", encoding="utf-8") as stream: | |
| try: | |
| fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| except BlockingIOError as error: | |
| holder = path.read_text(encoding="utf-8").strip() or "unknown" | |
| raise SystemExit( | |
| f"another migration already holds {path} ({holder}); " | |
| "refusing to run two at once (MIGRATION 3)" | |
| ) from error | |
| stream.seek(0) | |
| stream.truncate() | |
| stream.write(f"pid {os.getpid()} started {time.strftime('%Y-%m-%dT%H:%M:%S%z')}\n") | |
| stream.flush() | |
| try: | |
| yield | |
| finally: | |
| fcntl.flock(stream, fcntl.LOCK_UN) | |
| def _clone(src: Path, dst: Path) -> None: | |
| """FICLONE (reflink) copy where the filesystem supports it.""" | |
| with open(src, "rb") as reader, open(dst, "wb") as writer: | |
| fcntl.ioctl(writer.fileno(), 0x40049409, reader.fileno()) | |
| def materialise(src: Path, dst: Path, mode: str) -> str: | |
| """Place an unchanged file at ``dst`` without ever re-encoding it. | |
| An existing destination is never trusted on existence alone: it must be the | |
| same inode as the source, or match it by SHA256, otherwise it is replaced. | |
| """ | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| if dst.exists(): | |
| if os.path.samefile(src, dst): | |
| return "same-inode" | |
| if dst.stat().st_size == src.stat().st_size and sha256_file(dst) == sha256_file(src): | |
| return "present-verified" | |
| temp = dst.with_name(dst.name + ".hw11-tmp") | |
| temp.unlink(missing_ok=True) | |
| shutil.copy2(src, temp) | |
| os.replace(temp, dst) | |
| if mode in ("hardlink", "reflink"): | |
| link = os.link if mode == "hardlink" else (lambda a, b: _clone(Path(a), Path(b))) | |
| try: | |
| link(src, dst) | |
| return mode | |
| except OSError: | |
| pass | |
| shutil.copy2(src, dst) | |
| return "copy" | |
| def load_tensor(path: Path) -> torch.Tensor: | |
| tensor = torch.load(path, map_location="cpu", weights_only=True) | |
| if not isinstance(tensor, torch.Tensor): | |
| raise TypeError(f"{path}: expected a Tensor, got {type(tensor).__name__}") | |
| return tensor | |
| # -------------------------------------------------------------------------- | |
| # registry conformance | |
| # -------------------------------------------------------------------------- | |
| #: what a registered schema *is*, as opposed to what it is called | |
| SCHEMA_IDENTITY_FIELDS = ("dtype", "shape", "valid_shape", "unit") | |
| def schema_id_note(registry: Registry, owner: str, spec: dict, entry: dict, | |
| bundle_rel: str, field: str): | |
| """Reconcile a v1.0 ``schema_id`` with the bundle entry's ``schema_ids`` list. | |
| A mismatch is recorded as a note, not raised. CONTRACT 6.3 forbids changing | |
| ``schema_id``, so a v1.0 label the registry words differently cannot be | |
| corrected here; ``schema_ids`` is documented nowhere in CONTRACT.md or | |
| MIGRATION.md; and the registry's own ``note`` calls it "a declarative registry, | |
| not a JSON Schema document or executable validator". The check keeps its real | |
| purpose by refusing only when the declared schema is not *structurally* the | |
| field the entry allows (dtype, shape, valid_shape, unit) -- which is what a | |
| wrong bundle entry actually looks like. | |
| The case this was written for is a v1.0 that labels a field with one of the | |
| entry's ``schema_ids`` while declaring a ``convention`` the registry pairs with | |
| a *different* one of them, the two definitions being identical in every identity | |
| field. ``notes`` stays empty as long as no view does that; the pilot asserts it, | |
| and the check is the guard that keeps a schema mismatch from being silently | |
| accepted if one ever appears. | |
| """ | |
| allowed = entry.get("schema_ids") | |
| schema_id = spec.get("schema_id") | |
| if allowed is None or schema_id in allowed: | |
| return None | |
| declared = registry.components.get(schema_id) | |
| if declared is None: | |
| raise ValueError(f"{owner}: schema_id {schema_id!r} is not registered") | |
| equivalent = [name for name in allowed | |
| if all(declared.get(key) == (registry.components.get(name) or {}).get(key) | |
| for key in SCHEMA_IDENTITY_FIELDS)] | |
| if not equivalent: | |
| raise ValueError( | |
| f"{owner}: schema_id {schema_id!r} not allowed in {bundle_rel}:{field} and " | |
| f"is not structurally equivalent to any of {list(allowed)}") | |
| return { | |
| "owner": owner, | |
| "entry": f"{bundle_rel}:{field}", | |
| "declared_schema_id": schema_id, | |
| "entry_schema_ids": list(allowed), | |
| "structurally_equivalent_to": equivalent, | |
| "reason": "CONTRACT 6.3 forbids changing schema_id; the entry allows a " | |
| "schema identical in dtype, shape, valid_shape and unit", | |
| } | |
| def shared_distortion_valid(registry: Registry, owner: dict, entry: dict, | |
| data: torch.Tensor, owner_valid): | |
| """The bool an existing camera model pairs between intrinsic and distortion. | |
| CONTRACT 3: "既有相机模型要求内参与单独畸变向量共用有效性时,在两个字段内保存 | |
| 相同 bool 值并校验一致". This is the path for a v1.0 that declares | |
| ``distortion_ref`` with no distortion validity of its own: the owning component's | |
| intrinsic validity is the pairing the model already had, so this restates it | |
| rather than expanding an all-true tensor that was never declared. | |
| ReInterHand's ego views reach this helper, and it is the interesting case. Their | |
| v1.0 splits the two roles across two declarations: ``intrinsic`` carries the | |
| pointer (``distortion_ref``, no validity) while the standalone ``distortion`` | |
| component carries the bool (``valid_ref = camera/distortion_valid.pt``). The | |
| search below keys on the pointer, so ``camera_meta`` is ``intrinsic``, its | |
| ``distortion_valid_ref`` is absent, and the pairing falls to this helper -- which | |
| is exactly the CONTRACT 3 relationship the model requires. The verdict is | |
| checked against the component's own declaration rather than trusted; see the | |
| staged-identity guard at the call site. | |
| """ | |
| required = (registry.components.get(owner.get("schema_id")) or {}).get( | |
| "required_metadata") or [] | |
| if not any(key.startswith("distortion") for key in required) or owner_valid is None: | |
| return None | |
| declared = _distortion_valid_shape(registry, entry, data) | |
| if declared is None or list(owner_valid.shape) != declared: | |
| return None | |
| return owner_valid | |
| def _distortion_valid_shape(registry: Registry, entry: dict, data: torch.Tensor): | |
| """Resolve the declared ``valid_shape`` of whichever distortion schema fits ``data``. | |
| Which of the entry's schemas applies is decided structurally, by the declared | |
| ``shape`` matching the tensor, so nothing is assumed from the model's name. | |
| """ | |
| for schema_id in entry.get("schema_ids") or []: | |
| shape = (registry.components.get(schema_id) or {}).get("shape") | |
| if not shape or len(shape) != data.ndim: | |
| continue | |
| if not all(isinstance(dim, str) or int(dim) == size | |
| for dim, size in zip(shape, data.shape)): | |
| continue | |
| valid_shape = (registry.components.get(schema_id) or {}).get("valid_shape") or [] | |
| return [data.shape[axis] if isinstance(dim, str) else int(dim) | |
| for axis, dim in enumerate(valid_shape)] | |
| return None | |
| # -------------------------------------------------------------------------- | |
| # per-view migration | |
| # -------------------------------------------------------------------------- | |
| def _declared_shape(registry: Registry, owner: str, spec: dict, kind: str): | |
| """The registry's declared ``(shape, valid_shape)`` for this field.""" | |
| if kind == "attribute": | |
| return None, registry.visibility_valid_shape(spec["axes"]) | |
| schema_id = spec.get("schema_id") | |
| entry = registry.components.get(schema_id) | |
| if entry is None: | |
| raise KeyError(f"{owner}: schema_id {schema_id!r} is not registered") | |
| return entry.get("shape"), entry.get("valid_shape") | |
| def _rewrite_reference(spec: dict, bundle_rel: str, keys: list, valid: torch.Tensor) -> dict: | |
| """CONTRACT 5: same-file data/valid refs plus explicit dictionary keys.""" | |
| before = { | |
| "data_ref": spec.get("data_ref"), | |
| "valid_ref": spec.get("valid_ref"), | |
| "valid": spec.pop("valid", "<absent>"), | |
| "valid_axes": spec.get("valid_axes"), | |
| } | |
| spec["data_ref"] = bundle_rel | |
| spec["data_key"] = list(keys) + [DATA_TERMINAL] | |
| spec["valid_ref"] = bundle_rel | |
| spec["valid_key"] = list(keys) + [VALID_TERMINAL] | |
| spec["storage"] = {"profile": BUNDLE_PROFILE} | |
| spec["valid_storage"] = {"profile": BUNDLE_PROFILE} | |
| # visibility metadata requires valid_axes (tensor_attributes.visibility); | |
| # v1.0 wrote it as axes[:valid.ndim], so deriving it restates the same value. | |
| axes = spec.get("axes") | |
| if axes and not spec.get("valid_axes"): | |
| spec["valid_axes"] = list(axes)[:valid.ndim] | |
| return before | |
| def _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes, | |
| owner, spec, kind, num_frames): | |
| """Stage one registered numeric field into its bundle. No-op when unmerged. | |
| Returns the field's bool validity Tensor, or ``None`` when the reference is not | |
| a registered numeric field (media / JSONL / assets, preserved verbatim). The | |
| caller needs that Tensor because this function rewrites ``spec`` in place via | |
| `_rewrite_reference`, so the same spec can no longer be resolved to its source | |
| field once staged. | |
| """ | |
| ref = spec.get("data_ref") | |
| if not ref: | |
| return None | |
| resolved = registry.resolve(ref) | |
| if resolved is None: | |
| return None # media / JSONL / assets: preserved verbatim | |
| bundle_rel, keys, entry = resolved | |
| field = "/".join(keys) | |
| note = schema_id_note(registry, owner, spec, entry, bundle_rel, field) | |
| if note is not None: | |
| notes.append(note) | |
| if entry.get("attribute_id") and kind != "attribute": | |
| raise ValueError(f"{owner}: {bundle_rel}:{field} is an attribute entry") | |
| if kind == "attribute" and not entry.get("attribute_id"): | |
| raise ValueError(f"{owner}: {bundle_rel}:{field} is not declared as an attribute") | |
| source = src_view / ref | |
| if not source.is_file(): | |
| raise FileNotFoundError(f"{owner}: {ref} is registered but missing") | |
| data = load_tensor(source) | |
| declared_shape, declared_valid_shape = _declared_shape(registry, owner, spec, kind) | |
| if declared_shape and declared_shape[0] == "T" and data.shape[0] != num_frames: | |
| raise ValueError( | |
| f"{owner}: {ref} has {data.shape[0]} frames but metainfo says {num_frames}") | |
| valid_ref = spec.get("valid_ref") | |
| if valid_ref: | |
| valid = load_tensor(src_view / valid_ref) | |
| consumed.add(valid_ref) | |
| origin = f"source tensor {valid_ref}" | |
| else: | |
| if spec.get("valid") is not True: | |
| raise ValueError(f"{owner}: {ref} has neither valid_ref nor a declared all-known scalar") | |
| valid = expanded_all_known(data, declared_valid_shape) | |
| origin = "expanded declared all-known scalar (CONTRACT 3)" | |
| writer = writers.get(bundle_rel) | |
| if writer is None: | |
| writer = writers[bundle_rel] = BundleWriter(dst_view, bundle_rel) | |
| # The registry fixes one entry per numeric field, so two components may share | |
| # it (RHD's uv and xyz both read the same source visibility). Staging it | |
| # once is correct; a second owner with different bytes is a registry mismatch. | |
| identity = (bundle_rel, field) | |
| prior = staged.get(identity) | |
| if prior is None: | |
| writer.put(keys, data, valid) | |
| staged[identity] = {"data": data, "valid": valid, "owners": [owner], | |
| "source_data_ref": ref, "source_valid_ref": valid_ref} | |
| shared_with = None | |
| else: | |
| if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)): | |
| raise ValueError( | |
| f"{owner}: {identity[0]}:{field} is already staged from " | |
| f"{prior['source_data_ref']} with different values") | |
| prior["owners"].append(owner) | |
| shared_with = list(prior["owners"]) | |
| consumed.add(ref) | |
| before = _rewrite_reference(spec, bundle_rel, keys, valid) | |
| records.append({ | |
| "owner": owner, | |
| "kind": kind, | |
| "entry": f"{bundle_rel}:{field}", | |
| "source_data_ref": before["data_ref"], | |
| "source_valid_ref": before["valid_ref"], | |
| "source_scalar_valid": before["valid"], | |
| "source_valid_axes": before["valid_axes"], | |
| "valid_origin": origin, | |
| "shared_entry_owners": shared_with, | |
| "dtype": str(data.dtype), | |
| "shape": list(data.shape), | |
| "valid_shape": list(valid.shape), | |
| "valid_true": int(valid.sum()), | |
| "valid_false": int((~valid).sum()), | |
| "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, | |
| }) | |
| return valid | |
| def normalize_storage_revision(registry: Registry, meta: dict) -> bool: | |
| """Point the view's ``storage_revision`` at the revision the registry itself declares. | |
| v1.0's converter stamped ``lossless-video-2026-09-25`` into all 6,750 views, and | |
| ``doc/schema.json`` -- including the copy v1.0 shipped -- declares no such revision: | |
| its own is ``lossless-video-2026-09-18``, the value the published v1.1 siblings | |
| (RHD, ARCTIC) carry in every view. Nothing else about the key is a claim this | |
| migration may touch, so the value is read off the schema rather than restated here, | |
| and a view that declares no ``storage_revision`` keeps declaring none (the registry | |
| does not require the key, and H2O's published v1.1 omits it outright). Returns | |
| whether this view's value actually changed. | |
| """ | |
| if "storage_revision" not in meta: | |
| return False | |
| declared = registry.schema["storage_revision"] | |
| changed = meta["storage_revision"] != declared | |
| meta["storage_revision"] = declared | |
| return changed | |
| def migrate_view(registry, src_root, dst_root, sequence, camera, link_mode): | |
| """Migrate one ``<sequence>/<camera>`` view and return its report entry.""" | |
| src_view = src_root / sequence / camera | |
| dst_view = dst_root / sequence / camera | |
| meta_path = src_view / "metainfo.json" | |
| meta = json.loads(meta_path.read_text(encoding="utf-8")) | |
| if meta.get("schema_version") != V10_SCHEMA_VERSION: | |
| raise ValueError(f"{meta_path}: not {V10_SCHEMA_VERSION}") | |
| if (meta.get("sequence_id"), meta.get("camera_id")) != (sequence, camera): | |
| raise ValueError(f"{meta_path}: sequence_id/camera_id do not match the directory") | |
| num_frames = meta["num_frames"] | |
| dst_view.mkdir(parents=True, exist_ok=True) | |
| writers, consumed, records, staged, notes = {}, set(), [], {}, [] | |
| #: each component's staged validity, for a camera model that pairs it with the | |
| #: separate distortion vector (CONTRACT 3). Taken from _stage's return value: | |
| #: _stage rewrites the component in place, so re-resolving ``data_ref`` here | |
| #: would read the already-migrated bundle path and never match an entry. | |
| staged_valid = {} | |
| for name, component in meta["components"].items(): | |
| if not component.get("available", True): | |
| continue | |
| staged_valid[name] = _stage( | |
| registry, src_view, dst_view, writers, consumed, records, staged, notes, | |
| name, component, "component", num_frames) | |
| for attribute, spec in (component.get("attributes") or {}).items(): | |
| _stage(registry, src_view, dst_view, writers, consumed, records, staged, notes, | |
| f"{name}.{attribute}", spec, "attribute", num_frames) | |
| # camera distortion lives beside the intrinsic parameters (CONTRACT 5). v1.0 | |
| # declares it on the camera component that owns the calibration -- ARCTIC puts | |
| # ``distortion_ref`` on ``intrinsic`` -- so the components are searched first | |
| # and the ``camera`` block is only a fallback. | |
| # | |
| # ReInterHand's ego views are the second shape: v1.0 declares the distortion | |
| # twice, as a standalone ``distortion`` component *and* as | |
| # ``intrinsic.distortion_ref``. The loop above has therefore already staged | |
| # that entry (with the standalone component's own ``distortion_valid_ref``) | |
| # before this block runs, and the two declarations must agree. ARCTIC's | |
| # unconditional ``writer.put`` below would silently overwrite the component's | |
| # declaration with the intrinsic validity; that is value-neutral here (all 500 | |
| # ego views were verified byte-for-byte equal, see | |
| # ``tmp/reinterhand-tools/check_distortion_valid.py``) but it would discard a | |
| # declaration rather than checking it. So the entry goes through the same | |
| # staged-identity guard ``_stage`` uses. | |
| distortion_meta, distortion_owner = None, None | |
| for name, component in meta["components"].items(): | |
| if component.get("distortion_ref"): | |
| distortion_meta, distortion_owner = component, name | |
| break | |
| if distortion_meta is None and (meta.get("camera") or {}).get("distortion_ref"): | |
| distortion_meta = meta["camera"] | |
| if distortion_meta is not None: | |
| camera_meta = distortion_meta | |
| owner_label = (f"{distortion_owner}.distortion" if distortion_owner | |
| else "camera.distortion") | |
| ref = camera_meta["distortion_ref"] | |
| resolved = registry.resolve(ref) | |
| if resolved is None: | |
| raise ValueError(f"camera.distortion_ref {ref!r} does not resolve to a bundle") | |
| bundle_rel, keys, entry = resolved | |
| data = load_tensor(src_view / ref) | |
| valid_ref = camera_meta.get("distortion_valid_ref") | |
| if valid_ref: | |
| valid = load_tensor(src_view / valid_ref) | |
| consumed.add(valid_ref) | |
| origin = f"source tensor {valid_ref}" | |
| else: | |
| valid = shared_distortion_valid(registry, distortion_meta, entry, data, | |
| staged_valid.get(distortion_owner)) | |
| if valid is not None: | |
| origin = "shared with intrinsic validity (CONTRACT 3)" | |
| else: | |
| valid = expanded_all_known(data, camera_meta.get("distortion_valid_shape")) | |
| origin = "expanded declared all-known scalar (CONTRACT 3)" | |
| writer = writers.get(bundle_rel) or writers.setdefault( | |
| bundle_rel, BundleWriter(dst_view, bundle_rel)) | |
| identity = (bundle_rel, "/".join(keys)) | |
| prior = staged.get(identity) | |
| if prior is None: | |
| writer.put(keys, data, valid) | |
| staged[identity] = {"data": data, "valid": valid, "owners": [owner_label], | |
| "source_data_ref": ref, "source_valid_ref": valid_ref} | |
| shared_with = None | |
| else: | |
| if not (same_tensor(prior["data"], data) and same_tensor(prior["valid"], valid)): | |
| raise ValueError( | |
| f"{owner_label}: {identity[0]}:{identity[1]} is already staged from " | |
| f"{prior['source_data_ref']} with different values") | |
| prior["owners"].append(owner_label) | |
| shared_with = list(prior["owners"]) | |
| origin = (f"entry already staged from {prior['source_data_ref']}; " | |
| f"{origin} agrees byte-for-byte") | |
| consumed.add(ref) | |
| camera_meta["distortion_ref"] = bundle_rel | |
| camera_meta["distortion_key"] = list(keys) + [DATA_TERMINAL] | |
| camera_meta["distortion_valid_ref"] = bundle_rel | |
| camera_meta["distortion_valid_key"] = list(keys) + [VALID_TERMINAL] | |
| records.append({ | |
| "owner": owner_label, | |
| "kind": "component", | |
| "entry": f"{bundle_rel}:{'/'.join(keys)}", | |
| "source_data_ref": ref, | |
| "source_valid_ref": valid_ref, | |
| "source_scalar_valid": "<absent>", | |
| "source_valid_axes": camera_meta.get("distortion_valid_axes"), | |
| "valid_origin": origin, | |
| "shared_entry_owners": shared_with, | |
| "dtype": str(data.dtype), | |
| "shape": list(data.shape), | |
| "valid_shape": list(valid.shape), | |
| "valid_true": int(valid.sum()), | |
| "valid_false": int((~valid).sum()), | |
| "nan_count": int(torch.isnan(data).sum()) if data.is_floating_point() else None, | |
| }) | |
| # everything not consumed into a bundle is preserved byte-for-byte | |
| passthrough = {} | |
| for path in sorted(src_view.rglob("*")): | |
| if not path.is_file(): | |
| continue | |
| rel = path.relative_to(src_view).as_posix() | |
| if rel in consumed or rel == "metainfo.json": | |
| continue | |
| passthrough[rel] = materialise(path, dst_view / rel, link_mode) | |
| # MIGRATION 4.2: write, re-read, compare field by field, byte-exactly | |
| verification = [] | |
| for bundle_rel, writer in sorted(writers.items()): | |
| path = writer.save() | |
| if path is None: | |
| continue | |
| reloaded = torch.load(path, map_location="cpu", weights_only=True) | |
| for keys, leaf in _walk_leaf(writer.tree): | |
| node = reloaded | |
| for key in keys: | |
| node = node[key] | |
| for terminal in (DATA_TERMINAL, VALID_TERMINAL): | |
| if not same_tensor(leaf[terminal], node[terminal]): | |
| raise AssertionError(f"{bundle_rel}:{'/'.join(keys)}:{terminal} not byte-identical") | |
| verification.append({ | |
| "bundle": bundle_rel, | |
| "sha256": sha256_file(path), | |
| "size": path.stat().st_size, | |
| "fields": sum(1 for _ in _walk_leaf(writer.tree)), | |
| "comparison": "byte_view_exact_no_tolerance", | |
| }) | |
| meta["schema_version"] = SCHEMA_VERSION | |
| meta["release_id"] = RELEASE_ID | |
| storage_revision_changed = normalize_storage_revision(registry, meta) | |
| _write_json(dst_view / "metainfo.json", meta) | |
| return { | |
| "sequence_id": sequence, | |
| "camera_id": camera, | |
| "num_frames": num_frames, | |
| "storage_revision_changed": storage_revision_changed, | |
| "source_metainfo_sha256": sha256_file(meta_path), | |
| "source_metainfo_size": meta_path.stat().st_size, | |
| "output_metainfo_sha256": sha256_file(dst_view / "metainfo.json"), | |
| "bundles": verification, | |
| "fields": records, | |
| "schema_notes": notes, | |
| "passthrough_files": len(passthrough), | |
| "passthrough_modes": sorted(set(passthrough.values())), | |
| "replaced_source_refs": sorted( | |
| {r["source_data_ref"] for r in records} | {r["source_valid_ref"] for r in records if r["source_valid_ref"]}), | |
| } | |
| def _walk_leaf(tree, prefix=()): | |
| for key, value in tree.items(): | |
| if isinstance(value, dict) and set(value) == {DATA_TERMINAL, VALID_TERMINAL}: | |
| yield prefix + (key,), value | |
| elif isinstance(value, dict): | |
| yield from _walk_leaf(value, prefix + (key,)) | |
| def _write_json(path: Path, value) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temp = path.with_name(path.name + ".tmp") | |
| temp.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n", | |
| encoding="utf-8") | |
| temp.replace(path) | |
| # -------------------------------------------------------------------------- | |
| # dataset driver | |
| # -------------------------------------------------------------------------- | |
| def discover_views(src_root: Path): | |
| views = [] | |
| for meta in sorted(src_root.glob("data/*/*/metainfo.json")): | |
| views.append((meta.parent.parent.name, meta.parent.name)) | |
| return views | |
| def tool_digest(script_dir: Path, schema_path: Path) -> dict: | |
| return { | |
| "tool": f"{TOOL_ID}/{TOOL_REVISION}", | |
| "migrate_sha256": sha256_file(Path(__file__).resolve()), | |
| "layout_sha256": sha256_file(script_dir / "warehouse.py"), | |
| "schema_sha256": sha256_file(schema_path), | |
| "python": sys.version.split()[0], | |
| "torch": torch.__version__, | |
| } | |
| def source_manifest(path: Path | None) -> dict | None: | |
| """Describe the tree-API manifest the source bytes were pulled against. | |
| The registration has to be readable on its own: "this tree came from revision | |
| X" means little without the file list and digests that revision published, so | |
| the manifest's own digest and size travel with it (MIGRATION 3). | |
| """ | |
| if path is None: | |
| return None | |
| entries = json.loads(path.read_text(encoding="utf-8")) | |
| entries = entries["files"] if isinstance(entries, dict) else entries | |
| return { | |
| "path": str(path.resolve()), | |
| "sha256": sha256_file(path), | |
| "files": len(entries), | |
| "bytes": sum(int(entry.get("size", 0)) for entry in entries), | |
| } | |
| def checkpoint_ok(state_path: Path, expected: dict, digest: dict) -> bool: | |
| """MIGRATION 4.4: re-verify inputs, tool revision and artefacts, not existence.""" | |
| if not state_path.is_file(): | |
| return False | |
| try: | |
| prior = json.loads(state_path.read_text(encoding="utf-8")) | |
| except (json.JSONDecodeError, OSError): | |
| return False | |
| if prior.get("tool") != digest: | |
| return False | |
| # a checkpoint describes one destination; never let it vouch for another | |
| if prior.get("dst_view") != str(expected["dst_view"]): | |
| return False | |
| if prior.get("source_metainfo_sha256") != expected["source_metainfo_sha256"]: | |
| return False | |
| for bundle in prior.get("bundles", []): | |
| path = Path(prior["dst_view"]) / bundle["bundle"] | |
| if not path.is_file() or sha256_file(path) != bundle["sha256"]: | |
| return False | |
| meta = Path(prior["dst_view"]) / "metainfo.json" | |
| if not meta.is_file() or sha256_file(meta) != prior["output_metainfo_sha256"]: | |
| return False | |
| return True | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument("--src", type=Path, default=DATASET_ROOT, | |
| help="dataset root holding shared-v1.0 (default: the dataset " | |
| "this package is installed in)") | |
| parser.add_argument("--dst", type=Path, default=RELEASE_ROOT, | |
| help="output release directory (default <src>/shared-v1.1)") | |
| parser.add_argument("--schema", type=Path, default=RELEASE_ROOT / "doc" / "schema.json", | |
| help="v1.1 schema.json (default <dst>/doc/schema.json)") | |
| parser.add_argument("--link", default="hardlink", choices=["hardlink", "reflink", "copy"], | |
| help="how unchanged media/JSONL is placed (default hardlink)") | |
| parser.add_argument("--views", nargs="*", default=None, | |
| help="restrict to these sequence ids") | |
| parser.add_argument("--limit", type=int, default=None, help="migrate at most N views") | |
| parser.add_argument("--resume", action="store_true", | |
| help="skip views whose checkpoint re-verifies") | |
| parser.add_argument("--dry-run", action="store_true") | |
| parser.add_argument("--source-revision", default=None, metavar="SHA", | |
| help="the pinned revision the shared-v1.0 bytes came from; " | |
| "recorded in the registration (MIGRATION 3)") | |
| parser.add_argument("--source-manifest", type=Path, default=None, | |
| help="tree-API manifest of that revision; its digest and file " | |
| "count are recorded so the registration is self-contained") | |
| args = parser.parse_args(argv) | |
| src_release = args.src / "shared-v1.0" | |
| dst_release = args.dst or (args.src / "shared-v1.1") | |
| if not src_release.is_dir(): | |
| parser.error(f"{src_release} is not a directory") | |
| schema_path = args.schema or (dst_release / "doc" / "schema.json") | |
| if not schema_path.is_file(): | |
| parser.error(f"v1.1 schema not found at {schema_path} (pass --schema)") | |
| registry = Registry.load(schema_path) | |
| src_root, dst_root = src_release / "data", dst_release / "data" | |
| views = discover_views(src_release) | |
| if not views: | |
| parser.error(f"no <sequence>/<camera>/metainfo.json found under {src_root}") | |
| first = src_root / views[0][0] / views[0][1] / "metainfo.json" | |
| dataset_id = json.loads(first.read_text(encoding="utf-8"))["dataset_id"] | |
| work = args.src / "tmp" / "migration-v11" | |
| state_dir = work / "checkpoints" | |
| if args.views: | |
| wanted = set(args.views) | |
| views = [v for v in views if v[0] in wanted] | |
| if args.limit: | |
| views = views[:args.limit] | |
| digest = tool_digest(Path(__file__).resolve().parent, schema_path) | |
| print(f"dataset={dataset_id} views={len(views)} src={src_release} dst={dst_release}") | |
| print(f"tool={digest['tool']} link={args.link}") | |
| if args.dry_run: | |
| for sequence, camera in views: | |
| print(f" would migrate {sequence}/{camera}") | |
| return 0 | |
| with migration_lock(work): | |
| registration = { | |
| "dataset_id": dataset_id, | |
| "source": {"release": "shared-v1.0", "schema_version": V10_SCHEMA_VERSION, | |
| "schema_sha256": sha256_file(src_release / "doc" / "schema.json") | |
| if (src_release / "doc" / "schema.json").is_file() else None, | |
| "path": str(src_release.resolve()), | |
| "revision": args.source_revision, | |
| "manifest": source_manifest(args.source_manifest)}, | |
| "target": {"release": RELEASE_ID, "schema_version": SCHEMA_VERSION, | |
| "schema_sha256": sha256_file(schema_path), "path": str(dst_release.resolve())}, | |
| "tool": digest, | |
| "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), | |
| "views_total": len(views), | |
| "views": [], | |
| "errors": [], | |
| } | |
| done = skipped = failed = 0 | |
| for index, (sequence, camera) in enumerate(views, 1): | |
| state_path = state_dir / f"{sequence}__{camera}.json" | |
| dst_view = dst_root / sequence / camera | |
| try: | |
| if args.resume and checkpoint_ok(state_path, { | |
| "dst_view": str(dst_view), | |
| "source_metainfo_sha256": sha256_file(src_root / sequence / camera / "metainfo.json"), | |
| }, digest): | |
| skipped += 1 | |
| print(f"[{index}/{len(views)}] {sequence}/{camera} skip (checkpoint re-verified)") | |
| continue | |
| entry = migrate_view(registry, src_root, dst_root, sequence, camera, args.link) | |
| entry["dst_view"] = str(dst_view) | |
| entry["tool"] = digest | |
| entry["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) | |
| _write_json(state_path, entry) | |
| registration["views"].append({k: entry[k] for k in ( | |
| "sequence_id", "camera_id", "num_frames", "source_metainfo_sha256", | |
| "output_metainfo_sha256", "bundles", "passthrough_files", | |
| "replaced_source_refs", "schema_notes")}) | |
| done += 1 | |
| print(f"[{index}/{len(views)}] {sequence}/{camera} ok " | |
| f"fields={len(entry['fields'])} bundles={len(entry['bundles'])} " | |
| f"passthrough={entry['passthrough_files']}") | |
| except Exception as error: # noqa: BLE001 - recorded, never hidden | |
| failed += 1 | |
| registration["errors"].append({ | |
| "sequence_id": sequence, "camera_id": camera, | |
| "error": f"{type(error).__name__}: {error}", | |
| "traceback": traceback.format_exc(), | |
| }) | |
| print(f"[{index}/{len(views)}] {sequence}/{camera} FAILED: {error}", file=sys.stderr) | |
| _write_json(work / "registration.json", registration) | |
| registration["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) | |
| registration["stage"] = "complete" if failed == 0 else "failed" | |
| registration["counts"] = {"migrated": done, "skipped": skipped, "failed": failed} | |
| _write_json(work / "registration.json", registration) | |
| print(f"done={done} skipped={skipped} failed={failed}") | |
| print(f"registration: {work / 'registration.json'}") | |
| return 1 if failed else 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) |