Update app.py
Browse files
app.py
CHANGED
@@ -8,65 +8,59 @@ the calls to the backend logic in other modules.
|
|
8 |
"""
|
9 |
import gradio as gr
|
10 |
|
11 |
-
from config import AVAILABLE_MODELS,
|
12 |
from core import generate_code
|
13 |
from deployment import deploy_to_hf_space
|
14 |
-
from utils import get_gradio_language
|
15 |
|
16 |
# --- UI Helper Functions ---
|
17 |
-
|
18 |
def send_to_sandbox(code: str, language: str) -> str:
|
19 |
"""Generates an iframe for the preview tab, safely handling quotes."""
|
20 |
if language == "html" and code:
|
21 |
-
# First, replace all double quotes in the HTML code with the " entity.
|
22 |
-
# This prevents the srcdoc attribute from breaking.
|
23 |
safe_code = code.replace('"', '"')
|
24 |
-
# Now, inject the safe code into the iframe.
|
25 |
return f'<iframe srcdoc="{safe_code}" width="100%" height="920px" style="border:0;"></iframe>'
|
26 |
return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only for HTML.</div>"
|
27 |
|
28 |
-
|
29 |
# --- Event Handlers ---
|
30 |
-
|
31 |
def on_generate_click(
|
32 |
query: str, image: gr.Image, file: gr.File, website_url: str,
|
33 |
history: list, model_name: str, enable_search: bool, language: str
|
34 |
):
|
35 |
-
"""Handler for the 'Generate' button click event."""
|
36 |
if not query and not image and not file and not website_url:
|
37 |
yield {
|
38 |
code_output: gr.update(value="Please provide a prompt, image, file, or URL.", language="text"),
|
39 |
-
history_output: history
|
40 |
}
|
41 |
return
|
42 |
|
43 |
model_config = next((m for m in AVAILABLE_MODELS if m['name'] == model_name), AVAILABLE_MODELS[0])
|
44 |
|
45 |
-
# Stream the response
|
46 |
for response in generate_code(query, image, file.name if file else None, website_url, history, model_config, enable_search, language):
|
47 |
-
# Determine the code to be used for the sandbox preview
|
48 |
preview_code = response.get("code_output", "")
|
49 |
-
|
50 |
ui_update = {
|
51 |
code_output: gr.update(value=preview_code, language=get_gradio_language(language)),
|
52 |
sandbox: send_to_sandbox(preview_code, language)
|
53 |
}
|
54 |
if "history" in response:
|
55 |
ui_update[history_state] = response["history"]
|
56 |
-
|
|
|
57 |
yield ui_update
|
58 |
|
59 |
def on_model_change(model_name: str):
|
60 |
-
"""Updates UI elements when the model selection changes."""
|
61 |
model_id = next((m['id'] for m in AVAILABLE_MODELS if m['name'] == model_name), None)
|
62 |
return gr.update(visible=model_id in MULTIMODAL_MODELS)
|
63 |
|
64 |
def on_language_change(language: str):
|
65 |
-
"""Updates the code output and preview when language changes."""
|
66 |
return gr.update(language=get_gradio_language(language))
|
67 |
|
68 |
-
|
|
|
69 |
"""Handler for the deploy button."""
|
|
|
|
|
|
|
|
|
70 |
sdk_map = {"Static (HTML)": "static", "Gradio (Python)": "gradio"}
|
71 |
sdk = sdk_map.get(sdk_name, "static")
|
72 |
return gr.update(value=deploy_to_hf_space(code, space_name, sdk, hf_token), visible=True)
|
@@ -74,21 +68,19 @@ def on_deploy_click(code: str, space_name: str, sdk_name: str, hf_token: str):
|
|
74 |
# --- Gradio UI Layout ---
|
75 |
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder") as demo:
|
76 |
history_state = gr.State([])
|
77 |
-
hf_token_state = gr.State()
|
78 |
|
79 |
gr.Markdown("# 🤖 AnyCoder - AI Code Generator")
|
80 |
gr.Markdown("Describe what you want to build, upload a design, or provide a URL to redesign. The AI will generate the code for you.")
|
81 |
|
82 |
with gr.Row():
|
83 |
with gr.Column(scale=1):
|
84 |
-
# --- Inputs ---
|
85 |
input_prompt = gr.Textbox(label="Prompt", placeholder="e.g., a login form with a blue button", lines=3)
|
86 |
language_dropdown = gr.Dropdown(choices=["html", "python", "javascript", "css"], value="html", label="Language")
|
87 |
website_url_input = gr.Textbox(label="URL to Redesign", placeholder="https://example.com")
|
88 |
file_input = gr.File(label="Reference File (PDF, TXT, DOCX, image)")
|
89 |
image_input = gr.Image(label="UI Design Image", type="numpy", visible=False)
|
90 |
|
91 |
-
# --- Controls ---
|
92 |
with gr.Accordion("Settings", open=False):
|
93 |
model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[0]['name'], label="Model")
|
94 |
search_toggle = gr.Checkbox(label="Enable Web Search", value=False)
|
@@ -97,7 +89,6 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder") as
|
|
97 |
clear_btn = gr.Button("Clear")
|
98 |
generate_btn = gr.Button("Generate", variant="primary", scale=2)
|
99 |
|
100 |
-
# --- Deployment ---
|
101 |
with gr.Accordion("🚀 Deploy to Hugging Face", open=False):
|
102 |
login_button = gr.LoginButton()
|
103 |
space_name_input = gr.Textbox(label="New App Name", placeholder="my-cool-app")
|
@@ -106,14 +97,18 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder") as
|
|
106 |
deploy_status = gr.Markdown(visible=False)
|
107 |
|
108 |
with gr.Column(scale=2):
|
109 |
-
# --- Outputs ---
|
110 |
with gr.Tabs():
|
111 |
with gr.Tab("Preview"):
|
112 |
sandbox = gr.HTML(label="Live Preview", elem_id="sandbox-preview")
|
113 |
with gr.Tab("Code"):
|
114 |
code_output = gr.Code(label="Generated Code", language="html", interactive=True)
|
115 |
with gr.Tab("History"):
|
116 |
-
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
# --- Event Wiring ---
|
119 |
generate_btn.click(
|
@@ -121,16 +116,20 @@ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder") as
|
|
121 |
inputs=[input_prompt, image_input, file_input, website_url_input, history_state, model_dropdown, search_toggle, language_dropdown],
|
122 |
outputs=[code_output, sandbox, history_state, history_output]
|
123 |
)
|
124 |
-
|
|
|
|
|
125 |
|
126 |
model_dropdown.change(on_model_change, inputs=model_dropdown, outputs=image_input)
|
127 |
language_dropdown.change(on_language_change, inputs=language_dropdown, outputs=code_output)
|
128 |
language_dropdown.change(lambda code, lang: send_to_sandbox(code, lang), inputs=[code_output, language_dropdown], outputs=sandbox)
|
129 |
|
130 |
-
|
|
|
|
|
131 |
deploy_btn.click(
|
132 |
on_deploy_click,
|
133 |
-
inputs=[code_output, space_name_input, sdk_dropdown,
|
134 |
outputs=deploy_status
|
135 |
)
|
136 |
|
|
|
8 |
"""
|
9 |
import gradio as gr
|
10 |
|
11 |
+
from config import AVAILABLE_MODELS, MULTIMODAL_MODELS
|
12 |
from core import generate_code
|
13 |
from deployment import deploy_to_hf_space
|
14 |
+
from utils import get_gradio_language, history_to_chatbot_messages # <--- FIX: Import new helper
|
15 |
|
16 |
# --- UI Helper Functions ---
|
|
|
17 |
def send_to_sandbox(code: str, language: str) -> str:
|
18 |
"""Generates an iframe for the preview tab, safely handling quotes."""
|
19 |
if language == "html" and code:
|
|
|
|
|
20 |
safe_code = code.replace('"', '"')
|
|
|
21 |
return f'<iframe srcdoc="{safe_code}" width="100%" height="920px" style="border:0;"></iframe>'
|
22 |
return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only for HTML.</div>"
|
23 |
|
|
|
24 |
# --- Event Handlers ---
|
|
|
25 |
def on_generate_click(
|
26 |
query: str, image: gr.Image, file: gr.File, website_url: str,
|
27 |
history: list, model_name: str, enable_search: bool, language: str
|
28 |
):
|
|
|
29 |
if not query and not image and not file and not website_url:
|
30 |
yield {
|
31 |
code_output: gr.update(value="Please provide a prompt, image, file, or URL.", language="text"),
|
32 |
+
history_output: history_to_chatbot_messages(history) # <--- FIX: Use new helper
|
33 |
}
|
34 |
return
|
35 |
|
36 |
model_config = next((m for m in AVAILABLE_MODELS if m['name'] == model_name), AVAILABLE_MODELS[0])
|
37 |
|
|
|
38 |
for response in generate_code(query, image, file.name if file else None, website_url, history, model_config, enable_search, language):
|
|
|
39 |
preview_code = response.get("code_output", "")
|
|
|
40 |
ui_update = {
|
41 |
code_output: gr.update(value=preview_code, language=get_gradio_language(language)),
|
42 |
sandbox: send_to_sandbox(preview_code, language)
|
43 |
}
|
44 |
if "history" in response:
|
45 |
ui_update[history_state] = response["history"]
|
46 |
+
# <--- FIX: Use the helper function to format history for the chatbot
|
47 |
+
ui_update[history_output] = history_to_chatbot_messages(response["history"])
|
48 |
yield ui_update
|
49 |
|
50 |
def on_model_change(model_name: str):
|
|
|
51 |
model_id = next((m['id'] for m in AVAILABLE_MODELS if m['name'] == model_name), None)
|
52 |
return gr.update(visible=model_id in MULTIMODAL_MODELS)
|
53 |
|
54 |
def on_language_change(language: str):
|
|
|
55 |
return gr.update(language=get_gradio_language(language))
|
56 |
|
57 |
+
# <--- FIX: Modified function to accept the auth token from the button
|
58 |
+
def on_deploy_click(code: str, space_name: str, sdk_name: str, auth_token: gr.OAuthToken | None):
|
59 |
"""Handler for the deploy button."""
|
60 |
+
hf_token = auth_token.token if auth_token else None
|
61 |
+
if not hf_token:
|
62 |
+
return gr.update(value="⚠️ Please log in with your Hugging Face account to deploy.", visible=True)
|
63 |
+
|
64 |
sdk_map = {"Static (HTML)": "static", "Gradio (Python)": "gradio"}
|
65 |
sdk = sdk_map.get(sdk_name, "static")
|
66 |
return gr.update(value=deploy_to_hf_space(code, space_name, sdk, hf_token), visible=True)
|
|
|
68 |
# --- Gradio UI Layout ---
|
69 |
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder") as demo:
|
70 |
history_state = gr.State([])
|
71 |
+
# hf_token_state = gr.State() # <--- FIX: No longer needed
|
72 |
|
73 |
gr.Markdown("# 🤖 AnyCoder - AI Code Generator")
|
74 |
gr.Markdown("Describe what you want to build, upload a design, or provide a URL to redesign. The AI will generate the code for you.")
|
75 |
|
76 |
with gr.Row():
|
77 |
with gr.Column(scale=1):
|
|
|
78 |
input_prompt = gr.Textbox(label="Prompt", placeholder="e.g., a login form with a blue button", lines=3)
|
79 |
language_dropdown = gr.Dropdown(choices=["html", "python", "javascript", "css"], value="html", label="Language")
|
80 |
website_url_input = gr.Textbox(label="URL to Redesign", placeholder="https://example.com")
|
81 |
file_input = gr.File(label="Reference File (PDF, TXT, DOCX, image)")
|
82 |
image_input = gr.Image(label="UI Design Image", type="numpy", visible=False)
|
83 |
|
|
|
84 |
with gr.Accordion("Settings", open=False):
|
85 |
model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[0]['name'], label="Model")
|
86 |
search_toggle = gr.Checkbox(label="Enable Web Search", value=False)
|
|
|
89 |
clear_btn = gr.Button("Clear")
|
90 |
generate_btn = gr.Button("Generate", variant="primary", scale=2)
|
91 |
|
|
|
92 |
with gr.Accordion("🚀 Deploy to Hugging Face", open=False):
|
93 |
login_button = gr.LoginButton()
|
94 |
space_name_input = gr.Textbox(label="New App Name", placeholder="my-cool-app")
|
|
|
97 |
deploy_status = gr.Markdown(visible=False)
|
98 |
|
99 |
with gr.Column(scale=2):
|
|
|
100 |
with gr.Tabs():
|
101 |
with gr.Tab("Preview"):
|
102 |
sandbox = gr.HTML(label="Live Preview", elem_id="sandbox-preview")
|
103 |
with gr.Tab("Code"):
|
104 |
code_output = gr.Code(label="Generated Code", language="html", interactive=True)
|
105 |
with gr.Tab("History"):
|
106 |
+
# <--- FIX: Update Chatbot component to modern standards
|
107 |
+
history_output = gr.Chatbot(
|
108 |
+
label="Conversation History",
|
109 |
+
type="messages",
|
110 |
+
height=500
|
111 |
+
)
|
112 |
|
113 |
# --- Event Wiring ---
|
114 |
generate_btn.click(
|
|
|
116 |
inputs=[input_prompt, image_input, file_input, website_url_input, history_state, model_dropdown, search_toggle, language_dropdown],
|
117 |
outputs=[code_output, sandbox, history_state, history_output]
|
118 |
)
|
119 |
+
# <--- FIX: Update clear button to output correctly formatted empty list for chatbot
|
120 |
+
clear_btn.click(lambda: ([], [], None, None, None, "", []),
|
121 |
+
outputs=[history_state, history_output, input_prompt, image_input, file_input, website_url_input, code_output])
|
122 |
|
123 |
model_dropdown.change(on_model_change, inputs=model_dropdown, outputs=image_input)
|
124 |
language_dropdown.change(on_language_change, inputs=language_dropdown, outputs=code_output)
|
125 |
language_dropdown.change(lambda code, lang: send_to_sandbox(code, lang), inputs=[code_output, language_dropdown], outputs=sandbox)
|
126 |
|
127 |
+
# <--- FIX: REMOVED the incorrect .login() event handler
|
128 |
+
|
129 |
+
# <--- FIX: Correct way to handle deployment click
|
130 |
deploy_btn.click(
|
131 |
on_deploy_click,
|
132 |
+
inputs=[code_output, space_name_input, sdk_dropdown, login_button], # Pass the button itself as input
|
133 |
outputs=deploy_status
|
134 |
)
|
135 |
|