#!/usr/bin/env python3 """Upload this checked release to a Hugging Face *dataset* repository.""" from __future__ import annotations import argparse import hashlib import re import sys from pathlib import Path, PurePosixPath ROOT = Path(__file__).resolve().parent.parent MANIFEST = ROOT / "SHA256SUMS.txt" def checked_paths() -> list[str]: """Check every manifest hash, and return an exact upload allowlist.""" if not MANIFEST.is_file(): raise ValueError("SHA256SUMS.txt is missing; extract the complete release.") selected: list[str] = [] for number, line in enumerate(MANIFEST.read_text(encoding="utf-8").splitlines(), 1): if not line.strip(): continue match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](.+)", line) if match is None: raise ValueError(f"Malformed SHA256SUMS entry at line {number}.") digest, name = match.groups() relative = PurePosixPath(name) if ( relative.is_absolute() or ".." in relative.parts or not relative.parts or "\\" in name or any(char in name for char in "*?[]") or name in selected or name == "SHA256SUMS.txt" ): raise ValueError(f"Unsafe or duplicate manifest entry at line {number}.") lowered = [part.lower() for part in relative.parts] forbidden = {"logs", "__pycache__", "credentials", "credential", "token", "tokens"} if ( any(part in forbidden for part in lowered) or any(part.startswith(".") and part not in {".gitattributes", ".gitignore"} for part in lowered) or relative.suffix.lower() in {".log", ".key", ".pem", ".p12", ".pfx"} ): raise ValueError(f"Private, credential, or log path in manifest at line {number}.") path = ROOT.joinpath(*relative.parts) if not path.is_file() or path.is_symlink() or any(parent.is_symlink() for parent in path.parents if parent != ROOT): raise ValueError(f"Missing file or symlink in manifest at line {number}.") try: path.resolve().relative_to(ROOT) except ValueError: raise ValueError(f"Manifest path leaves release directory at line {number}.") from None hasher = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): hasher.update(block) if hasher.hexdigest().lower() != digest.lower(): raise ValueError(f"Integrity check failed for manifest entry at line {number}.") selected.append(name) if not selected or "README.md" not in selected: raise ValueError("Manifest must include README.md and release files.") return selected + ["SHA256SUMS.txt"] def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("repo_id", nargs="?", help="Your namespace/dataset-name; prompted when omitted.") parser.add_argument("--private", action="store_true", help="Make a newly created repository private; existing visibility stays unchanged.") parser.add_argument("--dry-run", action="store_true", help="Verify local hashes and print the plan; no authentication or network.") parser.add_argument("--revision", help="Existing destination branch; defaults to the repository default branch.") args = parser.parse_args() if not args.repo_id: if not sys.stdin.isatty(): parser.error("Supply a repository ID as namespace/dataset-name.") args.repo_id = input("Hugging Face dataset repository (namespace/dataset-name): ").strip() if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_-]*/[A-Za-z0-9][A-Za-z0-9._-]*", args.repo_id): parser.error("Repository ID must be namespace/dataset-name using letters, digits, underscores, dots, or hyphens.") try: paths = checked_paths() except (OSError, UnicodeError, ValueError) as error: print(f"Upload stopped: {error}", file=sys.stderr) return 1 size = sum((ROOT / name).stat().st_size for name in paths) print(f"Integrity passed: {len(paths) - 1} hashed files; {len(paths)} upload files, {size:,} bytes.") print(f"Destination: https://huggingface.co/datasets/{args.repo_id}") print(f"Revision: {args.revision or 'default branch'}; new-repository visibility: {'private' if args.private else 'public'}.") if args.dry_run: print("Dry run complete. No authentication, network, repository creation, or upload occurred.") return 0 try: from huggingface_hub import HfApi except ImportError: print("Missing dependency. Install: python -m pip install --upgrade huggingface_hub", file=sys.stderr) print("Then authenticate: hf auth login", file=sys.stderr) return 1 try: api = HfApi(token=True) api.whoami() # Uses saved hf auth or HF_TOKEN; credentials are never printed. api.create_repo(repo_id=args.repo_id, repo_type="dataset", private=args.private, exist_ok=True) api.upload_folder( repo_id=args.repo_id, repo_type="dataset", folder_path=str(ROOT), allow_patterns=paths, revision=args.revision, commit_message="Upload CHISAEL-NEXYTHRA II research dataset v1.0.0", ) except Exception as error: status = getattr(getattr(error, "response", None), "status_code", None) status_note = f", HTTP {status}" if isinstance(status, int) else "" print(f"Upload failed ({type(error).__name__}{status_note}).", file=sys.stderr) print("Check your connection, repository permissions, and hf auth login; then rerun this command.", file=sys.stderr) if args.revision: print("The requested destination branch must already exist.", file=sys.stderr) return 1 print(f"Upload complete: https://huggingface.co/datasets/{args.repo_id}") return 0 if __name__ == "__main__": raise SystemExit(main())