fix transformers js deploy
Browse files485 unmodified lines48648748848949049149249349449549649749849950050150250350450550650750850951051151251351451524 unmodified lines54054154254354454554654716 unmodified lines56456556656756856957057157257357457557657757857958058158211 unmodified lines59459559659759859960060160260360460560660710 unmodified lines618619620621622623485 unmodified linestry:from huggingface_hub import duplicate_space# duplicate_space expects just the space name, not the full repo_idprint(f"[Deploy] Attempting to duplicate template space to: {space_name}")result = duplicate_space(from_id="static-templates/transformers.js",to_id=space_name,token=token,exist_ok=True)print(f"[Deploy] Template duplication result: {result}")except Exception as e:# If template duplication fails, fall back to regular createprint(f"[Deploy] Template duplication failed, creating regular static space: {e}")import tracebacktraceback.print_exc()try:api.create_repo(repo_id=repo_id,repo_type="space",space_sdk=sdk,private=private,exist_ok=True)except Exception as e2:return False, f"Failed to create transformers.js space: {str(e2)}", Noneelse:# For updates, verify we can access the existing spacetry:24 unmodified linescommit_message = "Update from anycoder" if is_update else "Deploy from anycoder"try:if use_individual_uploads:# For transformers.js, React, Streamlit: upload each file individually (matches original deploy.py)import time# Get list of files to upload from temp directory16 unmodified linesif not file_path.exists():return False, f"Failed to upload: {filename} not found", None# Upload with retry logic (like original)success = Falselast_error = Nonefor attempt in range(max_attempts):try:# MATCH GRADIO: upload_file WITHOUT commit_message for individual filesapi.upload_file(path_or_fileobj=str(file_path),path_in_repo=filename,repo_id=repo_id,repo_type="space"# NO commit_message - HF API handles this automatically for spaces)success = Trueprint(f"[Deploy] Successfully uploaded {filename}")11 unmodified linesif not success:return False, f"Failed to upload {filename} after {max_attempts} attempts: {last_error}", Noneelse:# For other languages, use upload_folder (Gradio uses individual files everywhere)# MATCH GRADIO: No commit_message for spacesprint(f"[Deploy] Uploading folder to {repo_id}")api.upload_folder(folder_path=str(temp_path),repo_id=repo_id,repo_type="space"# NO commit_message - HF API handles this automatically for spaces)except Exception as e:return False, f"Failed to upload files: {str(e)}", None10 unmodified lines# Don't fail deployment if README modification failsprint(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"✅ {action} successfully to {repo_id}!", space_url485 unmodified lines48648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152224 unmodified lines54754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061116 unmodified lines62862963063163263363463563663763863964064164264364464511 unmodified lines65765865966066166266366466566666766810 unmodified lines679680681682683684685686687688689690691692693485 unmodified linestry:from huggingface_hub import duplicate_space# duplicate_space expects just the space name (not full repo_id)# Use strip() to clean the space nameprint(f"[Deploy] Attempting to duplicate template space to: {space_name.strip()}")duplicated_repo = duplicate_space(from_id="static-templates/transformers.js",to_id=space_name.strip(),token=token,exist_ok=True)print(f"[Deploy] Template duplication result: {duplicated_repo} (type: {type(duplicated_repo)})")except Exception as e:# Handle potential RepoUrl object errorserror_msg = str(e)if "'url'" in error_msg or "RepoUrl" in error_msg:# For RepoUrl object issues, check if the space was actually created successfullyprint(f"[Deploy] RepoUrl error detected, checking if space was created: {error_msg}")try:# Check if space exists by trying to access itspace_info = api.space_info(repo_id)if space_info:print(f"[Deploy] Space exists despite RepoUrl error, continuing with deployment")else:return False, f"Failed to create transformers.js space: {str(e)}", Noneexcept Exception as check_error:return False, f"Failed to create transformers.js space: {str(e)}", Noneelse:# Other errors - report themprint(f"[Deploy] Template duplication failed: {e}")import tracebacktraceback.print_exc()return False, f"Failed to create transformers.js space: {str(e)}", Noneelse:# For updates, verify we can access the existing spacetry:24 unmodified linescommit_message = "Update from anycoder" if is_update else "Deploy from anycoder"try:if language == "transformers.js":# Special handling for transformers.js - create NEW temp files for each upload# This matches the working pattern in ui.pyimport time# Get the parsed files from earlierfiles_to_upload = [("index.html", files.get('index.html')),("index.js", files.get('index.js')),("style.css", files.get('style.css'))]max_attempts = 3for file_name, file_content in files_to_upload:if not file_content:return False, f"Missing content for {file_name}", Nonesuccess = Falselast_error = Nonefor attempt in range(max_attempts):temp_file_path = Nonetry:# Create a NEW temp file for this upload (key difference from old approach)with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False, encoding='utf-8') as f:f.write(file_content)temp_file_path = f.name# Upload the file without commit_message (HF handles this for spaces)api.upload_file(path_or_fileobj=temp_file_path,path_in_repo=file_name,repo_id=repo_id,repo_type="space")success = Trueprint(f"[Deploy] Successfully uploaded {file_name}")breakexcept Exception as e:last_error = eerror_str = str(e)print(f"[Deploy] Upload error for {file_name}: {error_str}")if "403" in error_str or "Forbidden" in error_str:return False, f"Permission denied uploading {file_name}. Check your token has write access to {repo_id}.", Noneif attempt < max_attempts - 1:time.sleep(2) # Wait before retryprint(f"[Deploy] Retry {attempt + 1}/{max_attempts} for {file_name}")finally:# Clean up temp fileif temp_file_path and os.path.exists(temp_file_path):os.unlink(temp_file_path)if not success:return False, f"Failed to upload {file_name} after {max_attempts} attempts: {last_error}", Noneelif use_individual_uploads:# For React, Streamlit: upload each file individuallyimport time# Get list of files to upload from temp directory16 unmodified linesif not file_path.exists():return False, f"Failed to upload: {filename} not found", None# Upload with retry logicsuccess = Falselast_error = Nonefor attempt in range(max_attempts):try:# Upload without commit_message - HF API handles this for spacesapi.upload_file(path_or_fileobj=str(file_path),path_in_repo=filename,repo_id=repo_id,repo_type="space")success = Trueprint(f"[Deploy] Successfully uploaded {filename}")11 unmodified linesif not success:return False, f"Failed to upload {filename} after {max_attempts} attempts: {last_error}", Noneelse:# For other languages, use upload_folderprint(f"[Deploy] Uploading folder to {repo_id}")api.upload_folder(folder_path=str(temp_path),repo_id=repo_id,repo_type="space")except Exception as e:return False, f"Failed to upload files: {str(e)}", None10 unmodified lines# Don't fail deployment if README modification failsprint(f"Warning: Could not add anycoder tag to README: {e}")# For transformers.js updates, trigger a space restart to ensure changes take effectif is_update and language == "transformers.js":try:api.restart_space(repo_id=repo_id)print(f"[Deploy] Restarted space after update: {repo_id}")except Exception as restart_error:# Don't fail the deployment if restart fails, just log itprint(f"Note: Could not restart space after update: {restart_error}")space_url = f"https://huggingface.co/spaces/{repo_id}"action = "Updated" if is_update else "Deployed"return True, f"✅ {action} successfully to {repo_id}!", space_url
backend_deploy.py+97-27