mgbam commited on
Commit
52e9ca9
·
verified ·
1 Parent(s): 846f240

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -96
app.py CHANGED
@@ -1,142 +1,106 @@
1
- # /app.py (Final Corrected Version)
2
-
3
- """
4
- Main Gradio application for AnyCoder.
5
-
6
- This file defines the user interface, handles user interactions, and orchestrates
7
- the calls to the backend logic in other modules.
8
- """
9
  import gradio as gr
10
  import os
11
-
12
- from config import AVAILABLE_MODELS, MULTIMODAL_MODELS
13
  from core import generate_code
14
  from deployment import deploy_to_hf_space
15
  from utils import get_gradio_language, history_to_chatbot_messages
16
 
17
- # --- UI Helper Functions ---
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
- safe_code = code.replace('"', '"')
22
- return f'<iframe srcdoc="{safe_code}" width="100%" height="920px" style="border:0;"></iframe>'
23
- return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only for HTML.</div>"
24
-
25
  # --- Event Handlers ---
26
- def on_generate_click(
27
- query: str, image: gr.Image, file: gr.File, website_url: str,
28
- history: list, model_name: str, enable_search: bool, language: str
29
- ):
30
- if not query and not image and not file and not website_url:
31
  yield {
32
- code_output: gr.update(value="Please provide a prompt, image, file, or URL.", language="text"),
 
33
  history_output: history_to_chatbot_messages(history)
34
  }
35
  return
36
-
 
37
  model_config = next((m for m in AVAILABLE_MODELS if m['name'] == model_name), AVAILABLE_MODELS[0])
38
-
39
  for response in generate_code(query, image, file.name if file else None, website_url, history, model_config, enable_search, language):
40
- preview_code = response.get("code_output", "")
41
- ui_update = {
42
- code_output: gr.update(value=preview_code, language=get_gradio_language(language)),
43
- sandbox: send_to_sandbox(preview_code, language)
44
- }
45
  if "history" in response:
46
  ui_update[history_state] = response["history"]
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
  def on_deploy_click(code: str, space_name: str, sdk_name: str, request: gr.Request):
58
- """Handler for the deploy button, now correctly using gr.Request."""
59
  hf_token = request.token
60
- if not hf_token:
61
- return gr.update(value="⚠️ Please log in with your Hugging Face account to deploy.", visible=True)
62
-
63
- sdk_map = {"Static (HTML)": "static", "Gradio (Python)": "gradio"}
64
- sdk = sdk_map.get(sdk_name, "static")
65
  return gr.update(value=deploy_to_hf_space(code, space_name, sdk, hf_token), visible=True)
66
 
67
- # --- Gradio UI Layout ---
68
- with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder") as demo:
69
- # 1. DEFINE ALL COMPONENTS FIRST
70
  history_state = gr.State([])
71
-
72
- gr.Markdown("# 🤖 AnyCoder - AI Code Generator")
73
- 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.")
74
 
75
  with gr.Row():
76
  with gr.Column(scale=1):
77
- input_prompt = gr.Textbox(label="Prompt", placeholder="e.g., a login form with a blue button", lines=3)
78
- language_dropdown = gr.Dropdown(choices=["html", "python", "javascript", "css"], value="html", label="Language")
 
79
  website_url_input = gr.Textbox(label="URL to Redesign", placeholder="https://example.com")
80
- file_input = gr.File(label="Reference File (PDF, TXT, DOCX, image)")
81
- image_input = gr.Image(label="UI Design Image", type="numpy", visible=False)
82
 
83
- with gr.Accordion("Settings", open=False):
84
- model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[0]['name'], label="Model")
85
- search_toggle = gr.Checkbox(label="Enable Web Search", value=False)
 
 
86
 
87
  with gr.Row():
88
  clear_btn = gr.Button("Clear")
89
  generate_btn = gr.Button("Generate", variant="primary", scale=2)
 
 
 
 
90
 
91
- # Conditionally define the deployment components
92
- # We must define them here so they exist for the event wiring later.
93
  if os.getenv("SPACE_ID"):
94
  with gr.Accordion("🚀 Deploy to Hugging Face", open=False):
95
- login_button = gr.LoginButton() # This is just a placeholder in this context
96
- space_name_input = gr.Textbox(label="New App Name", placeholder="my-cool-app")
97
  sdk_dropdown = gr.Dropdown(choices=["Static (HTML)", "Gradio (Python)"], value="Static (HTML)", label="App Type")
