File size: 3,226 Bytes
24a3eed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import os
import runpy
import sys
from pathlib import Path


def _env(name: str) -> str | None:
    v = os.environ.get(name)
    if v is None:
        return None
    v = v.strip()
    return v or None


def _fail(msg: str) -> None:
    """
    Fail fast with a useful error message.

    This file is intended to run as a Hugging Face *public* Space entrypoint.
    It downloads a *private* Space snapshot at runtime and executes its app.
    """
    raise SystemExit(msg)


def _ensure_private_space_snapshot(
    *,
    repo_id: str,
    token: str,
    cache_dir: Path,
    entrypoint_rel: str,
) -> Path:
    try:
        from huggingface_hub import snapshot_download  # type: ignore
    except Exception as exc:  # pragma: no cover
        _fail(
            "Missing dependency: huggingface_hub\n"
            "Add it to your Space requirements.\n"
            f"Import error: {exc}"
        )

    cache_dir.mkdir(parents=True, exist_ok=True)
    entrypoint_path = (cache_dir / entrypoint_rel).resolve()

    # Avoid re-downloading on every rerun: only download if the entrypoint is missing.
    if entrypoint_path.exists():
        return entrypoint_path

    snapshot_download(
        repo_id=str(repo_id),
        repo_type="space",
        token=str(token),
        local_dir=str(cache_dir),
    )

    if not entrypoint_path.exists():
        _fail(
            "Downloaded private Space snapshot, but entrypoint file was not found.\n"
            f"repo_id={repo_id}\n"
            f"entrypoint={entrypoint_rel}\n"
            f"cache_dir={cache_dir}"
        )

    return entrypoint_path


def main() -> None:
    """
    Configuration (recommended to set via HF Space 'Secrets' / 'Variables'):

    - HF_TOKEN: Read token that can access the private Space repo.
    - PRIVATE_SPACE_REPO_ID: e.g. "org-or-user/private-space-name"

    Optional:
    - PRIVATE_SPACE_ENTRYPOINT: relative path inside the private repo (default: "app.py")
    - PRIVATE_SPACE_CACHE_DIR: local dir to store the downloaded snapshot (default: "private_space_cache")
    """

    token = _env("HF_TOKEN")
    repo_id = _env("PRIVATE_SPACE_REPO_ID")
    entrypoint_rel = _env("PRIVATE_SPACE_ENTRYPOINT") or "app.py"
    cache_dir = Path(_env("PRIVATE_SPACE_CACHE_DIR") or "private_space_cache")

    if not token:
        _fail(
            "HF_TOKEN is not set.\n"
            "Set it as a Hugging Face Space Secret with read access to the private Space."
        )
    if not repo_id:
        _fail(
            "PRIVATE_SPACE_REPO_ID is not set.\n"
            'Example: PRIVATE_SPACE_REPO_ID="org-or-user/private-space-name"'
        )

    entrypoint_path = _ensure_private_space_snapshot(
        repo_id=repo_id,
        token=token,
        cache_dir=cache_dir,
        entrypoint_rel=entrypoint_rel,
    )

    # Make the private Space snapshot importable (for `from x import y` inside it).
    cache_dir_str = str(cache_dir.resolve())
    if cache_dir_str not in sys.path:
        sys.path.insert(0, cache_dir_str)

    # Execute the private entrypoint as if it were the main app file.
    runpy.run_path(str(entrypoint_path), run_name="__main__")


if __name__ == "__main__":
    main()