Download code/materialization/finalize_morphosis_dsv4_shards.py from ergt2025/baseline_pdexp_result: direct link, hf CLI and curl.
- Browser
- Download file 5.92 kB
-
https://huggingface.co/datasets/ergt2025/baseline_pdexp_result/resolve/main/code/materialization/finalize_morphosis_dsv4_shards.py
- Command line
-
hf download hf://datasets/ergt2025/baseline_pdexp_result/code/materialization/finalize_morphosis_dsv4_shards.py
-
curl -L -o finalize_morphosis_dsv4_shards.py https://huggingface.co/datasets/ergt2025/baseline_pdexp_result/resolve/main/code/materialization/finalize_morphosis_dsv4_shards.py
5.92 kB
| #!/usr/bin/env python3 | |
| """Merge independently sealed Morphosis conversion shards.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import lzma | |
| import os | |
| import shutil | |
| import time | |
| from collections import Counter | |
| from pathlib import Path | |
| def sha256_file(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| while chunk := handle.read(8 << 20): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--shards-dir", type=Path, required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| args = parser.parse_args() | |
| if args.output_dir.exists(): | |
| raise FileExistsError(args.output_dir) | |
| seals = [] | |
| for index in range(8): | |
| path = args.shards_dir / f"shard-{index:02d}/materialization-seal.json" | |
| seal = json.loads(path.read_text()) | |
| expected_roots = 13 if index < 4 else 12 | |
| if ( | |
| seal.get("kind") != "morphosis-dsv4-materialization" | |
| or seal.get("shard") | |
| != {"count": 8, "index": index, "input_roots_seen": 100} | |
| or seal.get("roots") != expected_roots | |
| ): | |
| raise ValueError(f"shard {index} identity/count differs") | |
| seals.append(seal) | |
| if any(seal["source"] != seals[0]["source"] for seal in seals[1:]): | |
| raise ValueError("source identities differ across shards") | |
| if any(seal["target"] != seals[0]["target"] for seal in seals[1:]): | |
| raise ValueError("target identities differ across shards") | |
| stage = args.output_dir.with_name( | |
| f"{args.output_dir.name}.stage-{os.getpid()}" | |
| ) | |
| if stage.exists(): | |
| shutil.rmtree(stage) | |
| stage.mkdir(parents=True) | |
| archives = [] | |
| totals: Counter[str] = Counter() | |
| content_audit: Counter[str] = Counter() | |
| token_audit_rows = [] | |
| try: | |
| for index, seal in enumerate(seals): | |
| shard_dir = args.shards_dir / f"shard-{index:02d}" | |
| for item in seal["archives"]: | |
| source = shard_dir / item["archive"] | |
| if source.stat().st_size != item["archive_bytes"]: | |
| raise ValueError(f"archive size differs: {source}") | |
| if sha256_file(source) != item["archive_sha256"]: | |
| raise ValueError(f"archive hash differs: {source}") | |
| target = stage / item["archive"] | |
| if target.exists(): | |
| raise ValueError(f"duplicate archive: {item['archive']}") | |
| os.link(source, target) | |
| archives.append(item) | |
| for key, value in seal["totals"].items(): | |
| if key.startswith("target_max_"): | |
| totals[key] = max(totals[key], int(value)) | |
| else: | |
| totals[key] += int(value) | |
| content_audit.update(seal.get("content_audit") or {}) | |
| audit_path = shard_dir / seal["request_token_audit"]["path"] | |
| with lzma.open(audit_path, "rt", encoding="utf-8") as handle: | |
| token_audit_rows.extend(json.loads(line) for line in handle if line) | |
| if len(archives) != 100 or len({row["root_id"] for row in archives}) != 100: | |
| raise ValueError("merged archive inventory is not exactly 100 roots") | |
| if len(token_audit_rows) != totals["requests"]: | |
| raise ValueError("request token audit row count differs") | |
| archives.sort(key=lambda row: row["root_id"]) | |
| token_audit_rows.sort( | |
| key=lambda row: ( | |
| row["root_id"], | |
| row["trace_id"], | |
| row["generate_index"], | |
| ) | |
| ) | |
| audit_output = stage / "request-token-audit.jsonl.xz" | |
| with lzma.open(audit_output, "wt", encoding="utf-8", preset=1) as handle: | |
| for row in token_audit_rows: | |
| handle.write( | |
| json.dumps(row, separators=(",", ":"), sort_keys=True) + "\n" | |
| ) | |
| with (stage / "archives.sha256").open("w") as handle: | |
| for item in archives: | |
| handle.write(f"{item['archive_sha256']} {item['archive']}\n") | |
| global_seal = { | |
| "schema_version": 1, | |
| "kind": "morphosis-dsv4-materialization", | |
| "created_at_s": time.time(), | |
| "source": seals[0]["source"], | |
| "target": seals[0]["target"], | |
| "roots": len(archives), | |
| "totals": dict(totals), | |
| "content_audit": dict(sorted(content_audit.items())), | |
| "request_token_audit": { | |
| "path": audit_output.name, | |
| "rows": len(token_audit_rows), | |
| "sha256": sha256_file(audit_output), | |
| }, | |
| "archives": archives, | |
| "shards": [ | |
| { | |
| "index": index, | |
| "roots": seal["roots"], | |
| "seal_sha256": sha256_file( | |
| args.shards_dir | |
| / f"shard-{index:02d}/materialization-seal.json" | |
| ), | |
| } | |
| for index, seal in enumerate(seals) | |
| ], | |
| } | |
| (stage / "materialization-seal.json").write_text( | |
| json.dumps(global_seal, indent=2, sort_keys=True) + "\n" | |
| ) | |
| os.replace(stage, args.output_dir) | |
| except BaseException: | |
| shutil.rmtree(stage, ignore_errors=True) | |
| raise | |
| print( | |
| json.dumps( | |
| { | |
| "output_dir": str(args.output_dir), | |
| "roots": len(archives), | |
| "requests": totals["requests"], | |
| "materialization_seal_sha256": sha256_file( | |
| args.output_dir / "materialization-seal.json" | |
| ), | |
| }, | |
| sort_keys=True, | |
| ) | |
| ) | |
| if __name__ == "__main__": | |
| main() | |