JH-BK's picture
Create app.py
24a3eed verified
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()