File size: 2,742 Bytes
3513553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""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()