Spaces:
Sleeping
Add follow-up deployment support: Update existing spaces instead of creating new ones
Browse filesImplemented the same pattern as original deploy.py where follow-up prompts
update the existing deployed space with new commits instead of creating new spaces.
backend_deploy.py changes:
- Added existing_repo_id parameter to deploy_to_huggingface_space()
- Added commit_message parameter for custom commit messages
- Added is_update logic to detect updates vs new deployments
- Skip create_repo() when updating existing space
- Use appropriate commit message: "Update from anycoder" vs "Deploy from anycoder"
- Return different success message: "Updated" vs "Deployed"
- Skip 2-second wait for README on updates (already exists)
backend_api.py changes:
- Updated DeploymentRequest model to include:
* existing_repo_id (optional) - for explicitly updating a space
* commit_message (optional) - custom commit message
* space_name now optional (not needed for updates)
- Added deployed_spaces tracking to user_sessions
- Deploy endpoint now:
* Checks session for previously deployed spaces
* Automatically finds most recent space for same language
* Passes existing_repo_id to deployment function
* Tracks deployed spaces after successful deployment
* Returns repo_id in response for frontend tracking
Deployment flow:
1. First deployment: Creates new space, tracks in session
2. Follow-up for same language: Finds existing space from session
3. Updates that space with new commit (preserves git history)
4. Each update creates a new commit in the space's git repo
This matches the original Gradio UI behavior where:
- Initial "make a gradio app" creates new space
- Follow-up "add a button" updates the same space
- History is preserved with proper git commits
Session tracking ensures follow-up prompts in the same session
automatically update the correct space without user intervention.
Files changed (2)
- backend_api.py+47-3
- backend_deploy.py+59-40
109 unmodified lines110111112113113114115116117118119120154 unmodified lines275276277278279280281282274 unmodified lines5575585595605615625635645655665675685695705715725735745755765775782 unmodified lines581582583564584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613571614615616617618109 unmodified lines
class DeploymentRequest(BaseModel): code: str space_name: str space_name: Optional[str] = None language: str requirements: Optional[str] = None existing_repo_id: Optional[str] = None # For updating existing spaces commit_message: Optional[str] = None
class AuthStatus(BaseModel):154 unmodified lines "access_token": access_token, "user_info": user_info, "timestamp": datetime.now(), "username": user_info.get("name") or user_info.get("preferred_username") or "user", "deployed_spaces": [] # Track deployed spaces for follow-up updates } # Redirect to frontend with session token274 unmodified lines print(f"[Deploy] Attempting deployment with token (first 10 chars): {user_token[:10]}...") # Check for existing deployed space in this session existing_repo_id = request.existing_repo_id session_token = authorization.replace("Bearer ", "") if authorization else None # If no existing_repo_id provided, check session for previously deployed spaces if not existing_repo_id and session_token and session_token in user_sessions: session = user_sessions[session_token] deployed_spaces = session.get("deployed_spaces", []) # Find the most recent space for this language for space in reversed(deployed_spaces): if space.get("language") == request.language: existing_repo_id = space.get("repo_id") print(f"[Deploy] Found existing space for {request.language}: {existing_repo_id}") break # Use the standalone deployment function success, message, space_url = deploy_to_huggingface_space( code=request.code,2 unmodified lines token=user_token, username=auth.username, description=request.description if hasattr(request, 'description') else None, private=False private=False, existing_repo_id=existing_repo_id, commit_message=request.commit_message ) if success: # Track deployed space in session for follow-up updates if session_token and session_token in user_sessions: repo_id = space_url.split("/spaces/")[-1] if space_url else None if repo_id: session = user_sessions[session_token] deployed_spaces = session.get("deployed_spaces", []) # Update or add the space space_entry = { "repo_id": repo_id, "language": request.language, "timestamp": datetime.now() } # Remove old entry for same repo_id if exists deployed_spaces = [s for s in deployed_spaces if s.get("repo_id") != repo_id] deployed_spaces.append(space_entry) session["deployed_spaces"] = deployed_spaces print(f"[Deploy] Tracked space in session: {repo_id}") return { "success": True, "space_url": space_url, "message": message "message": message, "repo_id": repo_id if 'repo_id' in locals() else None } else: # Provide user-friendly error message based on the error255 unmodified lines2562572582592592602612622632622642652662672682672692702712722712732742752762772786 unmodified lines28528628728428528628728828929028828929029129229329429529629729829930030130230330429229329429529629729829930030530630730830931031131231331431531667 unmodified lines384385386387374375376377378379380381382383384385386387388388389390391392393394395396397398399400401402403404405406407408409410411412396413414415416417418402403419420421422423406424425426427428429430431413432433434435255 unmodified lines token: Optional[str] = None, username: Optional[str] = None, description: Optional[str] = None, private: bool = False private: bool = False, existing_repo_id: Optional[str] = None, commit_message: Optional[str] = None) -> Tuple[bool, str, Optional[str]]: """ Deploy code to HuggingFace Spaces Deploy code to HuggingFace Spaces (create new or update existing) Args: code: Generated code to deploy language: Target language/framework (html, gradio, streamlit, react, transformers.js, comfyui) space_name: Name for the space (auto-generated if None) space_name: Name for the space (auto-generated if None, ignored if existing_repo_id provided) token: HuggingFace API token username: HuggingFace username description: Space description private: Whether to make the space private private: Whether to make the space private (only for new spaces) existing_repo_id: If provided (username/space-name), updates this space instead of creating new one commit_message: Custom commit message (defaults to "Deploy from anycoder" or "Update from anycoder") Returns: Tuple of (success: bool, message: str, space_url: Optional[str])6 unmodified lines try: api = HfApi(token=token) # Get username if not provided if not username: try: user_info = api.whoami() username = user_info.get("name") or user_info.get("preferred_username") or "user" except Exception as e: return False, f"Failed to get user info: {str(e)}", None # Determine if this is an update or new deployment is_update = existing_repo_id is not None if is_update: # Use existing repo repo_id = existing_repo_id space_name = existing_repo_id.split('/')[-1] username = existing_repo_id.split('/')[0] if '/' in existing_repo_id else username else: # Get username if not provided if not username: try: user_info = api.whoami() username = user_info.get("name") or user_info.get("preferred_username") or "user" except Exception as e: return False, f"Failed to get user info: {str(e)}", None # Generate space name if not provided if not space_name: space_name = f"anycoder-{uuid.uuid4().hex[:8]}" # Clean space name (no spaces, lowercase, alphanumeric + hyphens) space_name = re.sub(r'[^a-z0-9-]', '-', space_name.lower()) space_name = re.sub(r'-+', '-', space_name).strip('-') repo_id = f"{username}/{space_name}" # Generate space name if not provided if not space_name: space_name = f"anycoder-{uuid.uuid4().hex[:8]}" # Clean space name (no spaces, lowercase, alphanumeric + hyphens) space_name = re.sub(r'[^a-z0-9-]', '-', space_name.lower()) space_name = re.sub(r'-+', '-', space_name).strip('-') repo_id = f"{username}/{space_name}" # Detect SDK sdk = detect_sdk_from_code(code, language)67 unmodified lines # Don't create README - HuggingFace will auto-generate it # We'll add the anycoder tag after deployment # Create the space (only for new deployments) # Create the space try: api.create_repo( repo_id=repo_id, repo_type="space", space_sdk=sdk, private=private, exist_ok=False ) except Exception as e: if "already exists" in str(e).lower(): # Space exists, we'll update it pass else: return False, f"Failed to create space: {str(e)}", None if not is_update: try: api.create_repo( repo_id=repo_id, repo_type="space", space_sdk=sdk, private=private, exist_ok=False ) except Exception as e: if "already exists" in str(e).lower(): # Space exists, treat as update is_update = True else: return False, f"Failed to create space: {str(e)}", None # Upload all files if not commit_message: commit_message = "Update from anycoder" if is_update else "Deploy from anycoder" try: api.upload_folder( folder_path=str(temp_path), repo_id=repo_id, repo_type="space", commit_message="Deploy from anycoder" commit_message=commit_message ) except Exception as e: return False, f"Failed to upload files: {str(e)}", None # After successful upload, modify the auto-generated README to add anycoder tag # HuggingFace automatically creates README.md when space is created # Wait a moment for it to be generated, then modify it # For new spaces: HF auto-generates README, wait and modify it # For updates: README should already exist, just add tag if missing try: import time if not is_update: time.sleep(2) # Give HF time to generate README time.sleep(2) # Give HF time to generate README for new spaces add_anycoder_tag_to_readme(api, repo_id, app_port) except Exception as e: # Don't fail deployment if README modification fails print(f"Warning: Could not add anycoder tag to README: {e}") space_url = f"https://huggingface.co/spaces/{repo_id}" action = "Updated" if is_update else "Deployed" return True, f"✅ Successfully deployed to {repo_id}!", space_url return True, f"✅ {action} successfully to {repo_id}!", space_url except Exception as e: return False, f"Deployment error: {str(e)}", None