website design feature
Browse filesFiles changed (3)
- README.md+56
- app.py+238-62
- requirements.txt+4-1
21 unmodified lines22232425262765 unmodified lines93949596979821 unmodified lines- **Multi-Model Support**: Choose from various AI models including DeepSeek, ERNIE-4.5-VL, MiniMax, and Qwen- **Image-to-Code**: Upload UI design images and get corresponding HTML/CSS code (ERNIE-4.5-VL model)- **Image Text Extraction**: Upload images and extract text using OCR for processing- **Live Preview**: See your generated code in action with the built-in sandbox- **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 code65 unmodified lines- The application will extract the text and include it in your prompt- You can then ask the AI to process, summarize, or work with the extracted text## Available Models- **DeepSeek V3**: Advanced code generation model21 unmodified lines2223242526272865 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315421 unmodified lines- **Multi-Model Support**: Choose from various AI models including DeepSeek, ERNIE-4.5-VL, MiniMax, and Qwen- **Image-to-Code**: Upload UI design images and get corresponding HTML/CSS code (ERNIE-4.5-VL model)- **Image Text Extraction**: Upload images and extract text using OCR for processing- **Website Redesign**: Enter a website URL to extract content and redesign it with modern, responsive layouts- **Live Preview**: See your generated code in action with the built-in sandbox- **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 code65 unmodified lines- The application will extract the text and include it in your prompt- You can then ask the AI to process, summarize, or work with the extracted text## Website Redesign FeatureThe website redesign feature allows you to extract content from existing websites and generate modern, responsive redesigns. This feature:1. **Extracts Website Content**: Automatically scrapes the target website to extract:- Page title and meta description- Navigation menu structure- Main content sections- Images and their descriptions- Overall page structure and purpose2. **Generates Modern Redesigns**: Creates improved versions with:- Modern, responsive layouts- Enhanced user experience- Better accessibility- Mobile-first design principles- Current design trends and best practices### How to Use Website Redesign1. **Enter a Website URL**: In the "🌐 Website URL (for redesign)" field, enter the URL of the website you want to redesign- Example: `https://example.com`- The URL can be with or without `https://`2. **Add Custom Requirements**: Optionally describe specific improvements you want:- "Make it more modern and minimalist"- "Add a dark mode toggle"- "Improve the mobile layout"- "Use a different color scheme"3. **Enable Web Search**: Toggle the web search feature to get the latest design trends and best practices4. **Generate**: Click "Generate" to create your redesigned website### Example Usage```URL: https://example.comDescription: Redesign this website with a modern, minimalist approach. Use a clean typography and improve the mobile experience.```The AI will analyze the original website content and create a completely redesigned version that maintains the core functionality while providing a better user experience.### Supported WebsitesThe feature works with most public websites, including:- Business websites- Portfolio sites- Blog platforms- E-commerce sites- Landing pages- Documentation sites**Note**: Some websites may block automated access or require JavaScript to load content. In such cases, the extraction may be limited.## Available Models- **DeepSeek V3**: Advanced code generation model
9 unmodified lines1011121314158 unmodified lines24252627282910 unmodified lines40414243444578 unmodified lines12412512612712812988 unmodified lines218219220221222223224213 unmodified lines43843944044144244344411 unmodified lines45645745845946046116 unmodified lines4784794804814824834844 unmodified lines4894904914924934944954964974984995005015025035045055065072 unmodified lines5105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156169 unmodified linesimport numpy as npfrom PIL import Imageimport pytesseractimport gradio as grfrom huggingface_hub import InferenceClient8 unmodified lines4. Include necessary comments and documentation5. Ensure the code is functional and follows best practicesIf an image is provided, analyze it and use the visual information to better understand the user's requirements.Always respond with code that can be executed or rendered directly.10 unmodified lines5. Include necessary comments and documentation6. Ensure the code is functional and follows best practicesIf an image is provided, analyze it and use the visual information to better understand the user's requirements.Always respond with code that can be executed or rendered directly.78 unmodified lines{"title": "Extract Text from Image","description": "Upload an image containing text and I'll extract and process the text content"}]88 unmodified linesreturn gr.update(visible=True), historydef clear_history():return [], [] # Empty lists for both tuple format and chatbot messagesdef update_image_input_visibility(model):"""Update image input visibility based on selected model"""213 unmodified linesexcept Exception as e:return f"Error extracting text: {e}"def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False):if query is None:query = ''if _history is None:11 unmodified linesfile_text = file_text[:5000] # Limit to 5000 chars for prompt sizequery = f"{query}\n\n[Reference file content below]\n{file_text}"# Enhance query with search if enabledenhanced_query = enhance_query_with_search(query, enable_search)16 unmodified linessearch_status = " (with web search)" if enable_search and tavily_client else ""yield {code_output: clean_code,status_indicator: f'<div class="status-indicator generating" id="status">Generating code{search_status}...</div>',history_output: history_to_chatbot_messages(_history),}_history = messages_to_history(messages + [{4 unmodified linescode_output: remove_code_block(content),history: _history,sandbox: send_to_sandbox(remove_code_block(content)),status_indicator: '<div class="status-indicator success" id="status">Code generated successfully!</div>',history_output: history_to_chatbot_messages(_history),}except Exception as e:error_message = f"Error: {str(e)}"yield {code_output: error_message,status_indicator: '<div class="status-indicator error" id="status">Error generating code</div>',history_output: history_to_chatbot_messages(_history),}# Main applicationwith gr.Blocks(theme=gr.themes.Base(), title="AnyCoder - AI Code Generator") as demo:history = gr.State([])setting = gr.State({"system": SystemPrompt,2 unmodified linesopen_panel = gr.State(None)with gr.Sidebar():gr.Markdown("# AnyCoder\nAI-Powered Code Generator")gr.Markdown("""Describe your app or UI in plain English. Optionally upload a UI image (for ERNIE model). Click Generate to get code and preview.""")gr.Markdown("**Tip:** For best search results about people or entities, include details like profession, company, or location. Example: 'John Smith software engineer at Google.'")gr.Markdown("**Tip:** You can attach a file (PDF, TXT, DOCX, CSV, MD, Images) to use as reference for your prompt, e.g. 'Summarize this PDF' or 'Extract text from this image'.")input = gr.Textbox(label="Describe your application",placeholder="e.g., Create a todo app with add, delete, and mark as complete functionality",lines=2)image_input = gr.Image(label="Upload UI design image (ERNIE-4.5-VL only)",visible=False)file_input = gr.File(label="Attach a file (PDF, TXT, DOCX, CSV, MD, Images)",file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"],visible=True)with gr.Row():btn = gr.Button("Generate", variant="primary", size="sm")clear_btn = gr.Button("Clear", variant="secondary", size="sm")# Search togglesearch_toggle = gr.Checkbox(label="🔍 Enable Web Search",value=False,info="Enable real-time web search to get the latest information and best practices")# Search status indicatorif not tavily_client:gr.Markdown("⚠️ **Web Search Unavailable**: Set `TAVILY_API_KEY` environment variable to enable search")else:gr.Markdown("✅ **Web Search Available**: Toggle above to enable real-time search")gr.Markdown("📷 **Image Text Extraction**: Upload images to extract text using OCR (requires Tesseract installation)")gr.Markdown("### Quick Examples")for i, demo_item in enumerate(DEMO_LIST[:5]):demo_card = gr.Button(value=demo_item['title'],variant="secondary",size="sm")demo_card.click(fn=lambda idx=i: gr.update(value=DEMO_LIST[idx]['description']),outputs=input)gr.Markdown("---")model_dropdown = gr.Dropdown(choices=[model['name'] for model in AVAILABLE_MODELS],value=AVAILABLE_MODELS[0]['name'],label="Select Model")def on_model_change(model_name):for m in AVAILABLE_MODELS:if m['name'] == model_name:return m, f"**Model:** {m['name']}", update_image_input_visibility(m)return AVAILABLE_MODELS[0], f"**Model:** {AVAILABLE_MODELS[0]['name']}", update_image_input_visibility(AVAILABLE_MODELS[0])model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}")model_dropdown.change(on_model_change,inputs=model_dropdown,outputs=[current_model, model_display, image_input])with gr.Accordion("System Prompt", open=False):systemPromptInput = gr.Textbox(value=SystemPrompt,label="System Prompt",lines=10)save_prompt_btn = gr.Button("Save", variant="primary")def save_prompt(input):return {setting: {"system": input}}save_prompt_btn.click(save_prompt, inputs=systemPromptInput, outputs=setting)with gr.Column():model_displaywith gr.Tabs():with gr.Tab("Code Editor"):code_output = gr.Code(language="html",lines=25,interactive=False,label="Generated Code")with gr.Tab("Live Preview"):sandbox = gr.HTML(label="Live Preview")with gr.Tab("History"):history_output = gr.Chatbot(show_label=False, height=400, type="messages")status_indicator = gr.Markdown('Ready to generate code',)# Event handlersbtn.click(generation_code,inputs=[input, image_input, file_input, setting, history, current_model, search_toggle],outputs=[code_output, history, sandbox, status_indicator, history_output])clear_btn.click(clear_history, outputs=[history, history_output, file_input])if __name__ == "__main__":demo.queue(default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=True)9 unmodified lines101112131415161718198 unmodified lines2829303132333435363738394010 unmodified lines515253545556575859606162636478 unmodified lines14314414514614714814915015115288 unmodified lines241242243244245246247213 unmodified lines46146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258311 unmodified lines59559659759859960060160260360460560660760860961016 unmodified lines6276286296306316324 unmodified lines6376386396406416426436446456466476486496506516526536546556566576586596606616626636646652 unmodified lines6686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917929 unmodified linesimport numpy as npfrom PIL import Imageimport pytesseractimport requestsfrom urllib.parse import urlparse, urljoinfrom bs4 import BeautifulSoupimport html2textimport gradio as grfrom huggingface_hub import InferenceClient8 unmodified lines4. Include necessary comments and documentation5. Ensure the code is functional and follows best practicesFor website redesign tasks:- Analyze the extracted website content to understand the structure and purpose- Create a modern, responsive design that improves upon the original- Maintain the core functionality and content while enhancing the user experience- Use modern CSS frameworks and design patterns- Ensure accessibility and mobile responsivenessIf an image is provided, analyze it and use the visual information to better understand the user's requirements.Always respond with code that can be executed or rendered directly.10 unmodified lines5. Include necessary comments and documentation6. Ensure the code is functional and follows best practicesFor website redesign tasks:- Analyze the extracted website content to understand the structure and purpose- Use web search to find current design trends and best practices for the specific type of website- Create a modern, responsive design that improves upon the original- Maintain the core functionality and content while enhancing the user experience- Use modern CSS frameworks and design patterns- Ensure accessibility and mobile responsivenessIf an image is provided, analyze it and use the visual information to better understand the user's requirements.Always respond with code that can be executed or rendered directly.78 unmodified lines{"title": "Extract Text from Image","description": "Upload an image containing text and I'll extract and process the text content"},{"title": "Website Redesign","description": "Enter a website URL to extract its content and redesign it with a modern, responsive layout"}]88 unmodified linesreturn gr.update(visible=True), historydef 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"""213 unmodified linesexcept Exception as e:return f"Error extracting text: {e}"def extract_website_content(url: str) -> str:"""Extract content from a website URL"""try:# Validate URLparsed_url = urlparse(url)if not parsed_url.scheme:url = "https://" + urlparsed_url = urlparse(url)if not parsed_url.netloc:return "Error: Invalid URL provided"# Set headers to mimic a browser requestheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'}# Make the requestresponse = requests.get(url, headers=headers, timeout=10)response.raise_for_status()# Parse HTML contentsoup = BeautifulSoup(response.content, 'html.parser')# Remove script and style elementsfor script in soup(["script", "style"]):script.decompose()# Extract titletitle = soup.find('title')title_text = title.get_text().strip() if title else "No title found"# Extract meta descriptionmeta_desc = soup.find('meta', attrs={'name': 'description'})description = meta_desc.get('content', '') if meta_desc else ""# Extract main content areascontent_sections = []# Look for common content containersmain_selectors = ['main', 'article', '.content', '.main-content', '.post-content','#content', '#main', '.entry-content', '.post-body']for selector in main_selectors:elements = soup.select(selector)for element in elements:text = element.get_text().strip()if len(text) > 100: # Only include substantial contentcontent_sections.append(text)# If no main content found, extract from bodyif not content_sections:body = soup.find('body')if body:# Remove navigation, footer, and other non-content elementsfor element in body.find_all(['nav', 'footer', 'header', 'aside']):element.decompose()content_sections.append(body.get_text().strip())# Extract navigation linksnav_links = []nav_elements = soup.find_all(['nav', 'header'])for nav in nav_elements:links = nav.find_all('a')for link in links:link_text = link.get_text().strip()link_href = link.get('href', '')if link_text and link_href:nav_links.append(f"{link_text}: {link_href}")# Extract imagesimages = []img_elements = soup.find_all('img')for img in img_elements:src = img.get('src', '')alt = img.get('alt', '')if src:# Convert relative URLs to absoluteif not src.startswith(('http://', 'https://')):src = urljoin(url, src)images.append(f"Image: {alt} ({src})")# Compile the extracted contentwebsite_content = f"""WEBSITE CONTENT EXTRACTION==========================URL: {url}Title: {title_text}Description: {description}NAVIGATION MENU:{chr(10).join(nav_links[:10]) if nav_links else "No navigation found"}MAIN CONTENT:{chr(10).join(content_sections[:3]) if content_sections else "No main content found"}IMAGES:{chr(10).join(images[:10]) if images else "No images found"}PAGE STRUCTURE:- This appears to be a {title_text.lower()} website- Contains {len(content_sections)} main content sections- Has {len(nav_links)} navigation links- Includes {len(images)} images"""return website_content.strip()except requests.exceptions.RequestException as e:return f"Error accessing website: {str(e)}"except Exception as e:return f"Error extracting website content: {str(e)}"def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], website_url: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False):if query is None:query = ''if _history is None:11 unmodified linesfile_text = file_text[:5000] # Limit to 5000 chars for prompt sizequery = f"{query}\n\n[Reference file content below]\n{file_text}"# Extract website content and append to query if website URL is presentwebsite_text = ""if website_url and website_url.strip():website_text = extract_website_content(website_url.strip())if website_text and not website_text.startswith("Error"):website_text = website_text[:8000] # Limit to 8000 chars for prompt sizequery = f"{query}\n\n[Website content to redesign below]\n{website_text}"elif website_text.startswith("Error"):query = f"{query}\n\n[Error extracting website: {website_text}]"# Enhance query with search if enabledenhanced_query = enhance_query_with_search(query, enable_search)16 unmodified linessearch_status = " (with web search)" if enable_search and tavily_client else ""yield {code_output: clean_code,history_output: history_to_chatbot_messages(_history),}_history = messages_to_history(messages + [{4 unmodified linescode_output: remove_code_block(content),history: _history,sandbox: send_to_sandbox(remove_code_block(content)),history_output: history_to_chatbot_messages(_history),}except Exception as e:error_message = f"Error: {str(e)}"yield {code_output: error_message,history_output: history_to_chatbot_messages(_history),}# Main applicationwith gr.Blocks(theme=gr.themes.Base(primary_hue="blue",secondary_hue="gray",neutral_hue="gray",font=gr.themes.GoogleFont("Inter"),font_mono=gr.themes.GoogleFont("JetBrains Mono"),text_size=gr.themes.sizes.text_md,spacing_size=gr.themes.sizes.spacing_md,radius_size=gr.themes.sizes.radius_md),title="AnyCoder - AI Code Generator") as demo:history = gr.State([])setting = gr.State({"system": SystemPrompt,2 unmodified linesopen_panel = gr.State(None)with gr.Sidebar():gr.Markdown("# AnyCoder")gr.Markdown("*AI-Powered Code Generator*")# Main input sectioninput = gr.Textbox(label="What would you like to build?",placeholder="Describe your application...",lines=3)# URL input for website redesignwebsite_url_input = gr.Textbox(label="Website URL (for redesign)",placeholder="https://example.com",lines=1,visible=True)# File upload (minimal)file_input = gr.File(label="Reference file",file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"],visible=True)# Image input (only for ERNIE model)image_input = gr.Image(label="UI design image",visible=False)# Action buttonswith gr.Row():btn = gr.Button("Generate", variant="primary", size="lg", scale=2)clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1)# Search toggle (minimal)search_toggle = gr.Checkbox(label="🔍 Web search",value=False)# Model selection (minimal)model_dropdown = gr.Dropdown(choices=[model['name'] for model in AVAILABLE_MODELS],value=AVAILABLE_MODELS[0]['name'],label="Model")# Quick examples (minimal)gr.Markdown("**Quick start**")with gr.Column():for i, demo_item in enumerate(DEMO_LIST[:3]):demo_card = gr.Button(value=demo_item['title'],variant="secondary",size="sm")demo_card.click(fn=lambda idx=i: gr.update(value=DEMO_LIST[idx]['description']),outputs=input)# Status indicators (minimal)if not tavily_client:gr.Markdown("⚠️ Web search unavailable")else:gr.Markdown("✅ Web search available")# Hidden elements for functionalitymodel_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=False)def on_model_change(model_name):for m in AVAILABLE_MODELS:if m['name'] == model_name:return m, f"**Model:** {m['name']}", update_image_input_visibility(m)return AVAILABLE_MODELS[0], f"**Model:** {AVAILABLE_MODELS[0]['name']}", update_image_input_visibility(AVAILABLE_MODELS[0])def save_prompt(input):return {setting: {"system": input}}model_dropdown.change(on_model_change,inputs=model_dropdown,outputs=[current_model, model_display, image_input])# System prompt (collapsed by default)with gr.Accordion("Advanced", open=False):systemPromptInput = gr.Textbox(value=SystemPrompt,label="System prompt",lines=5)save_prompt_btn = gr.Button("Save", variant="primary", size="sm")save_prompt_btn.click(save_prompt, inputs=systemPromptInput, outputs=setting)with gr.Column():with gr.Tabs():with gr.Tab("Code"):code_output = gr.Code(language="html",lines=25,interactive=False,label="Generated code")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")# Event handlersbtn.click(generation_code,inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle],outputs=[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)
4 unmodified lines56784 unmodified linespython-docxpytesseractPillowopencv-python4 unmodified lines5678910114 unmodified linespython-docxpytesseractPillowopencv-pythonrequestsbeautifulsoup4html2text
README.md+56
app.py+238-62
requirements.txt+4-1