monk / deploy_hf_space.py
hf-actions
Clean commit: remove virtualenv and large files
ca2863a
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()