#!/usr/bin/env python3 """Prepare and publish the completed HiQBind compact datasets to Hugging Face. The published repository layout is intentionally simple and stable:: README.md docs/ code/compact_v1/ data/hiqbind_5k_v1/ autodock_vina_full_v1/ diffdock_full_v1/ ``--prepare`` makes a persistent local staging tree. Tensor shards are *hard-linked* from the completed local datasets, so the staging tree does not duplicate the roughly 93 GB payload. The two JSON files which could expose local source paths (``manifest.json`` and ``source_index.json``) are copied after recursively replacing absolute paths with a non-path marker. ``--upload`` accepts ``HF_TOKEN``, ``--token``, or a token saved by ``huggingface_hub.login()``. It authenticates with ``whoami`` and checks the target dataset repository before invoking ``HfApi.upload_large_folder``. The latter keeps its resume metadata below the staging tree, therefore retain the same ``--stage-root`` if an upload is interrupted. Examples -------- Inspect without writing or contacting Hugging Face:: /u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --dry-run Build and inspect the reusable staging tree:: /u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py --prepare --verify Upload after review (the token is intentionally not printed):: HF_TOKEN=... /u/hhao/anaconda3/envs/hgf/bin/python upload_copuladock.py \ --prepare --verify --upload --num-workers 8 """ from __future__ import annotations import argparse import json import os import shutil import sys from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable, Mapping, Sequence RELEASE_ROOT = Path(__file__).resolve().parent PROJECT_ROOT = RELEASE_ROOT.parent WORKSPACE_ROOT = PROJECT_ROOT.parent DEFAULT_DATASET_ROOT = PROJECT_ROOT / "datasets_compact_hiqbind_v1" DEFAULT_STAGE_ROOT = RELEASE_ROOT / "hf_stage_copuladock" DEFAULT_REPO_ID = "liofoil/copuladock" @dataclass(frozen=True) class DatasetSpec: """A completed compact dataset and its release-relative destination.""" source_name: str release_name: str DATASETS: tuple[DatasetSpec, ...] = ( DatasetSpec("autodock_vina_full_v1", "autodock_vina_full_v1"), DatasetSpec("diffdock_full_v1", "diffdock_full_v1"), ) # These are the minimal reproducible construction/reader components. They # intentionally exclude raw docking outputs and cluster logs. CODE_SOURCES: tuple[tuple[Path, Path], ...] = ( ( WORKSPACE_ROOT / "docking_base/scripts/materialize_hiqbind_gnncp.py", Path("code/compact_v1/materialize_hiqbind_gnncp.py"), ), ( PROJECT_ROOT / "system_split_code/build_compact_v1_direct.py", Path("code/compact_v1/build_compact_v1_direct.py"), ), ( PROJECT_ROOT / "system_split_code/build_compact_v1_direct.sbatch", Path("code/compact_v1/build_compact_v1_direct.sbatch"), ), ( PROJECT_ROOT / "system_split_code/build_graph_unified_enhanced.py", Path("code/compact_v1/build_graph_unified_enhanced.py"), ), ( PROJECT_ROOT / "system_split_code/convert_to_compact_v1.py", Path("code/compact_v1/convert_to_compact_v1.py"), ), ( PROJECT_ROOT / "system_split_code/compact_graph_dataset.py", Path("code/compact_v1/compact_graph_dataset.py"), ), ( PROJECT_ROOT / "system_split_code/build_system_index.py", Path("code/compact_v1/build_system_index.py"), ), ( PROJECT_ROOT / "system_split_code/validate_compact_dataset.py", Path("code/compact_v1/validate_compact_dataset.py"), ), ( PROJECT_ROOT / "system_split_code/smoke_test_compact_dataset.py", Path("code/compact_v1/smoke_test_compact_dataset.py"), ), ( PROJECT_ROOT / "system_split_code/test_build_compact_v1_direct.py", # Keep tests alongside the modules they import. The upstream tests # intentionally resolve convert_to_compact_v1.py by sibling path. Path("code/compact_v1/test_build_compact_v1_direct.py"), ), ( PROJECT_ROOT / "system_split_code/test_compact_graph_dataset.py", Path("code/compact_v1/test_compact_graph_dataset.py"), ), ) # Previous staging revisions placed the two tests under ``tests/``. Prune # only these exact, generated staging copies during --prepare so an old stage # cannot publish duplicate stale tests. No dataset data are ever removed. OBSOLETE_STAGE_FILES: tuple[Path, ...] = ( Path("code/compact_v1/tests/test_build_compact_v1_direct.py"), Path("code/compact_v1/tests/test_compact_graph_dataset.py"), ) class ReleaseError(RuntimeError): """A release-preparation or release-verification failure.""" def _relative_to(path: Path, root: Path) -> Path: """Return ``path`` relative to ``root`` or raise a contextual error.""" try: return path.relative_to(root) except ValueError as exc: raise ReleaseError(f"path escapes its expected root: {path} (root={root})") from exc def _is_absolute_path_text(value: str) -> bool: """Detect POSIX/Windows-looking absolute paths without interpreting IDs.""" return value.startswith("/") or (len(value) >= 3 and value[1:3] in (":\\", ":/")) def _sanitize_value(value: Any) -> Any: """Copy JSON-like values while removing every absolute-path string.""" if isinstance(value, dict): return {str(key): _sanitize_value(item) for key, item in value.items()} if isinstance(value, list): return [_sanitize_value(item) for item in value] if isinstance(value, str) and _is_absolute_path_text(value): return "" return value def _find_absolute_path_values(value: Any, prefix: str = "$") -> list[str]: """Return JSON locations that still contain an absolute path string.""" found: list[str] = [] if isinstance(value, Mapping): for key, item in value.items(): found.extend(_find_absolute_path_values(item, f"{prefix}.{key}")) elif isinstance(value, list): for index, item in enumerate(value): found.extend(_find_absolute_path_values(item, f"{prefix}[{index}]")) elif isinstance(value, str) and _is_absolute_path_text(value): found.append(prefix) return found def _read_json(path: Path) -> Any: try: with path.open("r", encoding="utf-8") as handle: return json.load(handle) except (OSError, json.JSONDecodeError) as exc: raise ReleaseError(f"cannot read JSON {path}: {exc}") from exc def _write_json(path: Path, payload: Any) -> None: """Write a small JSON file atomically inside the staging tree.""" path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") try: with temporary.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: # If json.dump failed before os.replace, only remove the known temp file. if temporary.exists(): temporary.unlink() def _copy_file(source: Path, destination: Path) -> None: """Snapshot a small code/document file without following unsafe parents.""" if not source.is_file(): raise ReleaseError(f"required release file is missing: {source}") destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_name(destination.name + ".tmp") try: shutil.copy2(source, temporary) os.replace(temporary, destination) finally: if temporary.exists(): temporary.unlink() def _hardlink_file(source: Path, destination: Path) -> None: """Make one idempotent hard link; never silently copy a tensor shard.""" if not source.is_file(): raise ReleaseError(f"source file is missing: {source}") destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists(): source_stat = source.stat() destination_stat = destination.stat() if (source_stat.st_dev, source_stat.st_ino) == (destination_stat.st_dev, destination_stat.st_ino): return raise ReleaseError( "staging file already exists but is not the expected hard link; " f"refusing to replace it: {destination}" ) try: os.link(source, destination) except OSError as exc: raise ReleaseError( "hard-link failed; staging and source must share a filesystem. " f"source={source}, destination={destination}: {exc}" ) from exc def _dataset_source(dataset_root: Path, spec: DatasetSpec) -> Path: source = (dataset_root / spec.source_name).resolve() if not source.is_dir(): raise ReleaseError(f"completed compact dataset is missing: {source}") manifest = source / "manifest.json" if not manifest.is_file(): raise ReleaseError(f"completed compact dataset has no manifest: {manifest}") value = _read_json(manifest) if not isinstance(value, dict) or value.get("status") != "complete": raise ReleaseError(f"dataset is not a complete compact release: {source}") return source def _release_dataset_root(stage_root: Path, spec: DatasetSpec) -> Path: return stage_root / "data" / "hiqbind_5k_v1" / spec.release_name def _sanitized_json_payload(source: Path) -> Any: payload = _sanitize_value(_read_json(source)) leftovers = _find_absolute_path_values(payload) if leftovers: raise ReleaseError(f"path sanitizer left absolute paths in {source}: {leftovers[:5]}") return payload def _stage_dataset(source: Path, destination: Path) -> None: """Stage a compact dataset, hard-linking all immutable source artifacts.""" for source_file in sorted(source.rglob("*")): if not source_file.is_file(): continue relative = _relative_to(source_file, source) target = destination / relative # These two records contain source provenance. Their release versions # preserve logical relative fields but never disclose local paths. if source_file.name in {"manifest.json", "source_index.json"}: _write_json(target, _sanitized_json_payload(source_file)) else: _hardlink_file(source_file, target) def _release_assets() -> list[tuple[Path, Path]]: """Discover authored release documents plus the static code mapping.""" assets = list(CODE_SOURCES) # README is the Hugging Face dataset card. Other authored Markdown files # are companion documents, keeping the remote root uncluttered. for source in sorted(RELEASE_ROOT.glob("*.md"), key=lambda item: item.name.casefold()): remote = Path("README.md") if source.name == "README.md" else Path("docs") / source.name assets.append((source, remote)) # Release-authored companion docs and the small hand-written package notes # live in the release tree itself. Include them recursively while # deliberately excluding generated __pycache__ / staging content. authored_docs = RELEASE_ROOT / "docs" if authored_docs.is_dir(): for source in sorted(authored_docs.rglob("*"), key=lambda item: str(item).casefold()): if source.is_file() and "__pycache__" not in source.parts: assets.append((source, Path("docs") / _relative_to(source, authored_docs))) authored_code = RELEASE_ROOT / "code" / "compact_v1" if authored_code.is_dir(): for source in sorted(authored_code.rglob("*"), key=lambda item: str(item).casefold()): if source.is_file() and "__pycache__" not in source.parts: assets.append((source, Path("code/compact_v1") / _relative_to(source, authored_code))) # A dependency file placed at the release root is also supported for # convenience; a code/compact_v1 version takes precedence by causing an # explicit duplicate-destination error rather than silent replacement. for name in ("requirements.txt", "environment.yml", "environment.yaml"): source = RELEASE_ROOT / name if source.is_file(): assets.append((source, Path("code/compact_v1") / name)) # Include the reproducible release entry points themselves, but not this # staging directory or arbitrary local files. for name in ("upload_copuladock.py", "upload_copuladock.sbatch"): source = RELEASE_ROOT / name if source.is_file(): assets.append((source, Path("code/release") / name)) return assets def _stage_assets(stage_root: Path) -> list[Path]: staged: list[Path] = [] seen_destinations: set[Path] = set() for source, remote in _release_assets(): if remote in seen_destinations: raise ReleaseError(f"duplicate release destination: {remote}") seen_destinations.add(remote) if not source.is_file(): raise ReleaseError(f"required construction code is missing: {source}") target = stage_root / remote _copy_file(source, target) staged.append(target) return staged def _prune_obsolete_stage_files(stage_root: Path) -> None: """Remove only known stale generated code copies from an older layout.""" for relative in OBSOLETE_STAGE_FILES: target = stage_root / relative if target.is_file(): target.unlink() # Leave a directory untouched when it contains anything unexpected; # upload_large_folder ignores empty directories in any event. parent = target.parent if parent.is_dir() and not any(parent.iterdir()): parent.rmdir() def _validate_stage_location(stage_root: Path, dataset_root: Path) -> None: """Prevent accidental recursive staging into either source dataset root.""" stage_root = stage_root.resolve() dataset_root = dataset_root.resolve() if stage_root == dataset_root: raise ReleaseError("--stage-root must not equal --dataset-root") try: stage_root.relative_to(dataset_root) except ValueError: return raise ReleaseError("--stage-root must not be inside --dataset-root") def _expected_tensor_files(source: Path) -> list[Path]: return sorted(path for path in source.rglob("*.pt") if path.is_file()) def _human_bytes(number: int) -> str: value = float(number) for suffix in ("B", "KiB", "MiB", "GiB", "TiB"): if value < 1024.0 or suffix == "TiB": return f"{value:.1f} {suffix}" value /= 1024.0 return f"{number} B" def _source_summary(dataset_root: Path) -> list[dict[str, Any]]: summary: list[dict[str, Any]] = [] for spec in DATASETS: source = _dataset_source(dataset_root, spec) manifest = _read_json(source / "manifest.json") tensors = _expected_tensor_files(source) summary.append( { "name": spec.release_name, "source": str(source), "systems": int(manifest.get("n_systems", 0)), "graphs": int(manifest.get("n_graphs", 0)), "shards": len(tensors), "tensor_bytes": sum(path.stat().st_size for path in tensors), } ) return summary def prepare_stage(stage_root: Path, dataset_root: Path, *, dry_run: bool) -> None: """Create/update the reusable stage. ``dry_run`` performs no writes.""" _validate_stage_location(stage_root, dataset_root) summaries = _source_summary(dataset_root) assets = _release_assets() print(f"stage root: {stage_root}") for item in summaries: print( f" {item['name']}: {item['systems']} systems, {item['graphs']} graphs, " f"{item['shards']} .pt shards, {_human_bytes(item['tensor_bytes'])}" ) print(f" construction/release files: {len(assets)}") if dry_run: print("dry-run: source checks passed; no staging files were created or changed.") return stage_root.mkdir(parents=True, exist_ok=True) for spec in DATASETS: _stage_dataset(_dataset_source(dataset_root, spec), _release_dataset_root(stage_root, spec)) _stage_assets(stage_root) _prune_obsolete_stage_files(stage_root) print("staging preparation completed (tensor shards are hard links).") def verify_stage(stage_root: Path, dataset_root: Path, *, require_readme: bool) -> None: """Check staging layout, sanitization, and every tensor hard link.""" if not stage_root.is_dir(): raise ReleaseError(f"staging root does not exist: {stage_root}") errors: list[str] = [] checked_tensors = 0 for spec in DATASETS: source = _dataset_source(dataset_root, spec) staged = _release_dataset_root(stage_root, spec) if not staged.is_dir(): errors.append(f"missing staged dataset directory: {staged}") continue for name in ("manifest.json", "source_index.json", "system_index.json"): candidate = staged / name if not candidate.is_file(): errors.append(f"missing staged metadata: {candidate}") for name in ("manifest.json", "source_index.json"): candidate = staged / name if candidate.is_file(): try: leftovers = _find_absolute_path_values(_read_json(candidate)) except ReleaseError as exc: errors.append(str(exc)) else: if leftovers: errors.append(f"absolute paths remain in {candidate}: {leftovers[:5]}") for source_tensor in _expected_tensor_files(source): staged_tensor = staged / _relative_to(source_tensor, source) if not staged_tensor.is_file(): errors.append(f"missing staged tensor: {staged_tensor}") continue source_stat = source_tensor.stat() staged_stat = staged_tensor.stat() if (source_stat.st_dev, source_stat.st_ino) != (staged_stat.st_dev, staged_stat.st_ino): errors.append(f"tensor is not a hard link: {staged_tensor}") if source_stat.st_size != staged_stat.st_size: errors.append(f"tensor size differs: {staged_tensor}") checked_tensors += 1 for source, remote in _release_assets(): staged_file = stage_root / remote if not staged_file.is_file(): errors.append(f"missing staged release asset: {staged_file}") elif staged_file.stat().st_size != source.stat().st_size: errors.append(f"staged release asset size differs: {staged_file}") readme = stage_root / "README.md" if require_readme and not readme.is_file(): errors.append("README.md is required before upload; add it under release_copuladock/") if errors: raise ReleaseError("staging verification failed:\n - " + "\n - ".join(errors)) print(f"staging verification passed: {checked_tensors} tensor hard links checked; no local absolute paths in release metadata.") def _get_token(args: argparse.Namespace) -> str: token = args.token or os.environ.get("HF_TOKEN") if token: return token try: from huggingface_hub import get_token except ImportError as exc: raise ReleaseError( "--upload requires --token/HF_TOKEN or a saved Hugging Face login; " "huggingface_hub is unavailable." ) from exc token = get_token() if not token: raise ReleaseError( "--upload requires --token, HF_TOKEN, or a saved Hugging Face login. " "Run `python -c 'from huggingface_hub import login; login()'` first." ) return token def upload_stage(args: argparse.Namespace) -> None: """Authenticate safely and perform the one resumable folder upload.""" if args.dry_run: print( "dry-run: would verify credentials and call HfApi.upload_large_folder " f"for dataset repo {args.repo_id!r} from {args.stage_root}." ) return token = _get_token(args) try: from huggingface_hub import HfApi except ImportError as exc: raise ReleaseError( "huggingface_hub is unavailable. Run with " "/u/hhao/anaconda3/envs/hgf/bin/python." ) from exc api = HfApi(token=token) try: account = api.whoami(token=token) api.repo_info(args.repo_id, repo_type="dataset", revision=args.revision, token=token) except Exception as exc: # The Hub library exposes several transport/auth exception types. raise ReleaseError( f"cannot authenticate to or access dataset repository {args.repo_id!r}: {exc}" ) from exc # The user identity is useful operational evidence but contains no secret. account_name = account.get("name") if isinstance(account, Mapping) else None print(f"Hugging Face authentication verified for account: {account_name or ''}") print( "starting resumable upload_large_folder: " f"repo={args.repo_id}, revision={args.revision}, workers={args.num_workers}" ) try: api.upload_large_folder( repo_id=args.repo_id, folder_path=args.stage_root, repo_type="dataset", revision=args.revision, num_workers=args.num_workers, # upload_large_folder writes resumable state below .cache; it is # operational metadata, not part of the scientific release. ignore_patterns=[".cache/**", "**/__pycache__/**", "*.pyc", "*.tmp"], print_report=True, ) except Exception as exc: raise ReleaseError( "Hugging Face upload did not complete. Keep the staging root unchanged and rerun " "the same command to resume: " f"{exc}" ) from exc print("upload_large_folder completed successfully.") def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--prepare", action="store_true", help="create/update the persistent staging tree") parser.add_argument("--verify", action="store_true", help="verify an existing staging tree") parser.add_argument("--upload", action="store_true", help="upload a verified staging tree to Hugging Face") parser.add_argument( "--dry-run", action="store_true", help="show prepare/upload actions without staging writes or network access", ) parser.add_argument("--repo-id", default=DEFAULT_REPO_ID, help=f"target dataset repo (default: {DEFAULT_REPO_ID})") parser.add_argument("--revision", default="main", help="target revision (default: main)") parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT) parser.add_argument("--stage-root", type=Path, default=DEFAULT_STAGE_ROOT) parser.add_argument("--num-workers", type=int, default=8, help="upload_large_folder worker count (default: 8)") parser.add_argument("--token", help="Hugging Face token; prefer HF_TOKEN in a job environment") return parser def main(argv: Sequence[str] | None = None) -> int: args = build_parser().parse_args(argv) if not (args.prepare or args.verify or args.upload): raise ReleaseError("select at least one action: --prepare, --verify, and/or --upload") if args.num_workers < 1: raise ReleaseError("--num-workers must be at least 1") args.dataset_root = args.dataset_root.expanduser().resolve() args.stage_root = args.stage_root.expanduser().resolve() if args.prepare: prepare_stage(args.stage_root, args.dataset_root, dry_run=args.dry_run) if args.verify or args.upload: # A dry-run upload has no staging side effects, but validates a real # stage when one is already present. This catches layout mistakes # before credentials/network access are involved. verify_stage(args.stage_root, args.dataset_root, require_readme=args.upload and not args.dry_run) if args.upload: upload_stage(args) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except ReleaseError as exc: print(f"ERROR: {exc}", file=sys.stderr) raise SystemExit(2)