File size: 4,998 Bytes
75c683a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44501ff
 
 
 
 
 
 
 
 
 
 
 
75c683a
44501ff
 
75c683a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44501ff
 
 
75c683a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/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())