pydeploy-studio / utils /deployer.py
codeboosterstech's picture
Upload 12 files
fcd463d verified
raw
history blame
2.26 kB
"""
Deployment logic for Hugging Face Spaces
"""
import re
from typing import Dict, Optional
from huggingface_hub import HfApi
def deploy_to_space(
token: str,
space_name: str,
files: Dict[str, str],
username: Optional[str] = None
) -> str:
"""
Deploys the given files to a Hugging Face Space.
Returns the URL of the deployed space.
"""
# Validate inputs
if not token:
raise ValueError("Hugging Face Token is required.")
if not token.startswith('hf_'):
raise ValueError("Invalid Hugging Face token. Should start with 'hf_'")
if not space_name:
raise ValueError("Space name is required.")
# Validate space name format
if not re.match(r'^[a-z0-9-]{3,30}$', space_name):
raise ValueError(
"Space name must be 3-30 characters, lowercase letters, numbers, and hyphens only."
)
# Initialize Hugging Face API
api = HfApi(token=token)
try:
# Get user information
user_info = api.whoami()
if not username:
username = user_info['name']
except Exception as e:
raise ValueError(f"Invalid Token: {str(e)}")
# Create repository ID
repo_id = f"{username}/{space_name}"
try:
# Create or update the Space
api.create_repo(
repo_id=repo_id,
repo_type="space",
space_sdk="gradio",
exist_ok=True,
private=False
)
except Exception as e:
print(f"Note: {e}")
try:
# Upload files
for filename, content in files.items():
# Ensure app.py is clean
if filename == "app.py":
if '```' in content:
content = content.replace('```', '')
api.upload_file(
path_or_fileobj=content.encode('utf-8'),
path_in_repo=filename,
repo_id=repo_id,
repo_type="space",
commit_message=f"Add {filename} via Space Creator"
)
return f"https://huggingface.co/spaces/{repo_id}"
except Exception as e:
raise RuntimeError(f"Deployment failed: {str(e)}")