mgbam commited on
Commit
46c562f
·
verified ·
1 Parent(s): 0a9c605

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -105
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import os
2
  from typing import Dict, List, Optional, Tuple
 
3
  import asyncio
4
 
5
  import gradio as gr
@@ -9,18 +10,22 @@ from config import (
9
  )
10
  from api_clients import generation_code, tavily_client
11
  from chat_processing import (
12
- clear_history, history_to_chatbot_messages, update_image_input_visibility,
13
- get_gradio_language, send_to_sandbox,
14
  )
15
  from file_processing import create_multimodal_message
16
  from web_extraction import enhance_query_with_search
17
  from ux_components import create_top_demo_cards
18
 
19
  # --- Gradio App UI ---
 
20
 
21
 
22
-
23
- def demo_card_click(e: gr.EventData):
 
 
 
24
  try:
25
  # Get the index from the event data
26
  if hasattr(e, '_data') and e._data:
@@ -60,6 +65,7 @@ with gr.Blocks(
60
  ),
61
  title="AnyCoder - AI Code Generator"
62
  ) as demo:
 
63
  history = gr.State([])
64
  setting = gr.State({
65
  "system": HTML_SYSTEM_PROMPT,
@@ -67,130 +73,126 @@ with gr.Blocks(
67
  current_model = gr.State(AVAILABLE_MODELS[0]) # Moonshot Kimi-K2
68
  open_panel = gr.State(None)
69
  last_login_state = gr.State(None)
70
- with gr.Sidebar():
71
- input = gr.Textbox(
72
- label="What would you like to build?",
73
- placeholder="Describe your application...",
74
- lines=3,
75
- visible=True # Always visible
76
- )
77
- # Language dropdown for code generation
78
- language_choices = [
79
- "python", "c", "cpp", "markdown", "latex", "json", "html", "css", "javascript", "jinja2", "typescript", "yaml", "dockerfile", "shell", "r", "sql", "sql-msSQL", "sql-mySQL", "sql-mariaDB", "sql-sqlite", "sql-cassandra", "sql-plSQL", "sql-hive", "sql-pgSQL", "sql-gql", "sql-gpSQL", "sql-sparkSQL", "sql-esper"
80
- ]
81
- language_dropdown = gr.Dropdown(
82
- choices=language_choices,
83
- value="html",
84
- label="Code Language",
85
- visible=True # Always visible
86
- )
87
- website_url_input = gr.Textbox(
88
- label="Website URL for redesign",
89
- placeholder="https://example.com",
90
- lines=1,
91
- visible=True # Always visible
92
- )
93
- file_input = gr.File(
94
- label="Reference file",
95
- file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"],
96
- visible=True # Always visible
97
- )
98
- image_input = gr.Image(
99
- label="UI design image",
100
- visible=False # Hidden by default; shown only for ERNIE-VL or GLM-VL
101
- )
102
- with gr.Row():
103
- btn = gr.Button("Generate", variant="primary", size="lg", scale=2, visible=True) # Always visible
104
- clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True) # Always visible
105
- search_toggle = gr.Checkbox(
106
- label="🔍 Web search",
107
- value=False,
108
- visible=True # Always visible
109
- )
110
- model_dropdown = gr.Dropdown(
111
- choices=[model['name'] for model in AVAILABLE_MODELS],
112
- value=AVAILABLE_MODELS[0]['name'], # Moonshot Kimi-K2
113
- label="Model",
114
- visible=True # Always visible
115
- )
116
- gr.Markdown("**Quick start**", visible=True)
117
- quick_examples_col = create_top_demo_cards(input)
118
-
119
- if not tavily_client:
120
- gr.Markdown("⚠️ Web search unavailable", visible=True)
121
- else:
122
- gr.Markdown("✅ Web search available", visible=True)
123
- model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=True) # Moonshot Kimi-K2
124
- def on_model_change(model_name):
125
- for m in AVAILABLE_MODELS:
126
- if m['name'] == model_name:
127
- return m, f"**Model:** {m['name']}", update_image_input_visibility(m)
128
- return AVAILABLE_MODELS[0], f"**Model:** {AVAILABLE_MODELS[0]['name']}", update_image_input_visibility(AVAILABLE_MODELS[0]) # Moonshot Kimi-K2 fallback
129
-
130
- def save_prompt(input):
131
- return {setting: {"system": input}}
132
- model_dropdown.change(
133
- on_model_change,
134
- inputs=model_dropdown,
135
- outputs=[current_model, model_display, image_input]
136
- )
137
- with gr.Accordion("Advanced", open=False, visible=True) as advanced_accordion:
138
- systemPromptInput = gr.Textbox(
139
- value=HTML_SYSTEM_PROMPT,
140
- label="System prompt",
141
- lines=5
142
- )
143
- save_prompt_btn = gr.Button("Save", variant="primary", size="sm")
144
- save_prompt_btn.click(save_prompt, inputs=systemPromptInput, outputs=setting)
145
 
146
- with gr.Column():
147
- with gr.Tabs():
148
- with gr.Tab("Code"):
149
- code_output = gr.Code(
150
- language="html",
151
- lines=25,
152
- interactive=False,
153
- label="Generated code"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  )
155
- with gr.Tab("Preview"):
156
- sandbox = gr.HTML(label="Live preview")
157
- with gr.Tab("History"):
158
- history_output = gr.Chatbot(show_label=False, height=400, type="messages")
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
  # --- Event Handlers ---
 
 
 
 
 
 
 
 
 
161
  def update_code_language(language):
162
  return gr.update(language=get_gradio_language(language))
163
 
164
- language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)
165
-
166
  def preview_logic(code, language):
