test / _backend /cli /hf_deployer.py
aiioe's picture
Fixed env problem
32ca700 verified
Raw History Blame Contribute Delete
2.59 kB
import tempfile
import os
from pathlib import Path
from huggingface_hub import HfApi, create_repo
def deploy_space(space_id: str, source_dir: Path, token: str, private: bool = False):
def generate_dynamic_readme(title: str) -> str:
return f'''---\ntitle: {title}\nemoji: 🧑‍💼\ncolorFrom: indigo\ncolorTo: blue\nsdk: docker\nsdk_version: "1.0"\napp_file: app.py\npinned: false\n---\n\n# {title}\n\nThis Space is deployed with a dynamic README.\n'''
import questionary
# Get token and space name from environment
space_id = os.getenv("HF_SPACE_ID")
token = os.getenv("HF_TOKEN")
if not space_id or not token:
raise RuntimeError("HF_SPACE_ID and HUGGINGFACE_TOKEN must be set in environment.")
title = os.getenv("HF_SPACE_TITLE") or questionary.text("Enter Hugging Face Space title:", default="Interview Synthesizer").ask()
dynamic_readme = generate_dynamic_readme(title)
with tempfile.NamedTemporaryFile("w", delete=False, encoding="utf-8", suffix=".md") as tmpf:
tmpf.write(dynamic_readme)
tmpf.flush()
tmp_readme_path = Path(tmpf.name)
import shutil
shutil.copy(tmp_readme_path, source_dir / "README.md")
# Prompt for commit message
commit_message = questionary.text("Commit message:", default="automated upload").ask()
api = HfApi()
try:
create_repo(space_id, repo_type="space", token=token, private=private, exist_ok=True)
except Exception as e:
print(f"Repo create/check warning: {e}")
api.add_space_secret
try:
create_repo(space_id, repo_type="space", token=token, private=private, exist_ok=True, space_sdk="docker")
except Exception as e:
print(f"Repo create/check warning: {e}")
# Remove .env from upload if present
env_path = source_dir / ".env"
if env_path.exists():
env_path.unlink()
api.upload_folder(
token=token,
repo_id=space_id,
repo_type="space",
folder_path=str(source_dir),
path_in_repo=".",
commit_message=commit_message
)
print(f"Uploaded to https://huggingface.co/spaces/{space_id}")
# Add secrets from environment to Space
for key in ["OPENAI_API_KEY", "ENVIRONMENT"]:
value = os.getenv(key)
if value:
api.add_space_secret(
repo_id=space_id,
key=key,
value=value,
description=f"Secret {key} for Space deployment",
token=token
)