File size: 2,217 Bytes
ca2863a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""hf_auth_setup.py

Helper to show / set the Hugging Face spaces git remote from an HF token.

Usage: `python hf_auth_setup.py` — it will try to read token from `.env` and print the suggested remote URL.
If you confirm, it can add the remote for you.
"""
import os
import subprocess
from pathlib import Path

try:
    from dotenv import load_dotenv
except Exception:
    load_dotenv = None

ROOT = Path.cwd()

def load_token():
    if load_dotenv:
        p = ROOT / '.env'
        if p.exists():
            load_dotenv(p)
    for key in ('HF_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGINGFACE_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HF'):
        v = os.getenv(key)
        if v:
            return v
    return None

def run(cmd):
    print('>', ' '.join(cmd))
    return subprocess.run(cmd, cwd=ROOT)

def main():
    token = load_token()
    if not token:
        print('No HF token found in .env or env. Run `huggingface-cli login` or set HF_TOKEN in .env')
        return

    repo = ROOT.name
    username = None
    # Try to discover username via huggingface_hub if available
    try:
        from huggingface_hub import HfApi
        api = HfApi()
        info = api.whoami(token=token)
        username = info.get('name') or (info.get('user') or {}).get('name')
    except Exception:
        pass

    if not username:
        username = input('Hugging Face username (not found automatically): ').strip()
        if not username:
            print('Username required to compose remote. Exiting.')
            return

    remote = f"https://{token}@huggingface.co/spaces/{username}/{repo}.git"
    print('\nSuggested remote URL:')
    print(remote)
    print('\nYou can add this remote (token will be stored in git config).')
    ans = input('Add remote and push now? [y/N]: ').strip().lower()
    if ans != 'y':
        print('Done — you can add the remote manually if desired.')
        return

    # remove origin if exists
    run(['git', 'remote', 'remove', 'origin'])
    run(['git', 'remote', 'add', 'origin', remote])
    run(['git', 'push', '-u', 'origin', 'main'])
    print('Pushed to remote. Visit https://huggingface.co/spaces/{}/{}'.format(username, repo))

if __name__ == '__main__':
    main()