167
  if language == "html":
168
  return send_to_sandbox(code)
169
  else:
170
  return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML.</div>"
171
 
172
-
173
- # Use asyncio.create_task to ensure the generation_code coroutine is properly awaited
174
- def submit_query(*args):
175
- task = asyncio.create_task(generation_code(*args)) # Create a task
176
- async def wrapper():
177
- async for update in task:
178
  yield update
179
- return wrapper() # Return the wrapper function
180
 
181
  btn.click(fn=submit_query,
182
  inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown],
183
  outputs=[code_output, history, sandbox, history_output])
184
 
 
185
 
 
 
 
 
 
 
186
  # Update preview when code or language changes
 
187
  code_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
188
- language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
189
  clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])
190
 
191
-
192
- if __name__ == "__main__":
193
- demo.queue(api_open=False, default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=False, show_api=False)
194
-
195
  if __name__ == "__main__":
196
  demo.queue(api_open=False, default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=False, show_api=False)
 
1
  import os
2
  from typing import Dict, List, Optional, Tuple
3
+ import logging
4
  import asyncio
5
 
6
  import gradio as gr
 
10
  )
11
  from api_clients import generation_code, tavily_client
12
  from chat_processing import (
13
+ clear_history, history_to_chatbot_messages, update_image_input_visibility, update_submit_button,
14
+ get_gradio_language, send_to_sandbox
15
  )
16
  from file_processing import create_multimodal_message
17
  from web_extraction import enhance_query_with_search
18
  from ux_components import create_top_demo_cards
19
 
20
  # --- Gradio App UI ---
21
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
22
 
23
 
24
+ def demo_card_click(evt: gr.EventData):
25
+ """Handles clicks on the demo cards to populate the input textbox."""
26
+ # This function seems complex for its purpose. Gradio's event data can be tricky.
27
+ # A simpler approach might be to directly pass the description.
28
+ # For now, keeping the logic but adding comments.
29
  try:
30
  # Get the index from the event data
31
  if hasattr(e, '_data') and e._data:
 
65
  ),
66
  title="AnyCoder - AI Code Generator"
67
  ) as demo:
68
+ gr.HTML("<h1 align='center'>AnyCoder - AI Code Generator</h1>")
69
  history = gr.State([])
