Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456724 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788895 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321333 unmodified lines13713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018112 unmodified lines194195196197198199200201202203204205206207import gradio as grfrom huggingface_hub import InferenceClientimport osimport re # Import regex for potential cleaning, although prompt is the primary fix# --- Configuration ---API_TOKEN = os.getenv("HF_TOKEN", None)24 unmodified lines):"""Generates website code based on user prompt and choices.Yields the code token by token for live updates.Strives to output ONLY raw code."""print(f"--- Generating Code ---")print(f"Prompt: {prompt[:100]}...")print(f"Backend Context: {backend_choice}")print(f"File Structure: {file_structure}") # Crucial inputprint(f"Settings: Max Tokens={max_tokens}, Temp={temperature}, Top-P={top_p}")# --- Dynamically Build System Message Based on File Structure ---# Define specific instructions based on the user's choiceif file_structure == "Single File":file_structure_instruction = ("- **File Structure is 'Single File':** Generate ONLY a single, complete `index.html` file. ""Embed ALL CSS directly within `<style>` tags inside the `<head>`. ""Embed ALL necessary JavaScript directly within `<script>` tags just before the closing `</body>` tag. ""Do NOT use markers like `<!-- index.html -->` or `/* style.css */`.")else: # Multiple Filesfile_structure_instruction = ("- **File Structure is 'Multiple Files':** Generate code for `index.html`, `style.css`, and `script.js` (if JS is needed). ""Use these EXACT markers to separate the files:\n"" `<!-- index.html -->`\n"" `/* style.css */`\n"" `// script.js` (ONLY include this marker and the JS code if JavaScript is necessary for the requested functionality).\n""- Place the corresponding code directly after each marker.\n""- Inside the `index.html` code block, ensure you correctly link the CSS (`<link rel='stylesheet' href='style.css'>`) in the `<head>`.\n""- Inside the `index.html` code block, ensure you correctly include the JS (`<script src='script.js'></script>`) just before the closing `</body>` tag *if* the `// script.js` marker and code are present.")# Assemble the full system message with the dynamic instruction# Emphasize constraints VERY stronglysystem_message = ("You are an expert frontend web developer AI. Your SOLE task is to generate RAW SOURCE CODE (HTML, CSS, JavaScript) based on the user's request and selected options. ""You MUST follow ALL these rules ABSOLUTELY:\n""1. **RAW CODE ONLY:** Your *entire* response MUST consist *only* of the requested code. NO extra text, NO explanations, NO apologies, NO introductions (like 'Here is the code...', 'Okay, here is the code...'), NO summaries, NO comments about the code (unless it's a standard code comment like `<!-- comment -->`), and ABSOLUTELY NO MARKDOWN FORMATTING like ```html, ```css, ```javascript, or ```.\n""2. **IMMEDIATE CODE START:** The response MUST begin *directly* with the first character of the code (e.g., `<!DOCTYPE html>` or `<!-- index.html -->`). NO leading spaces or lines.\n""3. **MANDATORY `index.html`:** Always generate the content for `index.html`.\n"f"4. **FILE STRUCTURE ({file_structure}):** Strictly follow ONLY the instructions for the *selected* file structure below:\n"f" {file_structure_instruction}\n" # Insert the specific instruction here"5. **BACKEND CONTEXT ({backend_choice}):** Use this as a hint for frontend structure (e.g., placeholders like `{{ variable }}` if 'Flask' is chosen), but ONLY generate the static frontend code (HTML, CSS, client-side JS).\n""6. **FRONTEND ONLY:** Do NOT generate server-side code (Python, Node.js, etc.).\n""7. **ACCURACY:** Generate functional code that directly addresses the user's prompt.\n\n""REMEMBER: ONLY CODE. NO OTHER TEXT. START IMMEDIATELY WITH CODE." # Final reinforcement)# --- Construct the messages for the API ---messages = [{"role": "system", "content": system_message},# Make user prompt clearer{"role": "user", "content": f"Generate the website frontend code based on this description: {prompt}"}]# --- Stream the response from the API ---5 unmodified linesmessages=messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):token = message.choices[0].delta.contentif isinstance(token, str):response_stream += tokenfull_response_for_cleaning += token # Keep a separate copy for potential final cleaningyield response_stream # Yield the cumulative response for live updateprint(f"API stream finished. Raw length: {len(full_response_for_cleaning)}")# --- Basic Post-Processing (Attempt to remove backticks if prompt fails) ---# While the prompt *should* handle this, add a safety net.cleaned_response = full_response_for_cleaning.strip()# Remove potential leading/trailing markdown code fences more robustly# Matches ``` followed by optional language identifier and newline, or just ```cleaned_response = re.sub(r"^\s*```[a-z]*\s*\n?", "", cleaned_response)cleaned_response = re.sub(r"\n?\s*```\s*$", "", cleaned_response)# Also remove common introductory phrases if they slip through (less likely with strong prompt)common_intros = ["Here is the code:", "Okay, here is the code:", "Here's the code:","```html", "```css", "```javascript" # Also catch these if regex missed them]for intro in common_intros:if cleaned_response.lower().startswith(intro.lower()):cleaned_response = cleaned_response[len(intro):].lstrip()# Yield the final potentially cleaned response *once* after streaming is done# This replaces the last yielded value from the loop if cleaning occurredyield cleaned_response.strip() # Ensure no trailing whitespace after cleaningexcept Exception as e:error_message = f"An error occurred during the API call: {e}"3 unmodified lines# --- Build Gradio Interface using Blocks ---with gr.Blocks(css=".gradio-container { max-width: 90% !important; }") as demo:gr.Markdown("# Website Code Generator 🚀")gr.Markdown("Describe the website, choose options, and get ONLY the raw frontend code. ""Code appears live below. **Select 'Single File' or 'Multiple Files' carefully.**")with gr.Row():with gr.Column(scale=2):prompt_input = gr.Textbox(label="Website Description",placeholder="e.g., A simple landing page with a navbar, hero section, and footer.",lines=5,)backend_radio = gr.Radio(["Static", "Flask", "Node.js"],label="Backend Context Hint",value="Static",info="Hint for AI (e.g., template placeholders) - generates ONLY frontend code.",)file_structure_radio = gr.Radio(["Multiple Files", "Single File"], # Default: Multiplelabel="Output File Structure",value="Multiple Files",info="Choose 'Single File' for everything in index.html OR 'Multiple Files' for separate css/js.", # Clarified info)generate_button = gr.Button("Generate Website Code", variant="primary")with gr.Column(scale=3):code_output = gr.Code(label="Generated Code (Raw Output)", # Updated labellanguage="html",lines=28,interactive=False,)with gr.Accordion("Advanced Generation Settings", open=False):max_tokens_slider = gr.Slider(minimum=512, maximum=4096, value=2048, step=128, label="Max New Tokens")temperature_slider = gr.Slider(minimum=0.1, maximum=1.2, value=0.6, step=0.1, label="Temperature")top_p_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-P")# --- Connect Inputs/Outputs ---generate_button.click(12 unmodified lines# --- Examples ---gr.Examples(examples=[["A simple counter page with a number display, an increment button, and a decrement button. Use Javascript for the logic.", "Static", "Single File"],["A login form with fields for username and password, and a submit button. Basic styling.", "Static", "Multiple Files"],["Product cards display grid. Each card shows an image, product name, price, and an 'Add to Cart' button. Make it responsive.", "Static", "Multiple Files"],["A personal blog homepage with a header, a list of recent posts (just placeholders), and a sidebar with categories.", "Flask", "Multiple Files"],["A very basic HTML page with just a title 'My App' and a heading 'Welcome'. No CSS or JS.", "Static", "Single File"]],inputs=[prompt_input, backend_radio, file_structure_radio],label="Example Prompts")# --- Launch ---123456724 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283845 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311323 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518612 unmodified lines199200201202203204205206207208209210211import gradio as grfrom huggingface_hub import InferenceClientimport osimport re # For post-processing fallback# --- Configuration ---API_TOKEN = os.getenv("HF_TOKEN", None)24 unmodified lines):"""Generates website code based on user prompt and choices.Aims for richer CSS and strictly outputs ONLY raw code.Yields the code token by token for live updates."""print(f"--- Generating Code ---")print(f"Prompt: {prompt[:100]}...")print(f"Backend Context: {backend_choice}")print(f"File Structure: {file_structure}")print(f"Settings: Max Tokens={max_tokens}, Temp={temperature}, Top-P={top_p}")# --- Dynamically Build System Message Based on File Structure & Style Request ---if file_structure == "Single File":file_structure_instruction = ("- **File Structure is 'Single File':** Generate ONLY a single, complete `index.html` file. ""Embed ALL CSS directly within `<style>` tags inside the `<head>`. ""Embed ALL necessary JavaScript directly within `<script>` tags just before the closing `</body>` tag. ""Do NOT use file separation markers.")else: # Multiple Filesfile_structure_instruction = ("- **File Structure is 'Multiple Files':** Generate code for `index.html`, `style.css`, and `script.js` (if JS is needed). ""Use these EXACT markers: `<!-- index.html -->`, `/* style.css */`, `// script.js` (only if JS is needed).\n""- Place the corresponding code directly after each marker.\n""- Inside `index.html`, link `style.css` in the `<head>` and include `script.js` before `</body>` if generated.")# Assemble the full system message with enhanced style guidance and stricter output rulessystem_message = ("You are an expert frontend web developer AI. Your primary goal is to generate **visually appealing, modern, and well-styled** frontend code (HTML, CSS, client-side JS) based *only* on the user's description and selected options. ""Follow ALL these rules with EXTREME STRICTNESS:\n""1. **STYLE & DETAIL:** Generate rich, detailed code. Don't just make minimal examples. Use **plenty of CSS** for layout (Flexbox/Grid), spacing (padding/margin), typography (fonts), colors, and consider adding subtle transitions or effects for a polished look. Aim for a high-quality visual result.\n""2. **RAW CODE ONLY:** Your *entire* response MUST consist *only* of the requested source code. NO extra text, NO explanations, NO apologies, NO introductions ('Here is the code...'), NO summaries, NO comments about the code (except standard code comments), NO MARKDOWN formatting (like ```html), and ***ABSOLUTELY NO CONVERSATIONAL TEXT OR TAGS*** like `<|user|>` or `<|assistant|>` before, during, or after the code.\n""3. **IMMEDIATE CODE START:** The response MUST begin *directly* with the first character of the code (e.g., `<!DOCTYPE html>` or `<!-- index.html -->`). NO leading spaces, newlines, or any other characters.\n""4. **IMMEDIATE CODE END:** The response MUST end *immediately* after the very last character of the generated code (e.g., the final `</html>`, `}`, or `;`). DO NOT add *any* text, spaces, or newlines after the code concludes.\n""5. **MANDATORY `index.html`:** Always generate the content for `index.html`.\n"f"6. **FILE STRUCTURE ({file_structure}):** Strictly follow ONLY the instructions for the *selected* file structure below:\n"f" {file_structure_instruction}\n" # Insert the specific instruction here"7. **BACKEND CONTEXT ({backend_choice}):** Use this as a hint for frontend structure (e.g., placeholders like `{{ variable }}` if 'Flask' is chosen), but ONLY generate the static frontend code (HTML, CSS, client-side JS).\n""8. **FRONTEND ONLY:** Do NOT generate server-side code (Python, Node.js, etc.).\n""9. **ACCURACY:** Generate functional code that directly addresses the user's prompt.\n\n""REMEMBER: Create visually appealing code. Output ONLY the raw code. START immediately with code. END immediately with code. NO extra text or tags EVER." # Final reinforcement)# --- Construct the messages for the API ---messages = [{"role": "system", "content": system_message},{"role": "user", "content": f"Generate the website frontend code for: {prompt}"} # Slightly rephrased user message]# --- Stream the response from the API ---5 unmodified linesmessages=messages,max_tokens=max_tokens,stream=True,temperature=temperature, # User controlled - 0.7 is a reasonable default balancetop_p=top_p,):token = message.choices[0].delta.contentif isinstance(token, str):response_stream += tokenfull_response_for_cleaning += tokenyield response_stream # Yield cumulative response for live updateprint(f"API stream finished. Raw length: {len(full_response_for_cleaning)}")# --- Post-Processing (Fallback Safety Net) ---# Primarily rely on the prompt, but clean common issues just in case.cleaned_response = full_response_for_cleaning.strip()# Remove potential leading/trailing markdown code fencescleaned_response = re.sub(r"^\s*```[a-z]*\s*\n?", "", cleaned_response)cleaned_response = re.sub(r"\n?\s*```\s*$", "", cleaned_response)# Remove potential conversational tags if they slip through (less likely now)cleaned_response = re.sub(r"<\s*\|?\s*(user|assistant)\s*\|?\s*>", "", cleaned_response, flags=re.IGNORECASE)# Remove common introductory/closing phrases if they slip throughcommon_phrases = ["Here is the code:", "Okay, here is the code:", "Here's the code:","Sure, here is the code you requested:", "Let me know if you need anything else."# Add more if needed]temp_response = cleaned_response.lower()for phrase in common_phrases:if temp_response.startswith(phrase.lower()):cleaned_response = cleaned_response[len(phrase):].lstrip()if temp_response.endswith(phrase.lower()):cleaned_response = cleaned_response[:-len(phrase)].rstrip()# Yield the final cleaned response *once* after streaming.yield cleaned_response.strip()except Exception as e:error_message = f"An error occurred during the API call: {e}"3 unmodified lines# --- Build Gradio Interface using Blocks ---with gr.Blocks(css=".gradio-container { max-width: 90% !important; }") as demo:gr.Markdown("# ✨ Website Code Generator ✨") # Added some flairgr.Markdown("Describe the website you want. The AI will generate **visually styled** frontend code (HTML, CSS, JS) using **plenty of CSS**. ""The code appears live below. \n""**Important:** This generator creates code based *only* on your initial description. To refine the output, modify your description and generate again." # Added clarification)with gr.Row():with gr.Column(scale=2):prompt_input = gr.Textbox(label="Website Description",placeholder="e.g., A modern portfolio landing page with a smooth scroll navigation, a stylish hero section, project cards with hover effects, and a contact form.", # More ambitious placeholderlines=6, # Slightly more lines)backend_radio = gr.Radio(["Static", "Flask", "Node.js"], label="Backend Context Hint", value="Static",info="Hint for AI (e.g., template placeholders) - generates ONLY frontend code.")file_structure_radio = gr.Radio(["Multiple Files", "Single File"], label="Output File Structure", value="Multiple Files",info="Choose 'Single File' (all in index.html) or 'Multiple Files' (separate css/js).")generate_button = gr.Button("🎨 Generate Stylish Website Code", variant="primary") # Updated button textwith gr.Column(scale=3):code_output = gr.Code(label="Generated Code (Raw Output - Aiming for Style!)", # Updated labellanguage="html",lines=30, # More lines for potentially longer codeinteractive=False,)with gr.Accordion("Advanced Generation Settings", open=False):max_tokens_slider = gr.Slider(minimum=512, maximum=4096, value=2560, step=128, label="Max New Tokens", # Increased defaultinfo="Max length of generated code. Increase for complex pages.")temperature_slider = gr.Slider(minimum=0.1, maximum=1.2, value=0.7, step=0.1, label="Temperature", # Default 0.7 is often goodinfo="Controls randomness. Lower=more predictable, Higher=more creative.")top_p_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="Top-P",info="Alternative randomness control.")# --- Connect Inputs/Outputs ---generate_button.click(12 unmodified lines# --- Examples ---gr.Examples(examples=[["A simple counter page with a number display, an increment button, and a decrement button. Style the buttons nicely and center everything.", "Static", "Single File"],["A responsive product grid for an e-commerce site. Each card needs an image, title, price, and 'Add to Cart' button with a hover effect. Use modern CSS.", "Static", "Multiple Files"],["A personal blog homepage featuring a clean header with navigation, a main content area for post summaries (placeholders ok), and a simple footer. Use a nice font.", "Flask", "Multiple Files"],["A 'Coming Soon' page with a large countdown timer (use JS), a background image, and an email signup form. Make it look sleek.", "Static", "Multiple Files"]],inputs=[prompt_input, backend_radio, file_structure_radio],label="Example Prompts (Aiming for Style)" # Updated label)# --- Launch ---
app.py+72-68