Spaces:
Running
Running
Download scripts/set_hf_secrets.py from LeoWalker/learningfocused-mcp: direct link, hf CLI and curl.
- Browser
- Download file 2.09 kB
-
https://huggingface.co/spaces/LeoWalker/learningfocused-mcp/resolve/main/scripts/set_hf_secrets.py
- Command line
-
hf download hf://spaces/LeoWalker/learningfocused-mcp/scripts/set_hf_secrets.py
-
curl -L -o set_hf_secrets.py https://huggingface.co/spaces/LeoWalker/learningfocused-mcp/resolve/main/scripts/set_hf_secrets.py
2.09 kB
| #!/usr/bin/env python3 | |
| """Copy API keys into a Hugging Face Space. Never prints secret values.""" | |
| from __future__ import annotations | |
| import argparse | |
| import os | |
| import sys | |
| from pathlib import Path | |
| from dotenv import dotenv_values | |
| from huggingface_hub import HfApi, get_token | |
| ROOT = Path(__file__).resolve().parent.parent | |
| ENV_FILE = ROOT / ".env" | |
| SECRET_KEYS = ("OPENAI_API_KEY", "GOOGLE_API_KEY", "ASSEMBLYAI_API_KEY") | |
| def _value(env_key: str) -> str: | |
| file_vals = dotenv_values(ENV_FILE) if ENV_FILE.is_file() else {} | |
| value = os.environ.get(env_key) or file_vals.get(env_key) | |
| if not value: | |
| raise SystemExit(f"Missing {env_key} in environment or {ENV_FILE}") | |
| return str(value) | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--space", required=True, help="Space id, e.g. LeoWalker/learningfocused-mcp") | |
| parser.add_argument( | |
| "--write-job-secrets-file", | |
| default="", | |
| help="Optional path for hf jobs --secrets-file (API keys only; HF_TOKEN passed separately).", | |
| ) | |
| args = parser.parse_args(argv) | |
| api = HfApi() | |
| values = {key: _value(key) for key in SECRET_KEYS} | |
| for key, value in values.items(): | |
| api.add_space_secret(args.space, key, value) | |
| print(f"set Space secret {key} (value hidden)") | |
| hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or get_token() | |
| if not hf_token: | |
| raise SystemExit("No HF token available to store as Space secret HF_TOKEN") | |
| api.add_space_secret(args.space, "HF_TOKEN", hf_token) | |
| print("set Space secret HF_TOKEN (value hidden)") | |
| if args.write_job_secrets_file: | |
| path = Path(args.write_job_secrets_file) | |
| lines = [f"{key}={values[key]}" for key in SECRET_KEYS] | |
| path.write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| os.chmod(path, 0o600) | |
| print(f"wrote job secrets file with {len(SECRET_KEYS)} keys (values hidden)") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main(sys.argv[1:])) | |