#!/usr/bin/env python3 """Materialize one portable AppGen NGC HF config as MS-SWIFT JSON.""" from __future__ import annotations import argparse import hashlib import json import os import tempfile from pathlib import Path, PurePosixPath from typing import Any, Mapping, Sequence SCHEMA_VERSION = "appgen-sft-ngc-hf-bundle-v1" EXPECTED_CONFIGS = { "ngc-f-qwen25-absolute", "ngc-f-qwen3-normalized", "ngc-vt-qwen25-absolute", "ngc-vt-qwen3-normalized", } EXPECTED_ROWS = 3588 def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _load_object(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"expected JSON object: {path}") return value def _safe_relative(value: str, prefix: str) -> PurePosixPath: path = PurePosixPath(value) if path.is_absolute() or ".." in path.parts or not path.parts or path.parts[0] != prefix: raise ValueError(f"unsafe portable {prefix} path: {value!r}") return path def _atomic_rows(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) temporary = Path(temporary_name) try: with os.fdopen(fd, "w", encoding="utf-8") as handle: json.dump(rows, handle, ensure_ascii=False, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) def materialize(bundle_root: Path, config: str, output: Path) -> dict[str, Any]: root = bundle_root.resolve(strict=True) manifest_path = root / "bundle_manifest.json" ready_path = root / "READY.json" manifest = _load_object(manifest_path) ready = _load_object(ready_path) if manifest.get("schema_version") != SCHEMA_VERSION: raise ValueError("bundle manifest schema mismatch") if ready.get("validated") is not True or ready.get("manifest_sha256") != _sha256( manifest_path ): raise ValueError("bundle is not READY or its manifest changed") manifest_configs = set(manifest.get("configs", {})) required_f = {"ngc-f-qwen25-absolute", "ngc-f-qwen3-normalized"} if not required_f.issubset(manifest_configs) or not manifest_configs.issubset(EXPECTED_CONFIGS): raise ValueError("bundle config set mismatch") if set(ready.get("configs", [])) != manifest_configs: raise ValueError("bundle READY config set mismatch") if config not in manifest_configs: raise ValueError(f"unknown config: {config}") spec = manifest["configs"][config] data_relative = _safe_relative(str(spec["data_file"]), "data") data_path = root.joinpath(*data_relative.parts) if _sha256(data_path) != spec.get("data_sha256"): raise ValueError("portable data SHA mismatch") rows: list[dict[str, Any]] = [] with data_path.open("r", encoding="utf-8") as handle: for index, line in enumerate(handle): try: row = json.loads(line) except json.JSONDecodeError as exc: raise ValueError(f"row {index}: malformed JSONL: {exc}") from exc if not isinstance(row, dict): raise ValueError(f"row {index}: expected object") images = row.get("images") if not isinstance(images, list) or len(images) != 1: raise ValueError(f"row {index}: expected one image") relative = _safe_relative(str(images[0]), "images") image_path = root.joinpath(*relative.parts) image_spec = manifest.get("images", {}).get(relative.as_posix()) if not isinstance(image_spec, Mapping): raise ValueError(f"row {index}: image absent from hash manifest") if _sha256(image_path) != image_spec.get("sha256"): raise ValueError(f"row {index}: image SHA mismatch") row["images"] = [str(image_path)] rows.append(row) if len(rows) != EXPECTED_ROWS or len(rows) != spec.get("rows"): raise ValueError(f"materialized row count mismatch: {len(rows)}") _atomic_rows(output, rows) return { "schema_version": "appgen-sft-ngc-hf-materialized-v1", "config": config, "rows": len(rows), "output": str(output), "output_sha256": _sha256(output), "source_data_sha256": spec["data_sha256"], } def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bundle-root", type=Path, required=True) parser.add_argument("--config", choices=sorted(EXPECTED_CONFIGS), required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args(argv) result = materialize(args.bundle_root, args.config, args.output) print(json.dumps(result, indent=2, sort_keys=True)) return 0 if __name__ == "__main__": raise SystemExit(main())