Update app.py
Browse files
app.py
CHANGED
@@ -3,42 +3,21 @@ import re
|
|
3 |
from http import HTTPStatus
|
4 |
from typing import Dict, List, Optional, Tuple
|
5 |
import base64
|
|
|
|
|
6 |
import dashscope
|
7 |
import gradio as gr
|
8 |
from dashscope import Generation
|
9 |
from dashscope.api_entities.dashscope_response import Role
|
|
|
10 |
import modelscope_studio.components.base as ms
|
11 |
import modelscope_studio.components.legacy as legacy
|
12 |
import modelscope_studio.components.antd as antd
|
|
|
13 |
|
14 |
-
# Define system prompt
|
15 |
-
SystemPrompt = """You are an AI assistant specialized in creating web applications and tools.
|
16 |
-
Generate complete, runnable code based on user requirements with modern best practices."""
|
17 |
-
|
18 |
-
# Define demo list
|
19 |
-
DEMO_LIST = [
|
20 |
-
{
|
21 |
-
"title": "Web Application",
|
22 |
-
"description": "Create a responsive web application with modern UI",
|
23 |
-
"icon": "π"
|
24 |
-
},
|
25 |
-
{
|
26 |
-
"title": "Data Visualization",
|
27 |
-
"description": "Build an interactive data visualization dashboard",
|
28 |
-
"icon": "π"
|
29 |
-
},
|
30 |
-
{
|
31 |
-
"title": "Automation Tool",
|
32 |
-
"description": "Generate a Python automation tool",
|
33 |
-
"icon": "π οΈ"
|
34 |
-
}
|
35 |
-
]
|
36 |
-
|
37 |
-
# Initialize DashScope
|
38 |
YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
|
39 |
dashscope.api_key = YOUR_API_TOKEN
|
40 |
|
41 |
-
# Type definitions
|
42 |
History = List[Tuple[str, str]]
|
43 |
Messages = List[Dict[str, str]]
|
44 |
|
@@ -49,19 +28,22 @@ def history_to_messages(history: History, system: str) -> Messages:
|
|
49 |
messages.append({'role': Role.ASSISTANT, 'content': h[1]})
|
50 |
return messages
|
51 |
|
52 |
-
|
|
|
53 |
assert messages[0]['role'] == Role.SYSTEM
|
54 |
history = []
|
55 |
for q, r in zip(messages[1::2], messages[2::2]):
|
56 |
history.append([q['content'], r['content']])
|
57 |
return history
|
58 |
|
|
|
59 |
def remove_code_block(text):
|
60 |
pattern = r'```html\n(.+?)\n```'
|
61 |
match = re.search(pattern, text, re.DOTALL)
|
62 |
if match:
|
63 |
return match.group(1).strip()
|
64 |
-
|
|
|
65 |
|
66 |
def history_render(history: History):
|
67 |
return gr.update(open=True), history
|
@@ -73,173 +55,153 @@ def send_to_sandbox(code):
|
|
73 |
encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
|
74 |
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
75 |
return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
77 |
def demo_card_click(e: gr.EventData):
|
78 |
index = e._data['component']['index']
|
79 |
return DEMO_LIST[index]['description']
|
80 |
|
81 |
-
|
82 |
-
with gr.Blocks(css="app.css") as demo:
|
83 |
history = gr.State([])
|
84 |
-
setting = gr.State({
|
85 |
-
|
|
|
|
|
86 |
with ms.Application() as app:
|
87 |
-
with antd.ConfigProvider(
|
88 |
-
"token": {
|
89 |
-
"colorPrimary": "#6366f1",
|
90 |
-
"borderRadius": 8,
|
91 |
-
"fontSize": 16
|
92 |
-
}
|
93 |
-
}):
|
94 |
with antd.Row(gutter=[32, 12]) as layout:
|
95 |
-
# Left Column
|
96 |
with antd.Col(span=24, md=8):
|
97 |
with antd.Flex(vertical=True, gap="middle", wrap=True):
|
98 |
header = gr.HTML("""
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
input = antd.InputTextarea(
|
106 |
-
size="large",
|
107 |
-
|
108 |
-
|
109 |
-
)
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
clear_btn = antd.Button("Clear History", size="large")
|
114 |
-
|
115 |
-
antd.Divider("Examples")
|
116 |
-
|
117 |
-
with antd.Space(direction="vertical", style={"width": "100%"}):
|
118 |
with ms.Each(DEMO_LIST):
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
antd.Divider("
|
124 |
-
|
125 |
with antd.Flex(gap="small", wrap=True):
|
126 |
-
settingPromptBtn = antd.Button(
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
with antd.Col(span=24, md=16):
|
132 |
with ms.Div(elem_classes="right_panel"):
|
133 |
-
gr.HTML("""
|
134 |
-
<div class="render_header">
|
135 |
-
<span class="header_btn"></span>
|
136 |
-
<span class="header_btn"></span>
|
137 |
-
<span class="header_btn"></span>
|
138 |
-
</div>
|
139 |
-
""")
|
140 |
-
|
141 |
with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
|
142 |
with antd.Tabs.Item(key="empty"):
|
143 |
-
empty = antd.Empty(
|
144 |
-
|
145 |
-
elem_classes="right_content"
|
146 |
-
)
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
gen = Generation.call(
|
183 |
-
model="qwen2.5-coder-32b-instruct",
|
184 |
-
messages=messages,
|
185 |
-
result_format='message',
|
186 |
-
stream=True
|
187 |
-
)
|
188 |
-
|
189 |
-
for response in gen:
|
190 |
-
if response.status_code == HTTPStatus.OK:
|
191 |
-
role = response.output.choices[0].message.role
|
192 |
-
content = response.output.choices[0].message.content
|
193 |
-
|
194 |
-
if response.output.choices[0].finish_reason == 'stop':
|
195 |
-
_history = messages_to_history(messages + [
|
196 |
-
{'role': role, 'content': content}
|
197 |
-
])
|
198 |
-
|
199 |
-
yield {
|
200 |
-
code_output: content,
|
201 |
-
history: _history,
|
202 |
-
sandbox: send_to_sandbox(remove_code_block(content)),
|
203 |
-
state_tab: gr.update(active_key="render"),
|
204 |
-
code_drawer: gr.update(open=False),
|
205 |
-
}
|
206 |
-
else:
|
207 |
-
yield {
|
208 |
-
code_output: content,
|
209 |
-
state_tab: gr.update(active_key="loading"),
|
210 |
-
code_drawer: gr.update(open=True),
|
211 |
-
}
|
212 |
-
else:
|
213 |
-
raise ValueError(
|
214 |
-
f'Request id: {response.request_id}, Status code: {response.status_code}, '
|
215 |
-
f'error code: {response.code}, error message: {response.message}'
|
216 |
-
)
|
217 |
-
|
218 |
-
# Connect event handlers
|
219 |
-
btn.click(
|
220 |
-
generation_code,
|
221 |
-
inputs=[input, setting, history],
|
222 |
-
outputs=[code_output, history, sandbox, state_tab, code_drawer]
|
223 |
-
)
|
224 |
-
|
225 |
-
settingPromptBtn.click(
|
226 |
-
lambda: gr.update(open=True),
|
227 |
-
outputs=[system_prompt_modal]
|
228 |
-
)
|
229 |
-
|
230 |
-
system_prompt_modal.ok(
|
231 |
-
lambda input: ({"system": input}, gr.update(open=False)),
|
232 |
-
inputs=[systemPromptInput],
|
233 |
-
outputs=[setting, system_prompt_modal]
|
234 |
-
)
|
235 |
-
|
236 |
-
clear_btn.click(clear_history, outputs=[history])
|
237 |
-
|
238 |
-
# Launch the app
|
239 |
if __name__ == "__main__":
|
240 |
-
demo.queue(
|
241 |
-
server_name="0.0.0.0",
|
242 |
-
server_port=7860,
|
243 |
-
share=True,
|
244 |
-
ssr_mode=False
|
245 |
-
)
|
|
|
3 |
from http import HTTPStatus
|
4 |
from typing import Dict, List, Optional, Tuple
|
5 |
import base64
|
6 |
+
|
7 |
+
|
8 |
import dashscope
|
9 |
import gradio as gr
|
10 |
from dashscope import Generation
|
11 |
from dashscope.api_entities.dashscope_response import Role
|
12 |
+
|
13 |
import modelscope_studio.components.base as ms
|
14 |
import modelscope_studio.components.legacy as legacy
|
15 |
import modelscope_studio.components.antd as antd
|
16 |
+
from config import DEMO_LIST, SystemPrompt
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
|
19 |
dashscope.api_key = YOUR_API_TOKEN
|
20 |
|
|
|
21 |
History = List[Tuple[str, str]]
|
22 |
Messages = List[Dict[str, str]]
|
23 |
|
|
|
28 |
messages.append({'role': Role.ASSISTANT, 'content': h[1]})
|
29 |
return messages
|
30 |
|
31 |
+
|
32 |
+
def messages_to_history(messages: Messages) -> Tuple[str, History]:
|
33 |
assert messages[0]['role'] == Role.SYSTEM
|
34 |
history = []
|
35 |
for q, r in zip(messages[1::2], messages[2::2]):
|
36 |
history.append([q['content'], r['content']])
|
37 |
return history
|
38 |
|
39 |
+
|
40 |
def remove_code_block(text):
|
41 |
pattern = r'```html\n(.+?)\n```'
|
42 |
match = re.search(pattern, text, re.DOTALL)
|
43 |
if match:
|
44 |
return match.group(1).strip()
|
45 |
+
else:
|
46 |
+
return text.strip()
|
47 |
|
48 |
def history_render(history: History):
|
49 |
return gr.update(open=True), history
|
|
|
55 |
encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
|
56 |
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
57 |
return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
|
58 |
+
# return {
|
59 |
+
# '/src/App.jsx': {
|
60 |
+
# 'code': code,
|
61 |
+
# 'fpath': '/src/App.jsx',
|
62 |
+
# },
|
63 |
+
# # δ»₯θ·―εΎδΈΊ keyοΌεΏ
ι‘»δ»₯η»ε―Ήθ·―εΎζ₯ζθΏ°
|
64 |
+
# '/src/index.js': {
|
65 |
+
# 'code':
|
66 |
+
# 'import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);',
|
67 |
+
# 'fpath': '/src/index.js',
|
68 |
+
# },
|
69 |
+
# '/package.json': {
|
70 |
+
# 'code': '{"name":"demo", "main": "./src/index.js", "dependencies":{ "react": "18.3.1", "react-dom": "18.3.1", "antd": "5.21.6", "styled-components": "6.1.13" }}',
|
71 |
+
# 'fpath': '/package.json',
|
72 |
+
# },
|
73 |
+
# }
|
74 |
|
75 |
def demo_card_click(e: gr.EventData):
|
76 |
index = e._data['component']['index']
|
77 |
return DEMO_LIST[index]['description']
|
78 |
|
79 |
+
with gr.Blocks(css_paths="app.css") as demo:
|
|
|
80 |
history = gr.State([])
|
81 |
+
setting = gr.State({
|
82 |
+
"system": SystemPrompt,
|
83 |
+
})
|
84 |
+
|
85 |
with ms.Application() as app:
|
86 |
+
with antd.ConfigProvider():
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
with antd.Row(gutter=[32, 12]) as layout:
|
|
|
88 |
with antd.Col(span=24, md=8):
|
89 |
with antd.Flex(vertical=True, gap="middle", wrap=True):
|
90 |
header = gr.HTML("""
|
91 |
+
<div class="left_header">
|
92 |
+
<img src="//img.alicdn.com/imgextra/i2/O1CN01KDhOma1DUo8oa7OIU_!!6000000000220-1-tps-240-240.gif" width="200px" />
|
93 |
+
<h1>Make Any Tool Using AI</h2>
|
94 |
+
</div>
|
95 |
+
""")
|
|
|
96 |
input = antd.InputTextarea(
|
97 |
+
size="large", allow_clear=True, placeholder="Please enter what kind of application you want")
|
98 |
+
# input = gr.TextArea(placeholder="θ―·θΎε
₯ζ¨ζ³θ¦δΈδΈͺδ»δΉζ ·ηεΊη¨", show_label=False, container=False)
|
99 |
+
btn = antd.Button("send", type="primary", size="large")
|
100 |
+
clear_btn = antd.Button("clear history", type="default", size="large")
|
101 |
+
|
102 |
+
antd.Divider("examples")
|
103 |
+
with antd.Flex(gap="small", wrap=True):
|
|
|
|
|
|
|
|
|
|
|
104 |
with ms.Each(DEMO_LIST):
|
105 |
+
with antd.Card(hoverable=True, as_item="card") as demoCard:
|
106 |
+
antd.CardMeta()
|
107 |
+
demoCard.click(demo_card_click, outputs=[input])
|
108 |
+
|
109 |
+
antd.Divider("setting")
|
110 |
+
|
111 |
with antd.Flex(gap="small", wrap=True):
|
112 |
+
settingPromptBtn = antd.Button(
|
113 |
+
"βοΈ set system Prompt", type="default")
|
114 |
+
codeBtn = antd.Button("π§βπ» view code", type="default")
|
115 |
+
historyBtn = antd.Button("π history", type="default")
|
116 |
+
|
117 |
+
with antd.Modal(open=False, title="set system Prompt", width="800px") as system_prompt_modal:
|
118 |
+
systemPromptInput = antd.InputTextarea(
|
119 |
+
SystemPrompt, auto_size=True)
|
120 |
+
|
121 |
+
settingPromptBtn.click(lambda: gr.update(
|
122 |
+
open=True), inputs=[], outputs=[system_prompt_modal])
|
123 |
+
system_prompt_modal.ok(lambda input: ({"system": input}, gr.update(
|
124 |
+
open=False)), inputs=[systemPromptInput], outputs=[setting, system_prompt_modal])
|
125 |
+
system_prompt_modal.cancel(lambda: gr.update(
|
126 |
+
open=False), outputs=[system_prompt_modal])
|
127 |
+
|
128 |
+
with antd.Drawer(open=False, title="code", placement="left", width="750px") as code_drawer:
|
129 |
+
code_output = legacy.Markdown()
|
130 |
+
|
131 |
+
codeBtn.click(lambda: gr.update(open=True),
|
132 |
+
inputs=[], outputs=[code_drawer])
|
133 |
+
code_drawer.close(lambda: gr.update(
|
134 |
+
open=False), inputs=[], outputs=[code_drawer])
|
135 |
+
|
136 |
+
with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
|
137 |
+
history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
|
138 |
+
|
139 |
+
historyBtn.click(history_render, inputs=[history], outputs=[history_drawer, history_output])
|
140 |
+
history_drawer.close(lambda: gr.update(
|
141 |
+
open=False), inputs=[], outputs=[history_drawer])
|
142 |
+
|
143 |
with antd.Col(span=24, md=16):
|
144 |
with ms.Div(elem_classes="right_panel"):
|
145 |
+
gr.HTML('<div class="render_header"><span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span></div>')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
|
147 |
with antd.Tabs.Item(key="empty"):
|
148 |
+
empty = antd.Empty(description="empty input", elem_classes="right_content")
|
149 |
+
with antd.Tabs.Item(key="loading"):
|
150 |
+
loading = antd.Spin(True, tip="coding...", size="large", elem_classes="right_content")
|
151 |
+
with antd.Tabs.Item(key="render"):
|
152 |
+
sandbox = gr.HTML(elem_classes="html_content")
|
153 |
+
# sandbox = pro.FrontendCodeSandbox(elem_style={
|
154 |
+
# 'height': '920px',
|
155 |
+
# 'width': '100%'
|
156 |
+
# })
|
157 |
+
|
158 |
+
def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
|
159 |
+
if query is None:
|
160 |
+
query = ''
|
161 |
+
if _history is None:
|
162 |
+
_history = []
|
163 |
+
messages = history_to_messages(_history, _setting['system'])
|
164 |
+
messages.append({'role': Role.USER, 'content': query})
|
165 |
+
|
166 |
+
gen = Generation.call(model="qwen2.5-coder-32b-instruct",
|
167 |
+
messages=messages,
|
168 |
+
result_format='message',
|
169 |
+
stream=True)
|
170 |
+
for response in gen:
|
171 |
+
if response.status_code == HTTPStatus.OK:
|
172 |
+
role = response.output.choices[0].message.role
|
173 |
+
content = response.output.choices[0].message.content
|
174 |
+
if response.output.choices[0].finish_reason == 'stop':
|
175 |
+
_history = messages_to_history(messages + [{
|
176 |
+
'role': role,
|
177 |
+
'content': content
|
178 |
+
}])
|
179 |
+
print('history')
|
180 |
+
print(_history)
|
181 |
+
yield {
|
182 |
+
code_output: content,
|
183 |
+
history: _history,
|
184 |
+
sandbox: send_to_sandbox(remove_code_block(content)),
|
185 |
+
state_tab: gr.update(active_key="render"),
|
186 |
+
code_drawer: gr.update(open=False),
|
187 |
+
}
|
188 |
+
else:
|
189 |
+
yield {
|
190 |
+
code_output: content,
|
191 |
+
state_tab: gr.update(active_key="loading"),
|
192 |
+
code_drawer: gr.update(open=True),
|
193 |
+
}
|
194 |
+
else:
|
195 |
+
raise ValueError(
|
196 |
+
'Request id: %s, Status code: %s, error code: %s, error message: %s'
|
197 |
+
% (response.request_id, response.status_code, response.code,
|
198 |
+
response.message))
|
199 |
+
|
200 |
+
btn.click(generation_code,
|
201 |
+
inputs=[input, setting, history],
|
202 |
+
outputs=[code_output, history, sandbox, state_tab, code_drawer])
|
203 |
|
204 |
+
clear_btn.click(clear_history, inputs=[], outputs=[history])
|
205 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
206 |
if __name__ == "__main__":
|
207 |
+
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|
|
|
|
|
|
|
|
|
|