98
  deploy_btn = gr.Button("Deploy")
99
  deploy_status = gr.Markdown(visible=False)
100
-
101
  with gr.Column(scale=2):
102
- with gr.Tabs():
103
- with gr.Tab("Preview"):
104
- sandbox = gr.HTML(label="Live Preview", elem_id="sandbox-preview")
105
- with gr.Tab("Code"):
106
- code_output = gr.Code(label="Generated Code", language="html", interactive=True)
107
- with gr.Tab("History"):
108
- history_output = gr.Chatbot(
109
- label="Conversation History",
110
- type="messages",
111
- height=500
112
- )
113
-
114
- # 2. WIRE UP ALL EVENTS AT THE END
115
- # This ensures all component variables (like 'code_output') are defined before being used.
116
-
117
- # Main generation event
118
- generate_btn.click(
119
- fn=on_generate_click,
120
  inputs=[input_prompt, image_input, file_input, website_url_input, history_state, model_dropdown, search_toggle, language_dropdown],
121
- outputs=[code_output, sandbox, history_state, history_output]
122
- )
123
-
124
- # Clear button event
125
- clear_btn.click(lambda: ([], [], None, None, None, "", ""),
126
- outputs=[history_state, history_output, input_prompt, image_input, file_input, website_url_input, code_output])
 
127
 
128
- # UI change events
129
- model_dropdown.change(on_model_change, inputs=model_dropdown, outputs=image_input)
130
- language_dropdown.change(on_language_change, inputs=language_dropdown, outputs=code_output)
131
- language_dropdown.change(lambda code, lang: send_to_sandbox(code, lang), inputs=[code_output, language_dropdown], outputs=sandbox)
 
132
 
133
- # Conditionally wire up the deployment event
134
  if os.getenv("SPACE_ID"):
135
- deploy_btn.click(
136
- on_deploy_click,
137
- inputs=[code_output, space_name_input, sdk_dropdown],
138
- outputs=deploy_status
139
- )
140
 
141
  if __name__ == "__main__":
142
  demo.queue().launch()
 
1
+ # /app.py
2
+ """ Main Gradio application for AnyCoder. """
 
 
 
 
 
 
3
  import gradio as gr
4
  import os
5
+ from config import AVAILABLE_MODELS, MULTIMODAL_MODELS, DEMO_LIST
 
6
  from core import generate_code
7
  from deployment import deploy_to_hf_space
8
  from utils import get_gradio_language, history_to_chatbot_messages
9
 
 
 
 
 
 
 
 
 
10
  # --- Event Handlers ---
11
+ 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):
12
+ # This is the section with the error
13
+ if not any([query, image, file, website_url]):
 
 
14
  yield {
15
+ # <--- FIX: Change language="text" to language="markdown" ---
16
+ code_output: gr.update(value="## Please provide a prompt, image, file, or URL.", language="markdown"),
17
  history_output: history_to_chatbot_messages(history)
18
  }
19
  return
20
+
21
+ # The rest of the function is correct and needs no changes
22
  model_config = next((m for m in AVAILABLE_MODELS if m['name'] == model_name), AVAILABLE_MODELS[0])
 
23
  for response in generate_code(query, image, file.name if file else None, website_url, history, model_config, enable_search, language):
24
+ ui_update = {code_output: gr.update(value=response.get("code_output"), language=get_gradio_language(language))}
 
 
 
 
25
  if "history" in response:
26
  ui_update[history_state] = response["history"]
27
  ui_update[history_output] = history_to_chatbot_messages(response["history"])
28
  yield ui_update
29
 
30
+ # ... (The rest of the file is correct and does not need to be changed) ...
 
 
 
 
 
 
31
  def on_deploy_click(code: str, space_name: str, sdk_name: str, request: gr.Request):
 
32
  hf_token = request.token
33
+ if not hf_token: return gr.update(value="⚠️ Please log in with your Hugging Face account to deploy.", visible=True)
34
+ sdk = {"Static (HTML)": "static", "Gradio (Python)": "gradio"}.get(sdk_name, "static")
 
 
 
35
  return gr.update(value=deploy_to_hf_space(code, space_name, sdk, hf_token), visible=True)
36
 
37
+ # --- UI Layout ---
38
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue"), title="AnyCoder AI") as demo:
 
