#!/usr/bin/env python3 """One-shot deploy to Hugging Face: private dataset + public Docker Space. Idempotent — safe to re-run for redeploys (existing repos are reused; keys are only generated if the Space doesn't have them yet, unless --rotate-keys). Requires a logged-in Hugging Face account (`hf auth login`) or HF_TOKEN env. python3 scripts/deploy_space.py [--user NAME] [--rotate-keys] """ from __future__ import annotations import argparse import json import secrets as pysecrets import sys import tempfile from pathlib import Path from huggingface_hub import CommitOperationAdd, HfApi, get_token, whoami def main() -> int: ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--user", help="HF username/org (default: whoami)") ap.add_argument("--space", default="opa-traint") ap.add_argument("--dataset", default="opa-family-data") ap.add_argument("--rotate-keys", action="store_true", help="generate new USER_KEY/FAMILY_KEY (old links stop working)") args = ap.parse_args() api = HfApi() token = get_token() if not token: print("Not logged in — run `hf auth login` first.", file=sys.stderr) return 1 user = args.user or whoami()["name"] dataset = f"{user}/{args.dataset}" space = f"{user}/{args.space}" def ensure_repo(repo_id: str, **kwargs) -> str: # HF started returning 402 on /api/repos/create for some accounts even # with exist_ok — if the repo is already there, that's all we need. try: return str(api.create_repo(repo_id, **kwargs)) except Exception: rt = kwargs.get("repo_type") if api.repo_exists(repo_id, repo_type=rt): prefix = {"dataset": "datasets/", "space": "spaces/"}.get(rt, "") return f"https://huggingface.co/{prefix}{repo_id} (exists)" raise # 1. Private dataset for all family data. print("→ dataset:", ensure_repo(dataset, repo_type="dataset", private=True, exist_ok=True)) existing = set(api.list_repo_files(dataset, repo_type="dataset")) ops = [] for name, payload in (("people.json", {"people": []}), ("events.json", {"events": []})): if name in existing: continue tmp = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") json.dump(payload, tmp, ensure_ascii=False, indent=2) tmp.close() ops.append(CommitOperationAdd(path_in_repo=name, path_or_fileobj=tmp.name)) if ops: api.create_commit(repo_id=dataset, repo_type="dataset", operations=ops, commit_message="init family data structure") print(" initialized people.json / events.json") # 2. Public Docker Space. print("→ space:", ensure_repo(space, repo_type="space", space_sdk="docker", private=False, exist_ok=True)) # 3. Secrets. HF cannot list secret values back, so the generated keys are # kept in a local, gitignored file — re-runs reuse them and reprint the # bookmark links. keyfile = Path(".space_keys.json") keys = json.loads(keyfile.read_text()) if keyfile.exists() else {} if args.rotate_keys or "USER_KEY" not in keys: keys = {"USER_KEY": pysecrets.token_urlsafe(32), "FAMILY_KEY": pysecrets.token_urlsafe(32)} keyfile.write_text(json.dumps(keys, indent=2)) keyfile.chmod(0o600) api.add_space_secret(space, "USER_KEY", keys["USER_KEY"]) api.add_space_secret(space, "FAMILY_KEY", keys["FAMILY_KEY"]) api.add_space_secret(space, "HF_TOKEN", token) api.add_space_secret(space, "DATASET_REPO", dataset) print("→ secrets set: HF_TOKEN, DATASET_REPO, USER_KEY, FAMILY_KEY") # 4. Upload the code. Personal-data paths are excluded belt-and-braces — # they're gitignored anyway, and the Space repo must stay clean. api.upload_folder( folder_path=".", repo_id=space, repo_type="space", commit_message="Deploy Opa Traint", ignore_patterns=["data/*", "familie/*", ".git/*", "__pycache__/*", "*/__pycache__/*", "*.pyc", ".claude/*", ".venv/*", "venv/*", ".DS_Store", "lichess_db_puzzle.csv*", ".space_keys.json"], ) print("→ code uploaded — the Space is now building (takes a few minutes)") host = f"https://{user}-{args.space.replace('_', '-')}.hf.space" print() print("=== BEWAAR DEZE LINKS ===") print(f"Opa's bookmark : {host}/?k={keys['USER_KEY']}") print(f"Familie : {host}/familie?k={keys['FAMILY_KEY']}") print() print("Volgende stap: foto's uploaden met scripts/upload_family_data.py --bulk ./familie") return 0 if __name__ == "__main__": raise SystemExit(main())