Spaces:
Sleeping
Sleeping
File size: 3,831 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
import os
import subprocess
import sys
import time
from pathlib import Path
try:
from dotenv import load_dotenv
except Exception:
load_dotenv = None
try:
from huggingface_hub import HfApi
except Exception:
HfApi = None
ROOT = Path.cwd()
def load_token():
if load_dotenv:
dotenv_path = ROOT / '.env'
if dotenv_path.exists():
load_dotenv(dotenv_path)
for name in ('HF_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HUGGINGFACE_TOKEN', 'HF'):
val = os.getenv(name)
if val:
return val
return None
def run(cmd, check=True):
print('>', ' '.join(cmd))
res = subprocess.run(cmd, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
print(res.stdout)
if check and res.returncode != 0:
raise SystemExit(res.returncode)
return res
def ensure_git_init():
if not (ROOT / '.git').exists():
run(['git', 'init'])
# set main branch
run(['git', 'branch', '-M', 'main'], check=False)
# Only add/commit if there are changes
status = subprocess.run(['git', 'status', '--porcelain'], cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
if status.stdout.strip():
# perform add/commit without capturing stdout to avoid blocking on large outputs/hooks
print('> git add .')
subprocess.run(['git', 'add', '.'], cwd=ROOT)
print('> git commit -m "Initial commit for HF Space"')
subprocess.run(['git', 'commit', '-m', 'Initial commit for HF Space'], cwd=ROOT)
def create_space_and_push(token, repo_name=None, private=False):
if HfApi is None:
print('huggingface_hub not installed. Please run: python -m pip install huggingface_hub')
raise SystemExit(1)
api = HfApi()
who = api.whoami(token=token)
username = who.get('name') or who.get('user', {}).get('name')
if not username:
print('Unable to determine HF username via token.')
raise SystemExit(1)
if repo_name is None:
repo_name = ROOT.name
repo_id = f"{username}/{repo_name}"
print('Creating or ensuring Space:', repo_id)
try:
api.create_repo(repo_id=repo_id, repo_type='space', token=token, private=private, space_sdk='gradio')
print('Repository created or already exists.')
except Exception as e:
print('create_repo warning:', e)
# Use huggingface_hub.Repository helper to push with token
try:
from huggingface_hub import Repository
repo_local_dir = str(ROOT)
print('Using huggingface_hub.Repository to push files (handles auth).')
repo = Repository(local_dir=repo_local_dir, clone_from=repo_id, use_auth_token=token)
repo.push_to_hub(commit_message='Initial commit for HF Space')
except Exception as e:
print('Repository push via huggingface_hub failed:', e)
print('Falling back to adding token-embedded remote and git push (may fail if token invalid).')
remote = f"https://{token}@huggingface.co/spaces/{repo_id}.git"
# remove existing origin if points elsewhere
run(['git', 'remote', 'remove', 'origin'], check=False)
run(['git', 'remote', 'add', 'origin', remote])
run(['git', 'push', '-u', 'origin', 'main'], check=False)
def main():
token = load_token()
if not token:
print('No HF token found in environment or .env. Set HF_TOKEN or HUGGINGFACEHUB_API_TOKEN in .env or env.')
sys.exit(2)
ensure_git_init()
create_space_and_push(token, repo_name=None, private=False)
print('\nDeploy complete. Visit your Space URL:')
time.sleep(0.5)
print('https://huggingface.co/spaces/{owner}/{repo}'.format(owner=HfApi().whoami(token=token).get('name'), repo=ROOT.name))
if __name__ == '__main__':
main()
|