update
Browse files79 unmodified lines80818283848586878384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411579 unmodified lines
### How to Deploy
1. **Login**: Click the "Sign in with Hugging Face" button in the sidebar2. **Authorize Permissions**: When the authorization page appears, make sure to grant ALL the requested permissions: - β
**read-repos** - Read access to repositories - β
**write-repos** - Write access to create repositories - β
**manage-repos** - Manage repository settings1. **Login**: Click the "Sign in with Hugging Face" button in the sidebar and authorize with your Hugging Face account2. **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" button5. **Share**: Get a shareable URL for your deployed application3. **Complete Authorization**: Click "Authorize" to complete the login4. **Generate Code**: Generate some HTML code using the AI5. **Enter Title**: In the sidebar, enter a title for your space (e.g., "My Todo App")6. **Deploy**: Click the "π Deploy to Space" button7. **Share**: Get a shareable URL for your deployed application
**Important**: You must grant ALL three permissions during the OAuth authorization process. If you only grant partial permissions, deployment will fail.
**Note**: You need to be logged in with your Hugging Face account to deploy. This ensures that:- Deployments are created under your own account namespace2 unmodified lines
**Technical Note**: The deployment uses your personal OAuth token to create spaces under your account, ensuring full security and ownership of your deployed applications.
### Troubleshooting Deployment Issues
If you encounter permission errors during deployment:
1. **Check Permissions**: Make sure you granted all three required permissions during login2. **Logout and Login Again**: Click logout and sign in again, ensuring all permissions are granted3. **Account Status**: Verify your Hugging Face account allows repository creation4. **Network Issues**: Check your internet connection and try again5. **Contact Support**: If issues persist, contact Hugging Face support
### What Gets Deployed
- **Complete HTML Application**: Your generated code wrapped in a professional template184 unmodified lines185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223239 unmodified lines46346446543346646746846947043847147247344147447547647717 unmodified lines49549649746549849950050111 unmodified lines5135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625639 unmodified lines5735745754985765775785795 unmodified lines58558658758858959059159259359459559659759859960060160260360460560660760860951261061161261351651751861461561661761861962062162262352152252352452552652762462562662762862963063163263363463563663763863964064164264364464564664764864965065165265353065465565665712 unmodified lines6706716725496736746756761 unmodified line67867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376411 unmodified lines7767777785747797807817826 unmodified lines78979079158779279379479567 unmodified lines863864865866867868869870871872873874875876877878879880881882661 unmodified lines1544154515461547154815491550155184 unmodified lines16361637163816391640164116421643164416451646164740 unmodified lines16881689169014641465146616911692169316941695169616971470147114721698169917001701170217037 unmodified lines1711171217131714171517161717171814 unmodified lines17331734173515061736173717381739184 unmodified lines print(f"Failed to initialize Tavily client: {e}") tavily_client = None
def validate_oauth_scopes(oauth_token) -> Tuple[bool, List[str]]: """ Validate that the OAuth token has the required scopes for creating spaces Returns (is_valid, missing_scopes) """ required_scopes = ['read-repos', 'write-repos', 'manage-repos'] if not oauth_token: return False, required_scopes # Try to get scopes from the token object token_scopes = [] # Check different ways scopes might be stored if hasattr(oauth_token, 'scopes'): token_scopes = oauth_token.scopes elif hasattr(oauth_token, 'scope'): token_scopes = oauth_token.scope.split(' ') if oauth_token.scope else [] elif hasattr(oauth_token, 'permissions'): token_scopes = oauth_token.permissions else: # If we can't determine scopes, assume they're missing return False, required_scopes # Convert to list if it's a string if isinstance(token_scopes, str): token_scopes = token_scopes.split(' ') # Check for required scopes missing_scopes = [scope for scope in required_scopes if scope not in token_scopes] return len(missing_scopes) == 0, missing_scopes
# Deployment functionsdef create_space_from_html(title: str, html_content: str, prompts: List[str] = None, user_token: str = None, username: str = None) -> Dict: """239 unmodified lines "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:def deploy_to_space(title: str, html_content: str, history: History, oauth_profile: gr.OAuthProfile = None, oauth_token: gr.OAuthToken = None) -> Tuple[str, str]: """ Deploy the generated HTML to a Hugging Face Space """ if not title or not title.strip(): return "β Please enter a title for your space." return "β Please enter a title for your space.", update_oauth_status(oauth_profile, oauth_token) if not html_content or not html_content.strip(): return "β No HTML content to deploy. Please generate some code first." return "β No HTML content to deploy. Please generate some code first.", update_oauth_status(oauth_profile, oauth_token) # Check if user is authenticated if not oauth_profile or not oauth_token:17 unmodified lines**Note:** Make sure to grant all the requested permissions when authorizing the application.
---*Please log in and try again.*"""*Please log in and try again.*""", update_oauth_status(oauth_profile, oauth_token) # Get user information from OAuth profile username = oauth_profile.name11 unmodified lines 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'}") # Check OAuth token scopes if available if hasattr(oauth_token, 'scopes'): print(f"Debug: OAuth token scopes: {oauth_token.scopes}") else: print("Debug: OAuth token scopes not available") # Check OAuth profile permissions if available if hasattr(oauth_profile, 'permissions'): print(f"Debug: OAuth profile permissions: {oauth_profile.permissions}") else: print("Debug: OAuth profile permissions not available") # Validate OAuth scopes scopes_valid, missing_scopes = validate_oauth_scopes(oauth_token) print(f"Debug: OAuth scopes valid: {scopes_valid}") print(f"Debug: Missing scopes: {missing_scopes}") if not scopes_valid: return f"""β **Missing OAuth Scopes**
Your OAuth token is missing the required permissions to create spaces.
**Missing Scopes:**{chr(10).join([f"- `{scope}`" for scope in missing_scopes])}
**Required Scopes:**- `read-repos` - Read access to repositories- `write-repos` - Write access to create repositories - `manage-repos` - Manage repository settings
**Steps to fix:**1. **Logout**: Click the logout button in the sidebar2. **Login Again**: Click "Sign in with Hugging Face" again3. **Grant All Permissions**: When the authorization page appears, make sure to check ALL the requested permissions: - β
read-repos - β
write-repos - β
manage-repos4. **Complete Authorization**: Click "Authorize" to complete the login5. **Try Deploying**: Try deploying again
**Important:** Make sure you see all three permissions checked on the authorization page before clicking "Authorize".
---*Please log in again with full permissions.*""", update_oauth_status(oauth_profile, oauth_token) # Validate token format if not user_token or not user_token.startswith('hf_'): return """β **Invalid Token Format**9 unmodified lines**Note:** Make sure you authorize all the required permissions when logging in.
---*Please try logging in again.*"""*Please try logging in again.*""", update_oauth_status(oauth_profile, oauth_token) # Test the token by making a simple API call try:5 unmodified lines try: repos = test_api.list_repos(author=username, token=user_token) print(f"Debug: User has {len(list(repos))} repositories") # Test if user can create repositories by checking their account type try: # Try to get user info to check account capabilities user_info = test_api.whoami() print(f"Debug: User info: {user_info}") # Check if user has pro account or sufficient permissions if user_info.get('type') == 'user': print("Debug: User account type confirmed") else: print(f"Debug: User account type: {user_info.get('type', 'unknown')}") except Exception as user_info_error: print(f"Debug: Could not get detailed user info: {user_info_error}") except Exception as repo_error: print(f"Debug: Could not list repos: {repo_error}") # Check if this is a scope/permission issue error_msg = str(repo_error).lower() if "403" in error_msg or "forbidden" in error_msg or "unauthorized" in error_msg: return """β **Insufficient Permissions** 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 scopes1. **Missing OAuth Scopes**: You didn't grant all the required permissions during login2. **Account Restrictions**: Your account has restrictions on creating repositories3. **Token Scope Issues**: The OAuth token doesn't include the necessary scopes
**Required Permissions:**- `read-repos` - Read access to repositories- `write-repos` - Write access to create repositories- `manage-repos` - Manage repository settings
**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 again1. **Logout**: Click the logout button in the sidebar2. **Login Again**: Click "Sign in with Hugging Face" again3. **Grant All Permissions**: When the authorization page appears, make sure to check ALL the requested permissions: - β
read-repos - β
write-repos - β
manage-repos4. **Complete Authorization**: Click "Authorize" to complete the login5. **Try Deploying**: Try deploying again
**Important:** Make sure you see all three permissions checked on the authorization page before clicking "Authorize".
---*Please log in again with full permissions.*""", update_oauth_status(oauth_profile, oauth_token) else: return f"""β **Repository Access Error**
Error: {str(repo_error)}
This could be due to:- Network connectivity issues- Hugging Face API temporary problems- Account-specific restrictions
**Steps to fix:**1. Check your internet connection2. Try logging out and logging back in3. Wait a few minutes and try again4. If the problem persists, check your Hugging Face account settings
---*Please log in again with full permissions.*"""*Please try again or contact support if the issue persists.*""", update_oauth_status(oauth_profile, oauth_token) except Exception as token_error: print(f"Debug: Token test failed: {token_error}")12 unmodified lines4. Try deploying again
---*Please log in again.*"""*Please log in again.*""", update_oauth_status(oauth_profile, oauth_token) # Extract prompts from history prompts = []1 unmodified line if isinstance(user_msg, str) and user_msg.strip(): prompts.append(user_msg.strip()) # Test if user can create repositories by attempting a test creation try: test_api = HfApi(token=user_token) # Try to create a test repository to verify permissions test_repo_name = f"{username}/test-permissions-{int(time.time())}" print(f"Debug: Testing repository creation with: {test_repo_name}") try: # Attempt to create a test repository test_repo_url = test_api.create_repo( repo_id=test_repo_name, repo_type="model", private=True, exist_ok=False, token=user_token ) print(f"Debug: Successfully created test repository: {test_repo_url}") # Clean up the test repository try: test_api.delete_repo(repo_id=test_repo_name, token=user_token) print(f"Debug: Successfully cleaned up test repository") except Exception as cleanup_error: print(f"Debug: Could not clean up test repository: {cleanup_error}") except Exception as test_create_error: print(f"Debug: Could not create test repository: {test_create_error}") error_msg = str(test_create_error).lower() if "403" in error_msg or "forbidden" in error_msg: return """β **Repository Creation Permission Denied**
Your Hugging Face account doesn't have permission to create repositories. This could be because:
1. **Account Type**: Your account type may not allow repository creation2. **Organization Restrictions**: If you're part of an organization, there may be restrictions3. **Account Status**: Your account may be limited or suspended
**Steps to fix:**1. **Check Account Status**: Visit https://huggingface.co/settings/account to check your account status2. **Verify Account Type**: Make sure your account allows repository creation3. **Contact Support**: If you believe this is an error, contact Hugging Face support4. **Try Different Account**: Consider using a different Hugging Face account
**Note:** Free accounts should be able to create repositories. If you're having issues, it might be a temporary restriction.
---*Please check your account settings or try with a different account.*""", update_oauth_status(oauth_profile, oauth_token) else: return f"""β **Repository Creation Test Failed**
Error: {str(test_create_error)}
This could be due to:- Network connectivity issues- Hugging Face API temporary problems- Account-specific restrictions
**Steps to fix:**1. Check your internet connection2. Wait a few minutes and try again3. If the problem persists, check your Hugging Face account settings
---*Please try again or contact support if the issue persists.*""", update_oauth_status(oauth_profile, oauth_token) except Exception as test_error: print(f"Debug: Repository creation test failed: {test_error}") return f"""β **Permission Test Failed**
Could not test repository creation permissions: {str(test_error)}
**Steps to fix:**1. Check your internet connection2. Try logging out and logging back in3. Wait a few minutes and try again
---*Please try again or contact support if the issue persists.*""", update_oauth_status(oauth_profile, oauth_token) # Use user's OAuth token to create space under their account result = create_space_from_html(title.strip(), html_content, prompts, user_token, username) 11 unmodified lines- Manage your space from your Hugging Face dashboard
---*Generated with β€οΈ using AnyCoder*"""*Generated with β€οΈ using AnyCoder*""", update_oauth_status(oauth_profile, oauth_token) else: return f"""β **Deployment failed**
6 unmodified lines- Make sure your Hugging Face account has the necessary permissions
---*Please try again or contact support if the issue persists.*"""*Please try again or contact support if the issue persists.*""", update_oauth_status(oauth_profile, oauth_token)
def history_to_messages(history: History, system: str) -> Messages: messages = [{'role': 'system', 'content': system}]67 unmodified linesdef clear_history(): return [], [], None, "" # Empty lists for both tuple format and chatbot messages, None for file, empty string for website URL
def update_oauth_status(oauth_profile: gr.OAuthProfile = None, oauth_token: gr.OAuthToken = None): """Update the OAuth status indicator based on login state""" if not oauth_profile or not oauth_token: return "π **Login Required**\nSign in to deploy applications" # Check if we have the required scopes scopes_valid, missing_scopes = validate_oauth_scopes(oauth_token) if scopes_valid: return f"β
**Logged in as {oauth_profile.name}**\nReady to deploy applications" else: missing_list = ", ".join(missing_scopes) return f"β οΈ **Incomplete Permissions**\nMissing: {missing_list}\nPlease logout and login again"
def update_image_input_visibility(model): """Update image input visibility based on selected model""" is_ernie_vl = model.get("id") == "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"661 unmodified lines # OAuth components are automatically injected as function parameters # when using gr.LoginButton() - no need to create them separately # OAuth status will be updated automatically by Gradio's OAuth system # Main input section input = gr.Textbox( label="What would you like to build?",84 unmodified lines else: gr.Markdown("β
Web search available") # OAuth status indicator oauth_status = gr.Markdown( value="π **Login Required**\nSign in to deploy applications", visible=True ) # Hidden elements for functionality model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=False) 40 unmodified lines### 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 - β
**read-repos** - Read access to repositories - β
**write-repos** - Write access to create repositories - β
**manage-repos** - Manage repository settings
### Steps to Deploy1. **Login**: Click "Sign in with Hugging Face" in the sidebar2. **Authorize Permissions**: When the authorization page appears, make sure to grant ALL the requested permissions2. **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" button3. **Generate Code**: Generate some HTML code using the AI4. **Enter Title**: In the sidebar, enter a title for your space (e.g., "My Todo App")5. **Deploy**: Click the "π Deploy to Space" button
### What Happens- Your application will be deployed to Hugging Face Spaces under your account7 unmodified lines- Try logging out and logging back in- Check that your Hugging Face account can create repositories
**Important**: You must grant ALL three permissions during the OAuth authorization process.
---*Your application will be deployed to Hugging Face Spaces and you'll get a shareable URL!*""", label="Deployment Status"14 unmodified lines deploy_btn.click( deploy_to_space, inputs=[space_title_input, code_output, history], outputs=[deploy_output], outputs=[deploy_output, oauth_status], api_name="deploy" )
README.md+22-5
app.py+257-27