File size: 2,585 Bytes
e454383 32ca700 e454383 32ca700 e454383 32ca700 e454383 32ca700 e454383 32ca700 | 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 | 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
)
|