#!/usr/bin/env python3 """Assemble ReInterHand's ``doc/`` tree from the canonical v1.1 spec and the v1.0 record. Every published v1.1 release carries the same three spec documents, and each dataset edits exactly the same three things in ``CONTRACT.md``: a status banner on line 1, its own 状态 line, and the v1.0 link retargeted from the shared ``../hand-warehouse-1.0/CONTRACT.md`` to the copy kept as ``V1_0_SEMANTICS.md``. Doing that by hand is how a release ends up with a banner that overstates what was actually verified, so this script derives the banner and the 状态 line from ``doc/FULL_MIGRATION_SUMMARY.json`` -- the record of what the run actually did -- and refuses to write a claim the record does not support. Adapted from ``RHD/shared-v1.1/script/provenance/operations/build_rhd_docs.py``, the second-generation builder. Three things differ for ReInterHand, and all three are about v1.0 material rather than about the v1.1 spec (which is shared, and checked against its canonical digests below): * ``RAW_MAPPING.md`` keeps its v1.0-era name, as RHD's does, instead of the ``RAW_TO_SHARED.md`` that ARCTIC, H2O and dex-ycb use. It is *checked*, not rewritten: the mapping record is the dataset's own, and a builder that regenerated it could silently drop a row. * The v1.0 ``script/`` tree is snapshotted into ``script/v1_0_snapshot/script`` alongside the v1.0 contract and schema in ``script/v1_0_snapshot/doc``. RHD's builder leaves that copy alone; ReInterHand's produces it, because its v1.0 ``script/`` is where the release's own producer lives (``preprocess_reinterhand.py``) and a snapshot that is made by hand is one nobody can re-derive. * ``doc/history-v1.0/`` is 752 MB, not 7 MB: ReInterHand's v1.0 ``doc/validation/`` carries 114 rendered review clips. ARCTIC carries 412 MB the same way, so the whole set is reproduced, verbatim and complete -- a "history" tree whose pages link to videos that were left behind is not a reproduction. Run: python shared-v1.1/script/provenance/operations/build_reinterhand_docs.py Order inside a run: the two carried-over trees are produced first, then ``doc/RAW_MAPPING.md`` is checked, then the four spec documents are written. The mapping record names ``script/v1_0_snapshot/`` as where the v1.0 scripts live, and this script is what puts them there, so checking it first would fail on a tree built from scratch -- the case where the check matters most. Idempotent: it rewrites the two transformed files, copies the two verbatim ones, refreshes ``doc/history-v1.0/`` and re-snapshots the v1.0 scripts, so re-running after the migration finishes refreshes the banner. """ from __future__ import annotations import argparse import hashlib import json import re import shutil import sys from pathlib import Path OPERATIONS = Path(__file__).resolve().parent SCRIPT_DIR = OPERATIONS.parent.parent # /script RELEASE_ROOT = SCRIPT_DIR.parent # /shared-v1.1 DATASET_ROOT = RELEASE_ROOT.parent # SPEC = SCRIPT_DIR / "reinterhand_v1_1" / "spec" DOC = RELEASE_ROOT / "doc" V10 = DATASET_ROOT / "shared-v1.0" HISTORY = DOC / "history-v1.0" SNAPSHOT = SCRIPT_DIR / "v1_0_snapshot" #: the canonical spec, shared by every dataset. Checked rather than trusted: if #: these do not match, the release would ship a spec it did not migrate against. CANONICAL = { "CONTRACT.md": "502dde9ac0549551237f684472489ddf6372bad3a26b1f6cca96f360c5dff158", "MIGRATION.md": "773f5146d49f5060bfc13ef92c143c59b683a6dc633cad44897414d5299088a0", "schema.json": "9f3769f950b36f75f3d571c77b5a661ca8e72afae20c9f1ddd1deef140e6cca8", } #: ``../hand-warehouse-1.0/CONTRACT.md`` in the canonical text; the release keeps #: its own copy of the v1.0 semantics beside it instead of reaching outside the tree V10_LINK = "../hand-warehouse-1.0/CONTRACT.md" V10_LINK_LOCAL = "V1_0_SEMANTICS.md" STATES = { #: no summary yet: the migration has not finished, so claim nothing about it "in_progress": { "banner": "> ReInterHand shared-v1.1 本地全量迁移进行中;自动验收、人工复查与 HF 发布均未完成。", "status": "状态:ReInterHand shared-v1.1 配套注册表与读写工具已适配;本地迁移、自动验收、人工复查与 HF 发布均未完成。", }, #: full acceptance recorded, human review and upload still outstanding "accepted_pending_review": { "banner": "> ReInterHand shared-v1.1 已完成本地全量迁移与自动验收(逐字段字节级比对);人工复查与 HF 发布尚未完成。", "status": "状态:ReInterHand shared-v1.1 配套注册表与读写工具已适配;本地全量数值一致性及结构检查通过,发布清单已在发布树外重建(`tmp/reinterhand-tools/PUBLISH_MANIFEST.json`,树内不含清单)。人工复查不属于自动验收,尚未完成;HF 发布尚未进行。", }, } def sha256(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1 << 22), b""): digest.update(chunk) return digest.hexdigest() def canonical_bytes(name): """The shared spec verbatim, with its canonical digest confirmed.""" path = SPEC / name got = sha256(path) if got != CANONICAL[name]: raise SystemExit(f"{path} is not the canonical {name}: {got} != {CANONICAL[name]}") return path.read_bytes() def canonical_text(name): """The shared spec as LF text, for a file this release transforms. The canonical ``CONTRACT.md`` and ``schema.json`` are CRLF; only the documents this release edits are normalised. A file that is *copied* keeps its bytes -- both published releases ship ``schema.json`` at the canonical 39043 bytes with its CRLF intact -- so the two paths are kept apart rather than sharing one round-trip through ``str``. """ return canonical_bytes(name).replace(b"\r\n", b"\n").decode("utf-8") def state_name(): """Which of STATES the recorded migration summary supports.""" summary = DOC / "FULL_MIGRATION_SUMMARY.json" if not summary.is_file(): return "in_progress" record = json.loads(summary.read_text(encoding="utf-8")) if record.get("phase") != "local_finalized_not_uploaded": raise SystemExit(f"{summary}: unexpected phase {record.get('phase')!r}") if record.get("human_full_approval"): raise SystemExit( f"{summary}: records a human approval, but no published wording is " "defined here; a published release needs its own banner" ) return "accepted_pending_review" def build_contract(state): """The canonical contract with the three dataset-specific edits applied.""" text = canonical_text("CONTRACT.md") lines = text.split("\n") status_index = next( index for index, line in enumerate(lines) if line.startswith("状态:") ) if lines[status_index].count("状态:") != 1 or not lines[status_index].startswith( "状态:合同草案" ): raise SystemExit(f"line {status_index + 1} is not the canonical 状态 line") if text.count(V10_LINK) != 1: raise SystemExit(f"the canonical text no longer links {V10_LINK} exactly once") lines[status_index] = STATES[state]["status"] body = "\n".join(lines).replace(V10_LINK, V10_LINK_LOCAL) #: banner, one blank line, then the canonical text; and no trailing newline, #: which is how both published releases ship it return f"{STATES[state]['banner']}\n\n{body}".rstrip("\n") def check_mapping_record(dry_run=False): """ReInterHand's own field mapping, kept under its v1.0-era name and cross-checked. This release does not rewrite the file, so the builder does the next best thing: it confirms the mapping record is there and that every ``script/...`` path it points a reader at actually exists. A restructured ``script/`` that left these references stale would send the reviewer to a file that is gone. ``dry_run`` only relaxes the case a dry run cannot satisfy: the carried-over trees are produced by this same script, and a dry run produces nothing, so a reference into ``script/v1_0_snapshot/`` is reported as pending instead of failing. Everything else is checked in both modes. """ path = DOC / "RAW_MAPPING.md" if not path.is_file(): raise SystemExit(f"{path} is missing; it is the 字段映射 CONTRACT 2 requires") text = path.read_text(encoding="utf-8") #: the record points a reader at entry points, not only at Python ones: it also #: names the tool package's README, which is the file that documents how to run #: the chain. Matching only ``.py`` would let that reference go stale unnoticed. referenced = sorted( set(re.findall(r"`(script/[A-Za-z0-9_./-]+\.(?:py|md|sh))`", text)) | set(re.findall(r"`(script/v1_0_snapshot/[A-Za-z0-9_./-]*)`", text)) ) if not referenced: raise SystemExit(f"{path} names no script/ entry point") missing = [rel for rel in referenced if not (RELEASE_ROOT / rel).exists()] if missing and not dry_run: raise SystemExit(f"{path} points at {len(missing)} file(s) that are not in " f"the release: {missing}") if missing: print(f" (dry run) {len(missing)} reference(s) do not exist yet and this run " f"is what creates them: {missing}") return path, referenced def sync_tree(source, target, label): """Reproduce ``source`` under ``target``, and drop what the source no longer has. Used for both carried-over sets: the v1.0 document tree and the v1.0 scripts. A copy that only ever adds cannot drift *towards* the source, but it can keep a file the source has since dropped, which would misrepresent what v1.0 was. """ if not source.is_dir(): raise SystemExit(f"{source} is missing; it is what {label} reproduces") wanted = {p.relative_to(source).as_posix() for p in source.rglob("*") if p.is_file()} for path in sorted(source.rglob("*")): if not path.is_file(): continue destination = target / path.relative_to(source) destination.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, destination) removed = [] if target.is_dir(): for path in sorted(target.rglob("*")): if path.is_file() and path.relative_to(target).as_posix() not in wanted: path.unlink() removed.append(path.relative_to(RELEASE_ROOT).as_posix()) return len(wanted), removed def sync_history(): """``doc/history-v1.0/`` is the v1.0 document set, reproduced. The published releases keep the previous version's documents here, so a reader can compare the two without leaving the release. ReInterHand's v1.0 ``doc/`` is the contract, its schema, the raw mapping and the release's own review pages -- 548 files, 752 MB of which 749 MB is the 114 review clips those pages link to. The whole set is carried (ARCTIC carries 412 MB the same way): dropping the clips would leave ``validation/index.html`` pointing at nothing. """ return sync_tree(V10 / "doc", HISTORY, "history-v1.0") def sync_snapshot(): """``script/v1_0_snapshot/`` is the v1.0 scripts and the v1.0 contract pair. RHD keeps these two sets as well, but its builder does not produce them. Here the snapshot is derived, so it can be re-made: the v1.0 ``script/`` is where this release's producer lives, and the contract and schema pair is the document set the data was written against. """ script_count, script_removed = sync_tree(V10 / "script", SNAPSHOT / "script", "the v1.0 scripts") doc_target = SNAPSHOT / "doc" doc_target.mkdir(parents=True, exist_ok=True) wanted = [] for name in ("CONTRACT.md", "schema.json"): source = V10 / "doc" / name if not source.is_file(): raise SystemExit(f"{source} is missing; the v1.0 contract pair is incomplete") shutil.copy2(source, doc_target / name) wanted.append(name) removed = [rel for rel in script_removed] for path in sorted(doc_target.iterdir()): if path.is_file() and path.name not in wanted: path.unlink() removed.append(path.relative_to(RELEASE_ROOT).as_posix()) return script_count, len(wanted), removed def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--dry-run", action="store_true", help="report what would be written and change nothing") args = parser.parse_args(argv) state = state_name() print(f"banner state: {state}") #: The carried-over trees are produced *before* the mapping record is checked, #: because that record is where a reader is told the v1.0 scripts live in #: ``script/v1_0_snapshot/`` -- and this script is what puts them there. Checking #: first would fail on a tree built from scratch, which is exactly the case the #: check exists for; it would also mean the first run of a fresh build reports a #: broken mapping record that is in fact correct. if args.dry_run: source = V10 / "doc" print(f" would sync doc/history-v1.0/ from {source} " f"({sum(1 for p in source.rglob('*') if p.is_file())} files)") print(f" would snapshot {V10 / 'script'} into script/v1_0_snapshot/script") else: count, removed = sync_history() print(f" doc/history-v1.0/: {count} files synced from {V10 / 'doc'}" f"{f', {len(removed)} stale file(s) removed' if removed else ''}") script_count, doc_count, removed = sync_snapshot() print(f" script/v1_0_snapshot/: {script_count} script files + {doc_count} " f"contract files synced from {V10}" f"{f', {len(removed)} stale file(s) removed' if removed else ''}") mapping, referenced = check_mapping_record(args.dry_run) print(f" doc/RAW_MAPPING.md: {sha256(mapping)[:16]} {mapping.stat().st_size} B " f"(ReInterHand's own record, name kept; {len(referenced)} script reference(s) resolve)") #: transformed documents are authored here and normalised to LF; copied ones #: are other artifacts reproduced byte for byte, line endings included transformed = { "CONTRACT.md": build_contract(state).encode("utf-8"), "MIGRATION.md": canonical_bytes("MIGRATION.md"), } copied = { "schema.json": canonical_bytes("schema.json"), "V1_0_SEMANTICS.md": (V10 / "doc" / "CONTRACT.md").read_bytes(), } for name, payload in transformed.items(): write(DOC / name, payload, "transformed", args.dry_run) for name, payload in copied.items(): write(DOC / name, payload, "copied", args.dry_run) if not args.dry_run: print(f" doc/CONTRACT.md banner: {STATES[state]['banner']}") return 0 def write(target, payload, kind, dry_run): if dry_run: print(f" would write doc/{target.name} ({len(payload)} bytes, {kind})") return before = sha256(target) if target.is_file() else None target.write_bytes(payload) after = sha256(target) print(f" doc/{target.name}: {len(payload)} bytes, {kind}, sha256 {after[:16]}" f"{'' if before != after else ' (unchanged)'}") if __name__ == "__main__": sys.dont_write_bytecode = True raise SystemExit(main())