Spaces:
Sleeping
Sleeping
| """set_hf_secrets.py | |
| Simple helper to add/update Hugging Face Space Secrets via the HF HTTP API. | |
| Usage (from repo root): | |
| python set_hf_secrets.py --owner <username> --repo <repo> # reads secrets from .env | |
| The script reads a set of known keys from `.env` and will POST them to | |
| the Space secrets endpoint using the HF token found in `.env` under HF_TOKEN or HF. | |
| Warning: ensure your `.env` is safe and do not commit it. | |
| """ | |
| import os | |
| import sys | |
| import json | |
| from pathlib import Path | |
| try: | |
| from dotenv import load_dotenv | |
| except Exception: | |
| load_dotenv = None | |
| import requests | |
| ROOT = Path.cwd() | |
| def load_token(): | |
| if load_dotenv: | |
| p = ROOT / '.env' | |
| if p.exists(): | |
| load_dotenv(p) | |
| for k in ('HF_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGINGFACE_TOKEN', 'HF'): | |
| v = os.getenv(k) | |
| if v: | |
| return v | |
| return None | |
| DEFAULT_KEYS = [ | |
| 'FB_PAGE_ACCESS_TOKEN', | |
| 'FB_PAGE_ID', | |
| 'REPLICATE_API_TOKEN', | |
| 'OPENAI_API_KEY', | |
| 'RUN_DAILY_REPLICATE', | |
| 'DAILY_INTERVAL_HOURS', | |
| ] | |
| def set_secret(token: str, owner: str, repo: str, key: str, value: str): | |
| repo_id = f"{owner}/{repo}" | |
| url = f"https://huggingface.co/api/spaces/{owner}/{repo}/secrets" | |
| headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"} | |
| payload = {"key": key, "value": value} | |
| r = requests.post(url, headers=headers, data=json.dumps(payload), timeout=15) | |
| if r.status_code not in (200, 201): | |
| raise RuntimeError(f"Failed setting secret {key}: {r.status_code} {r.text}") | |
| return r.json() | |
| def main(): | |
| import argparse | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('--owner', required=True, help='HF username or org (e.g. gowshiselva)') | |
| parser.add_argument('--repo', default=ROOT.name, help='Space repo name (default: repo folder name)') | |
| parser.add_argument('--keys', nargs='*', help='List of env keys to publish (default: common keys)') | |
| args = parser.parse_args() | |
| token = load_token() | |
| if not token: | |
| print('No HF token found in .env (HF_TOKEN/HF). Aborting.') | |
| sys.exit(2) | |
| keys = args.keys or DEFAULT_KEYS | |
| to_publish = {} | |
| for k in keys: | |
| v = os.getenv(k) | |
| if v is not None and v != '': | |
| to_publish[k] = v | |
| if not to_publish: | |
| print('No configured keys found in environment to publish. Exiting.') | |
| return | |
| print(f'Publishing {len(to_publish)} secrets to {args.owner}/{args.repo}...') | |
| for k, v in to_publish.items(): | |
| try: | |
| res = set_secret(token, args.owner, args.repo, k, v) | |
| print('OK', k) | |
| except Exception as e: | |
| print('ERROR', k, str(e)) | |
| if __name__ == '__main__': | |
| main() | |