70
  setting = gr.State({
71
  "system": HTML_SYSTEM_PROMPT,
 
73
  current_model = gr.State(AVAILABLE_MODELS[0]) # Moonshot Kimi-K2
74
  open_panel = gr.State(None)
75
  last_login_state = gr.State(None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ with gr.Row():
78
+ with gr.Column(scale=1):
79
+ gr.Markdown("## Controls")
80
+ input = gr.Textbox(
81
+ label="What would you like to build?",
82
+ placeholder="Describe your application...",
83
+ lines=4,
84
+ interactive=True
85
+ )
86
+ # Language dropdown for code generation
87
+ language_choices = [
88
+ "python", "c", "cpp", "markdown", "latex", "json", "html", "css", "javascript", "jinja2", "typescript", "yaml", "dockerfile", "shell", "r", "sql"
89
+ ]
90
+ language_dropdown = gr.Dropdown(
91
+ choices=language_choices,
92
+ value="html",
93
+ label="Code Language"
94
+ )
95
+ website_url_input = gr.Textbox(
96
+ label="Website URL for redesign",
97
+ placeholder="https://example.com",
98
+ lines=1
99
+ )
100
+ file_input = gr.File(
101
+ label="Reference file",
102
+ file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"]
103
+ )
104
+ image_input = gr.Image(
105
+ label="UI design image",
106
+ visible=False # Hidden by default; shown only for ERNIE-VL or GLM-VL
107
+ )
108
+ with gr.Row():
109
+ btn = gr.Button("Generate", variant="primary", size="lg", scale=2, interactive=False)
110
+ clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1)
111
+
112
+ gr.Markdown("---")
113
+ gr.Markdown("### Quick Examples")
114
+ quick_examples_col = create_top_demo_cards(input)
115
+
116
+ gr.Markdown("---")
117
+ gr.Markdown("### Settings")
118
+ search_toggle = gr.Checkbox(
119
+ label="🔍 Web search",
120
+ value=False,
121
+ )
122
+ if not tavily_client:
123
+ gr.Markdown("⚠️ Web search unavailable", visible=True)
124
+
125
+ model_dropdown = gr.Dropdown(
126
+ choices=[model['name'] for model in AVAILABLE_MODELS],
127
+ value=AVAILABLE_MODELS[0]['name'], # Moonshot Kimi-K2
128
+ label="Model",
129
+ )
130
+
131
+ with gr.Accordion("Advanced Settings", open=False):
132
+ systemPromptInput = gr.Textbox(
133
+ value=HTML_SYSTEM_PROMPT,
134
+ label="System Prompt",
135
+ lines=5
136
  )
137
+ save_prompt_btn = gr.Button("Save Prompt", variant="secondary", size="sm")
138
+
139
+ with gr.Column(scale=3):
140
+ model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=True)
141
+ with gr.Tabs():
142
+ with gr.Tab("Code"):
143
+ code_output = gr.Code(
144
+ language="html",
145
+ lines=28,
146
+ interactive=False,
147
+ label="Generated Code"
148
+ )
149
+ with gr.Tab("Preview"):
150
+ sandbox = gr.HTML(label="Live Preview")
151
+ with gr.Tab("History"):
152
+ history_output = gr.Chatbot(show_label=False, height=600, type="messages")
153
 
154
  # --- Event Handlers ---
155
+ def on_model_change(model_name):
156
+ for m in AVAILABLE_MODELS:
157
+ if m['name'] == model_name:
158
+ return m, f"**Model:** {m['name']}", update_image_input_visibility(m)
159
+ return AVAILABLE_MODELS[0], f"**Model:** {AVAILABLE_MODELS[0]['name']}", update_image_input_visibility(AVAILABLE_MODELS[0])
160
+
161
+ def save_prompt(prompt_text):
162
+ return {setting: {"system": prompt_text}}
163
+
164
  def update_code_language(language):
165
  return gr.update(language=get_gradio_language(language))
166
 
 
 
167
  def preview_logic(code, language):
168
  if language == "html":
169
  return send_to_sandbox(code)
170
  else:
171
  return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML.</div>"
172
 
173
+ async def submit_query(*args):
174
+ """Handles the main code generation logic asynchronously."""
175
+ # This is the correct way to handle async generators in Gradio
176
+ with gr.Tabs():
177
+ async for update in generation_code(*args):
 
178
  yield update
 
179
 
180
  btn.click(fn=submit_query,
181
  inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown],
182
  outputs=[code_output, history, sandbox, history_output])
183
 
184
+ input.change(update_submit_button, inputs=input, outputs=btn)
185
 
186
+ model_dropdown.change(
187
+ on_model_change,
188
+ inputs=model_dropdown,
189
+ outputs=[current_model, model_display, image_input]
190
+ )
191
+ save_prompt_btn.click(save_prompt, inputs=systemPromptInput, outputs=setting)
192
  # Update preview when code or language changes
193
+ language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)
194
  code_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
 
195
  clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])
196
 
 
 
 
 
197
  if __name__ == "__main__":
198
  demo.queue(api_open=False, default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=False, show_api=False)