from huggingface_hub import HfApi, create_repo from typing import Dict, Optional import tempfile import os 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. """ if not token: raise ValueError("Hugging Face Token is required.") api = HfApi(token=token) # Authenticate and get user try: user_info = api.whoami() if not username: username = user_info['name'] except Exception as e: raise ValueError(f"Invalid Token: {str(e)}") repo_id = f"{username}/{space_name}" # Create Repo if not exists try: api.create_repo( repo_id=repo_id, repo_type="space", space_sdk="gradio", exist_ok=True, private=False # Default to public, can be changed ) except Exception as e: print(f"Repo creation/check status: {e}") # Prepare files for upload operations = [] # Create a temporary directory to write files to upload # Note: api.upload_file or upload_folder can be used. # We will use upload_file loop for simplicity with in-memory strings # Ideally we use commit_operations for atomicity but simple upload loop is fine for MVP # Let's use upload_file content directly try: for filename, content in files.items(): # Convert string content to bytes content_bytes = content.encode('utf-8') api.upload_file( path_or_fileobj=content_bytes, path_in_repo=filename, repo_id=repo_id, repo_type="space", commit_message=f"Update {filename} via Agent" ) return f"https://huggingface.co/spaces/{repo_id}" except Exception as e: raise RuntimeError(f"Deployment Failed: {str(e)}")