"""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()