39
  history_state = gr.State([])
40
+ gr.Markdown("# 🚀 AnyCoder AI - Multi-Provider Code Generator")
 
 
41
 
42
  with gr.Row():
43
  with gr.Column(scale=1):
44
+ input_prompt = gr.Textbox(label="Prompt", placeholder="e.g., a login form with a blue button", lines=4)
45
+ model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[0]['name'], label="Select Model")
46
+ language_dropdown = gr.Dropdown(choices=["html", "python", "javascript", "css", "react"], value="html", label="Language")
47
  website_url_input = gr.Textbox(label="URL to Redesign", placeholder="https://example.com")
 
 
48
 
49
+ with gr.Row():
50
+ file_input = gr.File(label="Reference File", scale=2)
51
+ image_input = gr.Image(label="UI Image", type="numpy", visible=False, scale=1)
52
+
53
+ search_toggle = gr.Checkbox(label="Enable Web Search", value=False)
54
 
55
  with gr.Row():
56
  clear_btn = gr.Button("Clear")
57
  generate_btn = gr.Button("Generate", variant="primary", scale=2)
58
+
59
+ gr.Markdown("--- \n**Quick Examples**")
60
+ for item in DEMO_LIST:
61
+ gr.Button(item['title']).click(lambda d=item['description']: d, outputs=input_prompt)
62
 
 
 
63
  if os.getenv("SPACE_ID"):
64
  with gr.Accordion("🚀 Deploy to Hugging Face", open=False):
65
+ login_button = gr.LoginButton()
66
+ space_name_input = gr.Textbox(label="New App Name", placeholder="my-anycoder-app")
67
  sdk_dropdown = gr.Dropdown(choices=["Static (HTML)", "Gradio (Python)"], value="Static (HTML)", label="App Type")
68
  deploy_btn = gr.Button("Deploy")
69
  deploy_status = gr.Markdown(visible=False)
70
+
71
  with gr.Column(scale=2):
72
+ with gr.Tabs() as tabs:
73
+ preview_tab = gr.Tab("Preview")
74
+ code_tab = gr.Tab("Code")
75
+ history_tab = gr.Tab("History")
76
+ with preview_tab:
77
+ sandbox = gr.HTML(label="Live Preview", elem_id="sandbox-preview", visible=False)
78
+ placeholder = gr.Markdown("### Your live preview will appear here after generation.")
79
+ with code_tab:
80
+ code_output = gr.Code(label="Generated Code", language="html", interactive=True)
81
+ with history_tab:
82
+ history_output = gr.Chatbot(label="Conversation History", type="messages", height=600)
83
+
84
+ # --- Event Wiring ---
85
+ model_id = gr.State()
86
+ generate_btn.click(on_generate_click,
 
 
 
87
  inputs=[input_prompt, image_input, file_input, website_url_input, history_state, model_dropdown, search_toggle, language_dropdown],
88
+ outputs=[code_output, history_state, history_output])
89
+
90
+ code_output.change(lambda code: [gr.HTML(f'<iframe srcdoc="{code.replace("\"", """)}" width="100%" height="920px" style="border:0;"></iframe>', visible=True), gr.Markdown(visible=False)] if code else [gr.HTML(visible=False), gr.Markdown(visible=True)],
91
+ inputs=code_output, outputs=[sandbox, placeholder])
92
+
93
+ clear_btn.click(lambda: ([], [], None, None, None, "", "", None, gr.HTML(visible=False), gr.Markdown(visible=True)),
94
+ outputs=[history_state, history_output, input_prompt, image_input, file_input, website_url_input, code_output, model_id, sandbox, placeholder])
95
 
96
+ def on_model_change(model_name):
97
+ mid = next((m['id'] for m in AVAILABLE_MODELS if m['name'] == model_name), None)
98
+ is_multimodal = mid in MULTIMODAL_MODELS
99
+ return mid, gr.update(visible=is_multimodal)
100
+ model_dropdown.change(on_model_change, inputs=model_dropdown, outputs=[model_id, image_input])
101
 
 
102
  if os.getenv("SPACE_ID"):
103
+ deploy_btn.click(on_deploy_click, inputs=[code_output, space_name_input, sdk_dropdown], outputs=deploy_status)
 
 
 
 
104
 
105
  if __name__ == "__main__":
106
  demo.queue().launch()