# /deployment.py """ Handles deployment of generated code to Hugging Face Spaces. """ import logging from huggingface_hub import HfApi def deploy_to_hf_space(code: str, space_name: str, sdk: str, hf_token: str) -> str: """ Creates or updates a Hugging Face Space and uploads the generated code. """ if not code.strip(): return "Cannot deploy: No code has been generated." if not space_name.strip(): return "Cannot deploy: Please provide a name for your app." try: api = HfApi(token=hf_token) # Get the username associated with the token username = api.whoami(token=hf_token)['name'] repo_id = f"{username}/{space_name.strip()}" # Create the repository on the Hub api.create_repo(repo_id, repo_type="space", space_sdk=sdk, exist_ok=True) # Determine the correct filename based on the SDK file_path_in_repo = "index.html" if sdk == 'static' else "app.py" # Upload the generated code file api.upload_file( path_or_fileobj=code.encode('utf-8'), path_in_repo=file_path_in_repo, repo_id=repo_id, repo_type="space" ) # Construct the URL to the newly deployed Space space_url = f"https://huggingface.co/spaces/{repo_id}" # <--- FIX: The string literal is now correctly terminated --- return f"✅ Deployed successfully! [Open your Space]({space_url})" except Exception as e: # Provide a more informative error message logging.error(f"Failed to deploy to Hugging Face Space: {e}") return f"❌ Deployment failed: {str(e)}"