update to add deploy
Browse files8 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
## Installation
34 unmodified lines
6. View the generated code in the Code Editor tab or see it in action in the Live Preview tab
7. **Deploy to Space**: Enter a title and click "π Deploy to Space" to publish your application
## π Deployment Feature
AnyCoder now includes one-click deployment to Hugging Face Spaces! This feature allows you to:
### How to Deploy
1. **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 Feature
The web search feature uses Tavily to provide real-time information when generating code. To enable this feature:13 unmodified lines141516171819201921222324136 unmodified lines1611621631621641651661651671681691701711721731741751761771781791804 unmodified lines185186187179180188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424723 unmodified lines1148114911501151115211531154115511561157115811591160116140 unmodified lines12021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123153 unmodified lines128512861287128812891290129112921293129412955 unmodified lines1301130213031304130513061307130813091310131113121313131413 unmodified linesfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoupimport html2textimport jsonimport time
import gradio as grfrom huggingface_hub import InferenceClientfrom huggingface_hub import InferenceClient, HfApi, create_repofrom tavily import TavilyClient
# Configuration136 unmodified lines]
# HF Inference ClientYOUR_API_TOKEN = os.getenv('HF_TOKEN')HF_TOKEN = os.getenv('HF_TOKEN')client = InferenceClient( provider="auto", api_key=YOUR_API_TOKEN, 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 lines print(f"Failed to initialize Tavily client: {e}") tavily_client = None
History = List[Tuple[str, str]]Messages = List[Dict[str, str]]# 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 token api_token = user_token if user_token else HF_TOKEN if 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 token user_hf_api = HfApi(token=api_token) # Get the current user's username if not provided if 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 name clean_title = re.sub(r'[^a-zA-Z0-9_-]', '-', title.lower()) clean_title = re.sub(r'-+', '-', clean_title).strip('-') # Add timestamp to ensure uniqueness timestamp = int(time.time()) repo_name = f"{username}/{clean_title}-{timestamp}" # Create the space repo_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 structure full_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 file 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" ) # Create README.md with project info readme_content = f"""# {title}
This project was generated using [AnyCoder](https://huggingface.co/spaces/ahsenkhaliq/anycoder), an AI-powered code generator.
## About
This 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 Live
Visit: 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 authenticated if 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 profile username = oauth_profile.name user_token = oauth_token.token # Extract prompts from history prompts = [] 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 account result = 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 lines gr.Markdown("# AnyCoder") gr.Markdown("*AI-Powered Code Generator*") # Login button at the top login_btn = gr.LoginButton( value="Sign in with Hugging Face", logout_value="Logout ({})", variant="huggingface", size="sm" ) # Main input section input = gr.Textbox( label="What would you like to build?",40 unmodified lines label="Model" ) # Deployment section gr.Markdown("---") gr.Markdown("**π Deploy to Space**") # Space title input space_title_input = gr.Textbox( label="Space title", placeholder="My Awesome App", lines=1 ) # Deploy button deploy_btn = gr.Button( "π Deploy to Space", variant="primary", size="lg" ) # Deployment status deploy_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 lines outputs=[code_output, history, sandbox, history_output] ) clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input]) # Deployment event handler deploy_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