update to add deploy
Browse files8 unmodified lines9101112131412 unmodified lines27282930313234 unmodified lines6768697071728 unmodified linespinned: falsedisable_embedding: truehf_oauth: true---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12 unmodified lines- **Web Search Integration**: Enable real-time web search to get the latest information and best practices- **Chat History**: Keep track of your conversations and generated code- **Quick Examples**: Pre-built examples to get you started quickly## Installation34 unmodified lines6. View the generated code in the Code Editor tab or see it in action in the Live Preview tab## Web Search FeatureThe web search feature uses Tavily to provide real-time information when generating code. To enable this feature:8 unmodified lines9101112131415161712 unmodified lines3031323334353634 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251268 unmodified linespinned: falsedisable_embedding: truehf_oauth: truehf_oauth_scopes:- read- write---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12 unmodified lines- **Web Search Integration**: Enable real-time web search to get the latest information and best practices- **Chat History**: Keep track of your conversations and generated code- **Quick Examples**: Pre-built examples to get you started quickly- **π One-Click Deployment**: Deploy your generated applications directly to Hugging Face Spaces## Installation34 unmodified lines6. View the generated code in the Code Editor tab or see it in action in the Live Preview tab7. **Deploy to Space**: Enter a title and click "π Deploy to Space" to publish your application## π Deployment FeatureAnyCoder now includes one-click deployment to Hugging Face Spaces! This feature allows you to:### 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 namespace- You can manage and update your spaces from your Hugging Face dashboard- Each deployment gets a unique URL under your username**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 template- **Responsive Design**: Mobile-friendly layout with modern styling- **Project Documentation**: README with project details and prompts used- **Live URL**: Publicly accessible URL that anyone can visit### Deployment Benefits- **Instant Publishing**: No need to set up hosting or domains- **Shareable**: Get a public URL to share with others- **Professional**: Clean, branded presentation of your work- **Version Control**: Each deployment creates a new space with timestamp- **Free Hosting**: Hosted on Hugging Face's infrastructure### Example Deployment```Title: "My Weather Dashboard"Generated Code: <div>Weather app HTML...</div>Result: https://huggingface.co/spaces/my-weather-dashboard-1234567890```The deployed space will include:- Your application with professional styling- A header with your title and AnyCoder branding- A footer with attribution- A README documenting the project## Web Search FeatureThe web search feature uses Tavily to provide real-time information when generating code. To enable this feature:
13 unmodified lines141516171819202122136 unmodified lines1591601611621631641651661671681691701714 unmodified lines176177178179180181182183723 unmodified lines90790890991091191240 unmodified lines95395495595695795853 unmodified lines1012101310141015101610175 unmodified lines10231024102510261027102813 unmodified linesfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoupimport html2textimport gradio as grfrom huggingface_hub import InferenceClientfrom tavily import TavilyClient# Configuration136 unmodified lines]# HF Inference ClientYOUR_API_TOKEN = os.getenv('HF_TOKEN')client = InferenceClient(provider="auto",api_key=YOUR_API_TOKEN,bill_to="huggingface")# Tavily Search ClientTAVILY_API_KEY = os.getenv('TAVILY_API_KEY')tavily_client = None4 unmodified linesprint(f"Failed to initialize Tavily client: {e}")tavily_client = NoneHistory = List[Tuple[str, str]]Messages = List[Dict[str, str]]def history_to_messages(history: History, system: str) -> Messages:messages = [{'role': 'system', 'content': system}]723 unmodified linesgr.Markdown("# AnyCoder")gr.Markdown("*AI-Powered Code Generator*")# Main input sectioninput = gr.Textbox(label="What would you like to build?",40 unmodified lineslabel="Model")# Quick examples (minimal)gr.Markdown("**Quick start**")with gr.Column():53 unmodified lines)with gr.Tab("Preview"):sandbox = gr.HTML(label="Live preview")with gr.Tab("History"):history_output = gr.Chatbot(show_label=False, height=400, type="messages")5 unmodified linesoutputs=[code_output, history, sandbox, history_output])clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])if __name__ == "__main__":demo.queue(default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=True)13 unmodified lines1415161718192021222324136 unmodified lines1611621631641651661671681691701711721731741751761771781791804 unmodified lines185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424723 unmodified lines1148114911501151115211531154115511561157115811591160116140 unmodified lines12021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123153 unmodified lines128512861287128812891290129112921293129412955 unmodified lines1301130213031304130513061307130813091310131113121313131413 unmodified linesfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoupimport html2textimport jsonimport timeimport gradio as grfrom huggingface_hub import InferenceClient, HfApi, create_repofrom tavily import TavilyClient# Configuration136 unmodified lines]# HF Inference ClientHF_TOKEN = os.getenv('HF_TOKEN')client = InferenceClient(provider="auto",api_key=HF_TOKEN,bill_to="huggingface")# Type definitionsHistory = List[Tuple[str, str]]Messages = List[Dict[str, str]]# HF API Client for deploymenthf_api = HfApi(token=HF_TOKEN)# Tavily Search ClientTAVILY_API_KEY = os.getenv('TAVILY_API_KEY')tavily_client = None4 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:"""Create a Hugging Face Space from generated HTML content"""try:# Use user token if provided, otherwise fall back to server tokenapi_token = user_token if user_token else HF_TOKENif not api_token:return {"success": False,"error": "No Hugging Face token available","message": "Please log in with your Hugging Face account to deploy"}# Create API client with user tokenuser_hf_api = HfApi(token=api_token)# Get the current user's username if not providedif not username:try:user_info = user_hf_api.whoami()username = user_info.get('name', 'user')except Exception as e:print(f"Could not get user info: {e}")return {"success": False,"error": "Invalid or expired token","message": "Please check your Hugging Face token"}# Clean the title for use as repo nameclean_title = re.sub(r'[^a-zA-Z0-9_-]', '-', title.lower())clean_title = re.sub(r'-+', '-', clean_title).strip('-')# Add timestamp to ensure uniquenesstimestamp = int(time.time())repo_name = f"{username}/{clean_title}-{timestamp}"# Create the spacerepo_url = user_hf_api.create_repo(repo_id=repo_name,repo_type="space",space_sdk="static",private=False,exist_ok=False)# Prepare the HTML content with proper structurefull_html = f"""<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{title}</title><style>body {{font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;margin: 0;padding: 20px;background-color: #f5f5f5;}}.container {{max-width: 1200px;margin: 0 auto;background: white;padding: 20px;border-radius: 8px;box-shadow: 0 2px 10px rgba(0,0,0,0.1);}}.header {{text-align: center;margin-bottom: 30px;padding-bottom: 20px;border-bottom: 2px solid #f0f0f0;}}.header h1 {{color: #333;margin: 0;}}.header p {{color: #666;margin: 10px 0 0 0;}}.content {{line-height: 1.6;}}.footer {{margin-top: 40px;padding-top: 20px;border-top: 1px solid #f0f0f0;text-align: center;color: #666;font-size: 14px;}}</style></head><body><div class="container"><div class="header"><h1>{title}</h1><p>Generated with AnyCoder - AI Code Generator</p></div><div class="content">{html_content}</div><div class="footer"><p>Created with β€οΈ using AnyCoder</p></div></div></body></html>"""# 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 inforeadme_content = f"""# {title}This project was generated using [AnyCoder](https://huggingface.co/spaces/ahsenkhaliq/anycoder), an AI-powered code generator.## AboutThis is a static HTML application created by describing the requirements in plain English to an AI model.## Generated Prompts{f"".join([f"- {prompt}\n" for prompt in (prompts or [])])}## View LiveVisit: https://huggingface.co/spaces/{repo_name}---*Generated with β€οΈ using AnyCoder*"""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,"space_url": f"https://huggingface.co/spaces/{repo_name}","repo_name": repo_name,"message": f"Successfully created space: {title}"}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:"""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:return """β **Authentication Required**To deploy your application, you need to be logged in with your Hugging Face account.**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:**- Deployments are created under your own Hugging Face account- You need write permissions to create spaces- This ensures you own and can manage your deployed applications---*Please log in and try again.*"""# Get user information from OAuth profileusername = oauth_profile.nameuser_token = oauth_token.token# Extract prompts from historyprompts = []for user_msg, _ in history:if 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)if result["success"]:return f"""β **Successfully deployed!****Space URL:** {result['space_url']}Your application is now live on Hugging Face Spaces under your account. You can share this URL with others to showcase your generated application.**What's next:**- Visit the space to see your application in action- Share the URL with friends and colleagues- Make modifications and redeploy as needed- Manage your space from your Hugging Face dashboard---*Generated with β€οΈ using AnyCoder*"""else:return f"""β **Deployment failed****Error:** {result['error']}**Possible solutions:**- Ensure you have write access to create spaces on your account- Try a different title (avoid special characters)- Check your internet connection- 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}]723 unmodified linesgr.Markdown("# AnyCoder")gr.Markdown("*AI-Powered Code Generator*")# Login button at the toplogin_btn = gr.LoginButton(value="Sign in with Hugging Face",logout_value="Logout ({})",variant="huggingface",size="sm")# Main input sectioninput = gr.Textbox(label="What would you like to build?",40 unmodified lineslabel="Model")# Deployment sectiongr.Markdown("---")gr.Markdown("**π Deploy to Space**")# Space title inputspace_title_input = gr.Textbox(label="Space title",placeholder="My Awesome App",lines=1)# Deploy buttondeploy_btn = gr.Button("π Deploy to Space",variant="primary",size="lg")# Deployment statusdeploy_status = gr.Markdown(value="",visible=False)# Quick examples (minimal)gr.Markdown("**Quick start**")with gr.Column():53 unmodified lines)with gr.Tab("Preview"):sandbox = 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"):history_output = gr.Chatbot(show_label=False, height=400, type="messages")5 unmodified linesoutputs=[code_output, history, sandbox, history_output])clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])# Deployment event handlerdeploy_btn.click(deploy_to_space,inputs=[space_title_input, code_output, history],outputs=[deploy_output],api_name="deploy")if __name__ == "__main__":demo.queue(default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=True)
README.md+54
app.py+291-5