File size: 3,942 Bytes
ed7ea89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7871d59
ed7ea89
 
 
 
5281b90
ed7ea89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5281b90
ed7ea89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Create a NEW private ZeroGPU Space. Uses existing Hub authentication only."""

import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import re
import subprocess
import sys

from huggingface_hub import HfApi, get_token
from huggingface_hub.errors import HfHubHTTPError

ROOT = Path(__file__).resolve().parents[1]
ALLOWLIST = ["app.py", "settings.py", "style.css", "requirements.txt", "README.md",
             "NOTICE", "LICENSE-QWEN", ".gitignore", "scripts/*.py", "reports/*.md",
             "reports/sources.json", "evidence/**", "frontend/**", "package.json", "package-lock.json"]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--name", default="qwen-21-image-" + datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S"))
    args = parser.parse_args()
    if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._-]{1,80}", args.name):
        parser.error("Use a valid Space name, without a namespace or slash.")
    token = get_token()
    if not token:
        sys.exit("BLOCKED: No existing Hugging Face authentication. Run hf auth login securely in this environment.")
    api = HfApi(token=token)
    who = api.whoami()
    namespace = who["name"]
    repo_id = f"{namespace}/{args.name}"
    # Commit identity is an audit requirement, not a credential or remote action.
    if subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True).strip():
        sys.exit("Commit the reproducible source before deployment; the working tree is not clean.")
    source_commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
    print(json.dumps({"namespace": namespace, "is_pro": who.get("isPro"),
                      "requested_hardware": "zero-a10g", "private": True,
                      "source_commit": source_commit}))
    # exist_ok=False guarantees we do not overwrite an unrelated Space.
    url = api.create_repo(
        repo_id=repo_id, repo_type="space", space_sdk="gradio", private=True,
        space_hardware="zero-a10g", exist_ok=False,
        space_variables=[{"key": "GRADIO_SSR_MODE", "value": "false"},
                         {"key": "STILL_SOURCE_COMMIT", "value": source_commit}],
    )
    # Persist identity before upload so a failed upload can be resumed safely.
    state = {"repo_id": repo_id, "url": str(url), "private": True,
             "hardware_requested": "zero-a10g", "source_commit": source_commit,
             "created_at": datetime.now(timezone.utc).isoformat(), "uploaded": False}
    state_path = ROOT / "deployment.json"
    state_path.write_text(json.dumps(state, indent=2) + "\n")
    commit = api.upload_folder(
        repo_id=repo_id, repo_type="space", folder_path=str(ROOT), allow_patterns=ALLOWLIST,
        commit_message="Add Qwen 2.1 Image with direct Qwen-Image 2.1 ZeroGPU inference",
    )
    state.update(uploaded=True, hub_commit=commit.oid)
    state_path.write_text(json.dumps(state, indent=2) + "\n")
    info = api.space_info(repo_id)
    if not info.private:
        sys.exit("Unexpected privacy state: stop and inspect the newly created Space.")
    print(f"Created private Space: {url}")
    print(f"Hub source commit: {commit.oid}")
    print("Deployment is not accepted until actual generation and browser verification pass.")
    print(f"hf spaces logs {repo_id} --build --follow")
    print(f"hf spaces logs {repo_id} --follow")


if __name__ == "__main__":
    try:
        main()
    except HfHubHTTPError as exc:
        # No credentials, request headers, or full server responses in logs.
        code = exc.response.status_code if exc.response is not None else "unknown"
        hint = str(getattr(exc, "server_message", None) or type(exc).__name__)
        hint = re.sub(r"hf_[A-Za-z0-9]+", "[redacted]", hint)
        sys.exit(f"BLOCKED: Hub HTTP {code}: {hint}. No dedicated hardware was requested.")