update
Browse files9 unmodified lines1011121314159 unmodified linesdisable_embedding: truehf_oauth: truehf_oauth_scopes:- write-repos- manage-repos---9 unmodified lines101112131415169 unmodified linesdisable_embedding: truehf_oauth: truehf_oauth_scopes:- read-repos- write-repos- manage-repos---
210 unmodified lines21121221321421521615 unmodified lines23223323423523623723823924024124224324424524624763 unmodified lines31131231331431531631731831932032132232319 unmodified lines3433443453463473483493503513523533543 unmodified lines35835936036136236336436536636736813 unmodified lines3823833843853863873881 unmodified line3903913923933943957 unmodified lines403404405406407408768 unmodified lines117711781179118011811182125 unmodified lines1308130913101311131213131314210 unmodified linesif not username:username = user_info.get('name', 'user')print(f"Debug: Final username: {username}")except Exception as e:print(f"Debug: Could not get user info: {e}")return {15 unmodified lines# Create the spacetry:repo_url = user_hf_api.create_repo(repo_id=repo_name,repo_type="space",space_sdk="static",private=False,exist_ok=False)print(f"Debug: Successfully created space: {repo_url}")except Exception as e:print(f"Debug: Failed to create space: {e}")raise e# Prepare the HTML content with proper structure63 unmodified linesfull_html = html_template.format(title=title, html_content=html_content)# Upload the HTML fileuser_hf_api.upload_file(path_or_fileobj=full_html.encode('utf-8'),path_in_repo="index.html",repo_id=repo_name,repo_type="space")# Create README.md with project infoprompts_text = "".join([f"- {prompt}\n" for prompt in (prompts or [])])19 unmodified linesreadme_content = readme_template.format(title=title, prompts_text=prompts_text, repo_name=repo_name)user_hf_api.upload_file(path_or_fileobj=readme_content.encode('utf-8'),path_in_repo="README.md",repo_id=repo_name,repo_type="space")return {"success": True,3 unmodified lines}except Exception as e:return {"success": False,"error": str(e),"message": f"Failed to create space: {str(e)}"}def deploy_to_space(title: str, html_content: str, history: History, oauth_profile: gr.OAuthProfile = None, oauth_token: gr.OAuthToken = None) -> str:"""13 unmodified lines**How to log in:**1. Click the "Sign in with Hugging Face" button in the sidebar2. Authorize AnyCoder to access your Hugging Face account3. Try deploying again**Why login is required:**1 unmodified line- You need write permissions to create spaces- This ensures you own and can manage your deployed applications---*Please log in and try again.*"""7 unmodified linesprint(f"Debug: Token length: {len(user_token) if user_token else 0}")print(f"Debug: Token starts with: {user_token[:10] if user_token else 'None'}...")# Extract prompts from historyprompts = []for user_msg, _ in history:768 unmodified linessize="sm")# Main input sectioninput = gr.Textbox(label="What would you like to build?",125 unmodified linessandbox = gr.HTML(label="Live preview")with gr.Tab("Deploy"):deploy_output = gr.Markdown(value="## π Deploy Your Application\n\n1. Generate some code first\n2. Enter a title for your space\n3. Click 'Deploy to Space' in the sidebar\n\nYour application will be deployed to Hugging Face Spaces and you'll get a shareable URL!",label="Deployment Status")with gr.Tab("History"):210 unmodified lines21121221321421521621721821922022122222322422515 unmodified lines24124224324424524624724824925025125225325425525625725825926026126226326426526626763 unmodified lines33133233333433533633733833934034134234334434534634734834935035135235335435535635735819 unmodified lines3783793803813823833843853863873883893903913923 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343413 unmodified lines4484494504514524534544554564571 unmodified line4594604614624634644654667 unmodified lines474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553768 unmodified lines132213231324132513261327132813291330125 unmodified lines14561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490210 unmodified linesif not username:username = user_info.get('name', 'user')print(f"Debug: Final username: {username}")# Additional validationif not username or username == 'user':return {"success": False,"error": "Could not retrieve username from token","message": "The authentication token is valid but username could not be retrieved. Please try logging in again."}except Exception as e:print(f"Debug: Could not get user info: {e}")return {15 unmodified lines# Create the spacetry:print(f"Debug: Creating space with parameters:")print(f" repo_id: {repo_name}")print(f" repo_type: space")print(f" space_sdk: static")print(f" private: False")print(f" exist_ok: False")print(f" token length: {len(api_token) if api_token else 0}")repo_url = user_hf_api.create_repo(repo_id=repo_name,repo_type="space",space_sdk="static",private=False,exist_ok=False,token=api_token)print(f"Debug: Successfully created space: {repo_url}")except Exception as e:print(f"Debug: Failed to create space: {e}")print(f"Debug: Exception type: {type(e)}")print(f"Debug: Exception args: {e.args}")raise e# Prepare the HTML content with proper structure63 unmodified linesfull_html = html_template.format(title=title, html_content=html_content)# Check HTML content sizehtml_size = len(full_html.encode('utf-8'))print(f"Debug: HTML content size: {html_size} bytes")if html_size > 1000000: # 1MB limitprint(f"Debug: Warning - HTML content is large ({html_size} bytes)")# Truncate if too largeif len(html_content) > 500000: # 500KB limit for contenthtml_content = html_content[:500000] + "\n<!-- Content truncated due to size -->"full_html = html_template.format(title=title, html_content=html_content)print(f"Debug: HTML content truncated to {len(full_html.encode('utf-8'))} bytes")# Upload the HTML fileprint(f"Debug: Uploading index.html to {repo_name}")user_hf_api.upload_file(path_or_fileobj=full_html.encode('utf-8'),path_in_repo="index.html",repo_id=repo_name,repo_type="space",token=api_token)print(f"Debug: Successfully uploaded index.html")# Create README.md with project infoprompts_text = "".join([f"- {prompt}\n" for prompt in (prompts or [])])19 unmodified linesreadme_content = readme_template.format(title=title, prompts_text=prompts_text, repo_name=repo_name)print(f"Debug: Uploading README.md to {repo_name}")user_hf_api.upload_file(path_or_fileobj=readme_content.encode('utf-8'),path_in_repo="README.md",repo_id=repo_name,repo_type="space",token=api_token)print(f"Debug: Successfully uploaded README.md")return {"success": True,3 unmodified lines}except Exception as e:error_msg = str(e)# Handle specific API errorsif "401" in error_msg or "Unauthorized" in error_msg:return {"success": False,"error": "Authentication failed - please log in again","message": "Your token may have expired. Please log out and log back in."}elif "403" in error_msg or "Forbidden" in error_msg:return {"success": False,"error": "Permission denied - insufficient privileges","message": "You may not have permission to create spaces. Please check your Hugging Face account settings."}elif "409" in error_msg or "Conflict" in error_msg:return {"success": False,"error": "Repository already exists","message": "A space with this name already exists. Please try a different title."}elif "422" in error_msg or "Validation" in error_msg:return {"success": False,"error": "Invalid repository name","message": "The space title contains invalid characters. Please use only letters, numbers, hyphens, and underscores."}else:return {"success": False,"error": error_msg,"message": f"Failed to create space: {error_msg}"}def deploy_to_space(title: str, html_content: str, history: History, oauth_profile: gr.OAuthProfile = None, oauth_token: gr.OAuthToken = None) -> str:"""13 unmodified lines**How to log in:**1. Click the "Sign in with Hugging Face" button in the sidebar2. Authorize AnyCoder to access your Hugging Face account with the required permissions:- read-repos- write-repos- manage-repos3. Try deploying again**Why login is required:**1 unmodified line- You need write permissions to create spaces- This ensures you own and can manage your deployed applications**Note:** Make sure to grant all the requested permissions when authorizing the application.---*Please log in and try again.*"""7 unmodified linesprint(f"Debug: Token length: {len(user_token) if user_token else 0}")print(f"Debug: Token starts with: {user_token[:10] if user_token else 'None'}...")# Additional debugging for OAuth componentsprint(f"Debug: OAuth profile type: {type(oauth_profile)}")print(f"Debug: OAuth token type: {type(oauth_token)}")print(f"Debug: OAuth profile attributes: {dir(oauth_profile) if oauth_profile else 'None'}")print(f"Debug: OAuth token attributes: {dir(oauth_token) if oauth_token else 'None'}")# Validate token formatif not user_token or not user_token.startswith('hf_'):return """β **Invalid Token Format**The OAuth token appears to be invalid or in the wrong format. Please try logging out and logging back in.**Steps to fix:**1. Click the logout button in the sidebar2. Click "Sign in with Hugging Face" again3. Authorize the application with the required permissions (read-repos, write-repos, manage-repos)4. Try deploying again**Note:** Make sure you authorize all the required permissions when logging in.---*Please try logging in again.*"""# Test the token by making a simple API calltry:test_api = HfApi(token=user_token)user_info = test_api.whoami()print(f"Debug: Token test successful - user: {user_info.get('name', 'unknown')}")# Check if user has the necessary permissions by trying to list their repostry:repos = test_api.list_repos(author=username, token=user_token)print(f"Debug: User has {len(list(repos))} repositories")except Exception as repo_error:print(f"Debug: Could not list repos: {repo_error}")return """β **Insufficient Permissions**Your Hugging Face account doesn't have the necessary permissions to create spaces. This could be because:1. You didn't grant all the required permissions during login2. Your account has restrictions on creating repositories3. The OAuth token doesn't include the necessary scopes**Steps to fix:**1. Click the logout button in the sidebar2. Click "Sign in with Hugging Face" again3. Make sure to grant ALL the requested permissions:- read-repos- write-repos- manage-repos4. Try deploying again---*Please log in again with full permissions.*"""except Exception as token_error:print(f"Debug: Token test failed: {token_error}")return """β **Token Validation Failed**The OAuth token could not be validated. This could be because:1. The token has expired2. The token doesn't have the right permissions3. There's an issue with the authentication**Steps to fix:**1. Click the logout button in the sidebar2. Click "Sign in with Hugging Face" again3. Authorize with all required permissions4. Try deploying again---*Please log in again.*"""# Extract prompts from historyprompts = []for user_msg, _ in history:768 unmodified linessize="sm")# OAuth components are automatically injected as function parameters# when using gr.LoginButton() - no need to create them separately# Main input sectioninput = gr.Textbox(label="What would you like to build?",125 unmodified linessandbox = gr.HTML(label="Live preview")with gr.Tab("Deploy"):deploy_output = gr.Markdown(value="""## π Deploy Your Application### Prerequisites1. **Login Required**: You must be logged in with your Hugging Face account2. **Permissions**: Grant the following permissions when logging in:- read-repos- write-repos- manage-repos### Steps to Deploy1. **Login**: Click "Sign in with Hugging Face" in the sidebar2. **Generate Code**: Generate some HTML code using the AI3. **Enter Title**: In the sidebar, enter a title for your space (e.g., "My Todo App")4. **Deploy**: Click the "π Deploy to Space" button### What Happens- Your application will be deployed to Hugging Face Spaces under your account- You'll get a shareable URL (e.g., `https://huggingface.co/spaces/yourusername/my-app-1234567890`)- The deployment includes professional styling and documentation### TroubleshootingIf deployment fails:- Make sure you're logged in with the correct account- Ensure you granted all required permissions during login- Try logging out and logging back in- Check that your Hugging Face account can create repositories---*Your application will be deployed to Hugging Face Spaces and you'll get a shareable URL!*""",label="Deployment Status")with gr.Tab("History"):
README.md+1
app.py+186-10