File size: 2,447 Bytes
ca50bff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create/update the Hugging Face Docker Space for this repo."""

from __future__ import annotations

import os
import secrets
from pathlib import Path

from huggingface_hub import HfApi


ROOT = Path(__file__).resolve().parent
DEFAULT_SPACE_ID = "bg5/zai2api"


def require_env(name: str) -> str:
    value = os.getenv(name, "").strip()
    if not value:
        raise SystemExit(f"Missing required environment variable: {name}")
    return value


def main() -> None:
    backup_token = require_env("BACKUP_TOKEN")
    space_id = os.getenv("HF_SPACE_ID", DEFAULT_SPACE_ID).strip() or DEFAULT_SPACE_ID
    auth_token = os.getenv("AUTH_TOKEN", "").strip()
    if not auth_token:
        auth_token = "zai2api-" + secrets.token_urlsafe(32)

    api = HfApi(token=os.getenv("HF_TOKEN") or None)
    api.create_repo(
        repo_id=space_id,
        repo_type="space",
        space_sdk="docker",
        exist_ok=True,
    )

    api.upload_folder(
        repo_id=space_id,
        repo_type="space",
        folder_path=str(ROOT),
        path_in_repo=".",
        ignore_patterns=[
            ".git/*",
            ".local/*",
            "__pycache__/*",
            "node_modules/*",
            "captcha-provider/node_modules/*",
            "data/*",
            "*.log",
            ".generated-auth-token.txt",
        ],
        commit_message="部署 zai2api 到 HF Space",
    )

    api.add_space_secret(
        repo_id=space_id,
        key="AUTH_TOKEN",
        value=auth_token,
        description="API/admin key for zai2api",
    )
    api.add_space_secret(
        repo_id=space_id,
        key="BACKUP_TOKEN",
        value=backup_token,
        description="Z.AI JWT token",
    )
    api.add_space_variable(repo_id=space_id, key="PORT", value="7860")
    api.add_space_variable(
        repo_id=space_id,
        key="CAPTCHA_PROVIDER_URL",
        value="http://127.0.0.1:9876",
    )
    api.add_space_variable(repo_id=space_id, key="BROWSER_BACKEND", value="playwright")
    api.add_space_variable(repo_id=space_id, key="CHROMIUM_PATH", value="/usr/bin/chromium")

    token_path = ROOT / ".generated-auth-token.txt"
    token_path.write_text(auth_token + "\n", encoding="utf-8")

    print(f"Space: https://huggingface.co/spaces/{space_id}")
    print(f"App:   https://{space_id.replace('/', '-')}.hf.space")
    print(f"AUTH_TOKEN saved to: {token_path}")


if __name__ == "__main__":
    main()