update
Browse files79 unmodified lines80818283848586878889902 unmodified lines93949596979879 unmodified lines### How to Deploy1. **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 application**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.### What Gets Deployed- **Complete HTML Application**: Your generated code wrapped in a professional template79 unmodified lines8081828384858687888990919293949596972 unmodified lines10010110210310410510610710810911011111211311411579 unmodified lines### How to Deploy1. **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 settings3. **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 IssuesIf 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 template
184 unmodified lines185186187188189190239 unmodified lines43043143243343443543643743843944044144244344417 unmodified lines46246346446546646746811 unmodified lines4804814824834844859 unmodified lines4954964974984995005015 unmodified lines50750850951051151251351451551651751851952052152252352452552652752852953053153253312 unmodified lines5465475485495505515521 unmodified line55455555655755855911 unmodified lines5715725735745755765776 unmodified lines58458558658758858959067 unmodified lines658659660661662663661 unmodified lines13251326132713281329133084 unmodified lines14151416141714181419142040 unmodified lines1461146214631464146514661467146814691470147114721473147414757 unmodified lines14831484148514861487148814 unmodified lines1503150415051506150715081509184 unmodified linesprint(f"Failed to initialize Tavily client: {e}")tavily_client = None# 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:"""Deploy the generated HTML to a Hugging Face Space"""if not title or not title.strip():return "β Please enter a title for your space."if not html_content or not html_content.strip():return "β No HTML content to deploy. Please generate some code first."# Check if user is authenticatedif 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.*"""# Get user information from OAuth profileusername = oauth_profile.name11 unmodified linesprint(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**9 unmodified lines**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:5 unmodified linestry: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}")12 unmodified lines4. Try deploying again---*Please log in again.*"""# Extract prompts from historyprompts = []1 unmodified lineif isinstance(user_msg, str) and user_msg.strip():prompts.append(user_msg.strip())# Use user's OAuth token to create space under their accountresult = 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*"""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.*"""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 URLdef 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# Main input sectioninput = gr.Textbox(label="What would you like to build?",84 unmodified lineselse:gr.Markdown("β Web search available")# Hidden elements for functionalitymodel_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### 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 account7 unmodified lines- 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"14 unmodified linesdeploy_btn.click(deploy_to_space,inputs=[space_title_input, code_output, history],outputs=[deploy_output],api_name="deploy")184 unmodified lines185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223239 unmodified lines46346446546646746846947047147247347447547647717 unmodified lines49549649749849950050111 unmodified lines5135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625639 unmodified lines5735745755765775785795 unmodified lines58558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665712 unmodified lines6706716726736746756761 unmodified line67867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376411 unmodified lines7767777787797807817826 unmodified lines78979079179279379479567 unmodified lines863864865866867868869870871872873874875876877878879880881882661 unmodified lines1544154515461547154815491550155184 unmodified lines16361637163816391640164116421643164416451646164740 unmodified lines16881689169016911692169316941695169616971698169917001701170217037 unmodified lines1711171217131714171517161717171814 unmodified lines1733173417351736173717381739184 unmodified linesprint(f"Failed to initialize Tavily client: {e}")tavily_client = Nonedef validate_oauth_scopes(oauth_token) -> Tuple[bool, List[str]]:"""Validate that the OAuth token has the required scopes for creating spacesReturns (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 objecttoken_scopes = []# Check different ways scopes might be storedif hasattr(oauth_token, 'scopes'):token_scopes = oauth_token.scopeselif hasattr(oauth_token, 'scope'):token_scopes = oauth_token.scope.split(' ') if oauth_token.scope else []elif hasattr(oauth_token, 'permissions'):token_scopes = oauth_token.permissionselse:# If we can't determine scopes, assume they're missingreturn False, required_scopes# Convert to list if it's a stringif isinstance(token_scopes, str):token_scopes = token_scopes.split(' ')# Check for required scopesmissing_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) -> 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.", 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.", update_oauth_status(oauth_profile, oauth_token)# Check if user is authenticatedif 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.*""", update_oauth_status(oauth_profile, oauth_token)# Get user information from OAuth profileusername = oauth_profile.name11 unmodified linesprint(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 availableif 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 availableif hasattr(oauth_profile, 'permissions'):print(f"Debug: OAuth profile permissions: {oauth_profile.permissions}")else:print("Debug: OAuth profile permissions not available")# Validate OAuth scopesscopes_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 formatif 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.*""", update_oauth_status(oauth_profile, oauth_token)# Test the token by making a simple API calltry:5 unmodified linestry: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 typetry:# Try to get user info to check account capabilitiesuser_info = test_api.whoami()print(f"Debug: User info: {user_info}")# Check if user has pro account or sufficient permissionsif 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 issueerror_msg = str(repo_error).lower()if "403" in error_msg or "forbidden" in error_msg or "unauthorized" in error_msg:return """β **Insufficient Permissions**Your Hugging Face account doesn't have the necessary permissions to create spaces. This could be because:1. **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. **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 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.*""", update_oauth_status(oauth_profile, oauth_token)# Extract prompts from historyprompts = []1 unmodified lineif isinstance(user_msg, str) and user_msg.strip():prompts.append(user_msg.strip())# Test if user can create repositories by attempting a test creationtry:test_api = HfApi(token=user_token)# Try to create a test repository to verify permissionstest_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 repositorytest_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 repositorytry: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 accountresult = 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*""", 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.*""", 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 URLdef 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 scopesscopes_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 sectioninput = gr.Textbox(label="What would you like to build?",84 unmodified lineselse:gr.Markdown("β Web search available")# OAuth status indicatoroauth_status = gr.Markdown(value="π **Login Required**\nSign in to deploy applications",visible=True)# Hidden elements for functionalitymodel_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** - 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 permissions3. **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 linesdeploy_btn.click(deploy_to_space,inputs=[space_title_input, code_output, history],outputs=[deploy_output, oauth_status],api_name="deploy")
README.md+22-5
app.py+257-27