mgbam commited on
Commit
0a9c605
·
verified ·
1 Parent(s): 20491fe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -195
app.py CHANGED
@@ -1,196 +1,196 @@
1
- import os
2
- from typing import Dict, List, Optional, Tuple
3
- import asyncio
4
-
5
- import gradio as gr
6
-
7
- from config import (
8
- AVAILABLE_MODELS, DEMO_LIST, HTML_SYSTEM_PROMPT,
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_demo_card, 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:
27
- # Try different ways to get the index
28
- if 'index' in e._data:
29
- index = e._data['index']
30
- elif 'component' in e._data and 'index' in e._data['component']:
31
- index = e._data['component']['index']
32
- elif 'target' in e._data and 'index' in e._data['target']:
33
- index = e._data['target']['index']
34
- else:
35
- # If we can't get the index, try to extract it from the card data
36
- index = 0
37
- else:
38
- index = 0
39
-
40
- # Ensure index is within bounds
41
- if index >= len(DEMO_LIST):
42
- index = 0
43
-
44
- return DEMO_LIST[index]['description']
45
- except (KeyError, IndexError, AttributeError) as e:
46
- # Return the first demo description as fallback
47
- return DEMO_LIST[0]['description']
48
-
49
-
50
- with gr.Blocks(
51
- theme=gr.themes.Base(
52
- primary_hue="blue",
53
- secondary_hue="gray",
54
- neutral_hue="gray",
55
- font=gr.themes.GoogleFont("Inter"),
56
- font_mono=gr.themes.GoogleFont("JetBrains Mono"),
57
- text_size=gr.themes.sizes.text_md,
58
- spacing_size=gr.themes.sizes.spacing_md,
59
- radius_size=gr.themes.sizes.radius_md
60
- ),
61
- title="AnyCoder - AI Code Generator"
62
- ) as demo:
63
- history = gr.State([])
64
- setting = gr.State({
65
- "system": HTML_SYSTEM_PROMPT,
66
- })
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 asyncio
4
+
5
+ import gradio as gr
6
+
7
+ from config import (
8
+ AVAILABLE_MODELS, DEMO_LIST, HTML_SYSTEM_PROMPT,
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:
27
+ # Try different ways to get the index
28
+ if 'index' in e._data:
29
+ index = e._data['index']
30
+ elif 'component' in e._data and 'index' in e._data['component']:
31
+ index = e._data['component']['index']
32
+ elif 'target' in e._data and 'index' in e._data['target']:
33
+ index = e._data['target']['index']
34
+ else:
35
+ # If we can't get the index, try to extract it from the card data
36
+ index = 0
37
+ else:
38
+ index = 0
39
+
40
+ # Ensure index is within bounds
41
+ if index >= len(DEMO_LIST):
42
+ index = 0
43
+
44
+ return DEMO_LIST[index]['description']
45
+ except (KeyError, IndexError, AttributeError) as e:
46
+ # Return the first demo description as fallback
47
+ return DEMO_LIST[0]['description']
48
+
49
+
50
+ with gr.Blocks(
51
+ theme=gr.themes.Base(
52
+ primary_hue="blue",
53
+ secondary_hue="gray",
54
+ neutral_hue="gray",
55
+ font=gr.themes.GoogleFont("Inter"),
56
+ font_mono=gr.themes.GoogleFont("JetBrains Mono"),
57
+ text_size=gr.themes.sizes.text_md,
58
+ spacing_size=gr.themes.sizes.spacing_md,
59
+ radius_size=gr.themes.sizes.radius_md
60
+ ),
61
+ title="AnyCoder - AI Code Generator"
62
+ ) as demo:
63
+ history = gr.State([])
64
+ setting = gr.State({
65
+ "system": HTML_SYSTEM_PROMPT,
66
+ })
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)