File size: 1,541 Bytes
44a2bac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
from pathlib import Path

from dotenv import load_dotenv  # type: ignore


def load_dotenv_if_present(dotenv_path: str | os.PathLike = ".env.local") -> bool:
    """

    Optional convenience for local dev: loads .env if python-dotenv is installed.

    If python-dotenv is not installed or file doesn't exist, this is a no-op.



    Returns True if a .env was loaded, else False.

    """
    p = Path(dotenv_path)
    if not p.exists():
        return False

    load_dotenv(dotenv_path=p)
    return True


def require_secrets(*names: str) -> None:
    """Verify that required HF Space secrets are set, or exit with a clear message.



    Only enforced when ``SPACE_ID`` is present in the environment (i.e. the app

    is running on Hugging Face Spaces).  Locally, developers authenticate via

    ``hf auth login`` so secrets like ``MODEL_ACCESS_TOKEN`` are not needed.



    Args:

        *names: Environment variable names that must be non-empty.



    Raises:

        SystemExit: If any secret is missing while running on HF Spaces.

    """
    space_id = os.environ.get("SPACE_ID", "")
    if not space_id or not names:
        return

    missing = [n for n in names if not os.environ.get(n, "").strip()]
    if not missing:
        return

    settings_url = f"https://huggingface.co/spaces/{space_id}/settings"
    print(
        f"ERROR: Missing required secrets: {', '.join(missing)}\n" f"Set them at: {settings_url}",
        file=sys.stderr,
    )
    sys.exit(1)