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)