| |
| """ 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) |
| |
| username = api.whoami(token=hf_token)['name'] |
| repo_id = f"{username}/{space_name.strip()}" |
|
|
| |
| api.create_repo(repo_id, repo_type="space", space_sdk=sdk, exist_ok=True) |
| |
| |
| file_path_in_repo = "index.html" if sdk == 'static' else "app.py" |
| |
| |
| api.upload_file( |
| path_or_fileobj=code.encode('utf-8'), |
| path_in_repo=file_path_in_repo, |
| repo_id=repo_id, |
| repo_type="space" |
| ) |
| |
| |
| space_url = f"https://huggingface.co/spaces/{repo_id}" |
| |
| |
| return f"✅ Deployed successfully! [Open your Space]({space_url})" |
|
|
| except Exception as e: |
| |
| logging.error(f"Failed to deploy to Hugging Face Space: {e}") |
| return f"❌ Deployment failed: {str(e)}" |