builder / app.py
mgbam's picture
Update app.py
bfd7197 verified
raw
history blame
6.34 kB
# /app.py
""" Main Gradio application for AnyCoder. """
import gradio as gr
import os
from config import AVAILABLE_MODELS, MULTIMODAL_MODELS, DEMO_LIST
from core import generate_code
from deployment import deploy_to_hf_space
from utils import get_gradio_language, history_to_chatbot_messages
# --- Event Handlers ---
def on_generate_click(query: str, image: gr.Image, file: gr.File, website_url: str, history: list, model_name: str, enable_search: bool, language: str):
if not any([query, image, file, website_url]):
yield {
code_output: gr.update(value="## Please provide a prompt, image, file, or URL.", language="markdown"),
history_output: history_to_chatbot_messages(history)
}
return
model_config = next((m for m in AVAILABLE_MODELS if m['name'] == model_name), AVAILABLE_MODELS[0])
for response in generate_code(query, image, file.name if file else None, website_url, history, model_config, enable_search, language):
ui_update = {code_output: gr.update(value=response.get("code_output"), language=get_gradio_language(language))}
if "history" in response:
ui_update[history_state] = response["history"]
ui_update[history_output] = history_to_chatbot_messages(response["history"])
yield ui_update
def on_deploy_click(code: str, space_name: str, sdk_name: str, request: gr.Request):
hf_token = request.token
if not hf_token: return gr.update(value="⚠️ Please log in with your Hugging Face account to deploy.", visible=True)
sdk = {"Static (HTML)": "static", "Gradio (Python)": "gradio"}.get(sdk_name, "static")
return gr.update(value=deploy_to_hf_space(code, space_name, sdk, hf_token), visible=True)
# <--- FIX: Create a dedicated helper function for the preview logic ---
def update_preview(code: str):
"""Updates the preview pane based on the generated code."""
if code and code.strip():
# Sanitize the code for the iframe's srcdoc attribute
safe_code = code.replace('"', '"')
iframe_html = f'<iframe srcdoc="{safe_code}" width="100%" height="920px" style="border:0;"></iframe>'
return gr.HTML(iframe_html, visible=True), gr.Markdown(visible=False)
else:
# If there's no code, show the placeholder
return gr.HTML(visible=False), gr.Markdown(visible=True)
# --- UI Layout ---
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder AI") as demo:
history_state = gr.State([])
gr.Markdown("# 🚀 AnyCoder AI - Multi-Provider Code Generator")
with gr.Row():
with gr.Column(scale=1):
input_prompt = gr.Textbox(label="Prompt", placeholder="e.g., a login form with a blue button", lines=4)
model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[0]['name'], label="Select Model")
language_dropdown = gr.Dropdown(choices=["html", "python", "javascript", "css", "react"], value="html", label="Language")
website_url_input = gr.Textbox(label="URL to Redesign", placeholder="https://example.com")
with gr.Row():
file_input = gr.File(label="Reference File", scale=2)
image_input = gr.Image(label="UI Image", type="numpy", visible=False, scale=1)
search_toggle = gr.Checkbox(label="Enable Web Search", value=False)
with gr.Row():
clear_btn = gr.Button("Clear")
generate_btn = gr.Button("Generate", variant="primary", scale=2)
gr.Markdown("--- \n**Quick Examples**")
for item in DEMO_LIST: # Display all demos
gr.Button(item['title']).click(lambda d=item['description']: d, outputs=input_prompt)
if os.getenv("SPACE_ID"):
with gr.Accordion("🚀 Deploy to Hugging Face", open=False):
login_button = gr.LoginButton()
space_name_input = gr.Textbox(label="New App Name", placeholder="my-anycoder-app")
sdk_dropdown = gr.Dropdown(choices=["Static (HTML)", "Gradio (Python)"], value="Static (HTML)", label="App Type")
deploy_btn = gr.Button("Deploy")
deploy_status = gr.Markdown(visible=False)
with gr.Column(scale=2):
with gr.Tabs() as tabs:
preview_tab = gr.Tab("Preview")
code_tab = gr.Tab("Code")
history_tab = gr.Tab("History")
with preview_tab:
sandbox = gr.HTML(label="Live Preview", elem_id="sandbox-preview", visible=False)
placeholder = gr.Markdown("### Your live preview will appear here after generation.")
with code_tab:
code_output = gr.Code(label="Generated Code", language="html", interactive=True)
with history_tab:
history_output = gr.Chatbot(label="Conversation History", type="messages", height=600)
# --- Event Wiring ---
model_id = gr.State()
generate_btn.click(on_generate_click,
inputs=[input_prompt, image_input, file_input, website_url_input, history_state, model_dropdown, search_toggle, language_dropdown],
outputs=[code_output, history_state, history_output])
# <--- FIX: Use the new, clean helper function for the change event ---
code_output.change(fn=update_preview, inputs=code_output, outputs=[sandbox, placeholder])
clear_btn.click(lambda: ([], [], None, None, None, "", "", None, gr.HTML(visible=False), gr.Markdown(visible=True)),
outputs=[history_state, history_output, input_prompt, image_input, file_input, website_url_input, code_output, model_id, sandbox, placeholder])
def on_model_change(model_name):
mid = next((m['id'] for m in AVAILABLE_MODELS if m['name'] == model_name), None)
is_multimodal = mid in MULTIMODAL_MODELS if mid else False
return mid, gr.update(visible=is_multimodal)
model_dropdown.change(on_model_change, inputs=model_dropdown, outputs=[model_id, image_input])
if os.getenv("SPACE_ID"):
deploy_btn.click(on_deploy_click, inputs=[code_output, space_name_input, sdk_dropdown], outputs=deploy_status)
if __name__ == "__main__":
demo.queue().launch()