sidbhasin commited on
Commit
51f9030
1 Parent(s): f7c4923

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -133
app.py CHANGED
@@ -3,21 +3,19 @@ import re
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 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,22 +26,19 @@ def history_to_messages(history: History, system: str) -> Messages:
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,145 +50,181 @@ def send_to_sandbox(code):
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': '{ "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
-
76
-
77
 
 
 
 
 
 
 
78
  with ms.Application() as app:
79
  with antd.ConfigProvider():
80
  with antd.Row(gutter=[32, 12]) as layout:
 
81
  with antd.Col(span=24, md=8):
82
  with antd.Flex(vertical=True, gap="middle", wrap=True):
83
  header = gr.HTML("""
84
- <div class="left_header">
85
- <img src="//img.alicdn.com/imgextra/i2/O1CN01KDhOma1DUo8oa7OIU_!!6000000000220-1-tps-240-240.gif" width="200px" />
86
- <h1>Qwen2.5-Coder</h2>
87
- </div>
88
- """)
 
89
  input = antd.InputTextarea(
90
- size="large", allow_clear=True, placeholder="Please enter what kind of application you want")
91
- # input = gr.TextArea(placeholder="请输入您想要一个什么样的应用", show_label=False, container=False)
 
 
 
92
  btn = antd.Button("send", type="primary", size="large")
93
  clear_btn = antd.Button("clear history", type="default", size="large")
94
-
95
- antd.Divider("examples")
96
- with antd.Flex(gap="small", wrap=True):
97
- with ms.Each(DEMO_LIST):
98
- with antd.Card(hoverable=True, as_item="card") as demoCard:
99
- antd.CardMeta()
100
- demoCard.click(demo_card_click, outputs=[input])
101
-
102
- antd.Divider("setting")
103
-
104
  with antd.Flex(gap="small", wrap=True):
105
- settingPromptBtn = antd.Button(
106
- "⚙️ set system Prompt", type="default")
107
  codeBtn = antd.Button("🧑‍💻 view code", type="default")
108
  historyBtn = antd.Button("📜 history", type="default")
109
-
110
- with antd.Modal(open=False, title="set system Prompt", width="800px") as system_prompt_modal:
111
- systemPromptInput = antd.InputTextarea(
112
- SystemPrompt, auto_size=True)
113
-
114
- settingPromptBtn.click(lambda: gr.update(
115
- open=True), inputs=[], outputs=[system_prompt_modal])
116
- system_prompt_modal.ok(lambda input: ({"system": input}, gr.update(
117
- open=False)), inputs=[systemPromptInput], outputs=[setting, system_prompt_modal])
118
- system_prompt_modal.cancel(lambda: gr.update(
119
- open=False), outputs=[system_prompt_modal])
120
-
121
- with antd.Drawer(open=False, title="code", placement="left", width="750px") as code_drawer:
122
- code_output = legacy.Markdown()
123
-
124
- codeBtn.click(lambda: gr.update(open=True),
125
- inputs=[], outputs=[code_drawer])
126
- code_drawer.close(lambda: gr.update(
127
- open=False), inputs=[], outputs=[code_drawer])
128
-
129
- with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
130
- history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
131
-
132
- historyBtn.click(history_render, inputs=[history], outputs=[history_drawer, history_output])
133
- history_drawer.close(lambda: gr.update(
134
- open=False), inputs=[], outputs=[history_drawer])
135
-
136
  with antd.Col(span=24, md=16):
137
  with ms.Div(elem_classes="right_panel"):
138
- gr.HTML('<div class="render_header"><span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span></div>')
 
 
 
 
 
 
 
139
  with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
140
  with antd.Tabs.Item(key="empty"):
141
- empty = antd.Empty(description="empty input", elem_classes="right_content")
142
- with antd.Tabs.Item(key="loading"):
143
- loading = antd.Spin(True, tip="coding...", size="large", elem_classes="right_content")
144
- with antd.Tabs.Item(key="render"):
145
- sandbox = gr.HTML(elem_classes="html_content")
146
- # sandbox = pro.FrontendCodeSandbox(elem_style={
147
- # 'height': '920px',
148
- # 'width': '100%'
149
- # })
150
-
151
- def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
152
- if query is None:
153
- query = ''
154
- if _history is None:
155
- _history = []
156
- messages = history_to_messages(_history, _setting['system'])
157
- messages.append({'role': Role.USER, 'content': query})
158
-
159
- gen = Generation.call(model="qwen2.5-coder-32b-instruct",
160
- messages=messages,
161
- result_format='message',
162
- stream=True)
163
- for response in gen:
164
- if response.status_code == HTTPStatus.OK:
165
- role = response.output.choices[0].message.role
166
- content = response.output.choices[0].message.content
167
- if response.output.choices[0].finish_reason == 'stop':
168
- _history = messages_to_history(messages + [{
169
- 'role': role,
170
- 'content': content
171
- }])
172
- print('history')
173
- print(_history)
174
- yield {
175
- code_output: content,
176
- history: _history,
177
- sandbox: send_to_sandbox(remove_code_block(content)),
178
- state_tab: gr.update(active_key="render"),
179
- code_drawer: gr.update(open=False),
180
- }
181
- else:
182
- yield {
183
- code_output: content,
184
- state_tab: gr.update(active_key="loading"),
185
- code_drawer: gr.update(open=True),
186
- }
187
- else:
188
- raise ValueError(
189
- 'Request id: %s, Status code: %s, error code: %s, error message: %s'
190
- % (response.request_id, response.status_code, response.code,
191
- response.message))
192
-
193
- btn.click(generation_code,
194
- inputs=[input, setting, history],
195
- outputs=[code_output, history, sandbox, state_tab, code_drawer])
196
 
197
- clear_btn.click(clear_history, inputs=[], outputs=[history])
198
-
199
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Initialize DashScope
15
  YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN')
16
  dashscope.api_key = YOUR_API_TOKEN
17
 
18
+ # Type definitions
19
  History = List[Tuple[str, str]]
20
  Messages = List[Dict[str, str]]
21
 
 
26
  messages.append({'role': Role.ASSISTANT, 'content': h[1]})
27
  return messages
28
 
29
+ def messages_to_history(messages: Messages) -> History:
 
30
  assert messages[0]['role'] == Role.SYSTEM
31
  history = []
32
  for q, r in zip(messages[1::2], messages[2::2]):
33
  history.append([q['content'], r['content']])
34
  return history
35
 
 
36
  def remove_code_block(text):
37
  pattern = r'```html\n(.+?)\n```'
38
  match = re.search(pattern, text, re.DOTALL)
39
  if match:
40
  return match.group(1).strip()
41
+ return text.strip()
 
42
 
43
  def history_render(history: History):
44
  return gr.update(open=True), history
 
50
  encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
51
  data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
52
  return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ with gr.Blocks(css_paths="app.css") as demo:
55
+ history = gr.State([])
56
+ setting = gr.State({
57
+ "system": "You are an AI assistant specialized in creating web applications and tools."
58
+ })
59
+
60
  with ms.Application() as app:
61
  with antd.ConfigProvider():
62
  with antd.Row(gutter=[32, 12]) as layout:
63
+ # Left Column
64
  with antd.Col(span=24, md=8):
65
  with antd.Flex(vertical=True, gap="middle", wrap=True):
66
  header = gr.HTML("""
67
+ <div class="left_header">
68
+ <img src="//img.alicdn.com/imgextra/i2/O1CN01KDhOma1DUo8oa7OIU_!!6000000000220-1-tps-240-240.gif" width="200px" />
69
+ <h1>AI TOOL BUILDER BY SYNCMERCE</h1>
70
+ </div>
71
+ """)
72
+
73
  input = antd.InputTextarea(
74
+ size="large",
75
+ allow_clear=True,
76
+ placeholder="Please enter what kind of application you want"
77
+ )
78
+
79
  btn = antd.Button("send", type="primary", size="large")
80
  clear_btn = antd.Button("clear history", type="default", size="large")
81
+
 
 
 
 
 
 
 
 
 
82
  with antd.Flex(gap="small", wrap=True):
83
+ settingPromptBtn = antd.Button("⚙️ set system Prompt", type="default")
 
84
  codeBtn = antd.Button("🧑‍💻 view code", type="default")
85
  historyBtn = antd.Button("📜 history", type="default")
86
+
87
+ # Right Column
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  with antd.Col(span=24, md=16):
89
  with ms.Div(elem_classes="right_panel"):
90
+ gr.HTML("""
91
+ <div class="render_header">
92
+ <span class="header_btn"></span>
93
+ <span class="header_btn"></span>
94
+ <span class="header_btn"></span>
95
+ </div>
96
+ """)
97
+
98
  with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
99
  with antd.Tabs.Item(key="empty"):
100
+ empty = antd.Empty(
101
+ description="Start by describing your application",
102
+ elem_classes="right_content"
103
+ )
104
+ with antd.Tabs.Item(key="loading"):
105
+ loading = antd.Spin(
106
+ True,
107
+ tip="Creating your application...",
108
+ size="large",
109
+ elem_classes="right_content"
110
+ )
111
+ with antd.Tabs.Item(key="render"):
112
+ sandbox = gr.HTML(elem_classes="html_content")
113
+
114
+ # Add modals and drawers
115
+ with antd.Modal(open=False, title="System Prompt", width="800px") as system_prompt_modal:
116
+ systemPromptInput = antd.InputTextarea(
117
+ "You are an AI assistant specialized in creating web applications and tools.",
118
+ auto_size=True
119
+ )
120
+
121
+ with antd.Drawer(open=False, title="code", placement="left", width="750px") as code_drawer:
122
+ code_output = legacy.Markdown()
123
+
124
+ with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
125
+ history_output = legacy.Chatbot(
126
+ show_label=False,
127
+ flushing=False,
128
+ height=960,
129
+ elem_classes="history_chatbot"
130
+ )
131
+
132
+ # Event handlers
133
+ def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
134
+ if query is None:
135
+ query = ''
136
+ if _history is None:
137
+ _history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
+ messages = history_to_messages(_history, _setting['system'])
140
+ messages.append({'role': Role.USER, 'content': query})
141
+
142
+ gen = Generation.call(
143
+ model="qwen2.5-coder-32b-instruct",
144
+ messages=messages,
145
+ result_format='message',
146
+ stream=True
147
+ )
148
+
149
+ for response in gen:
150
+ if response.status_code == HTTPStatus.OK:
151
+ role = response.output.choices[0].message.role
152
+ content = response.output.choices[0].message.content
153
+
154
+ if response.output.choices[0].finish_reason == 'stop':
155
+ _history = messages_to_history(messages + [
156
+ {'role': role, 'content': content}
157
+ ])
158
+
159
+ yield {
160
+ code_output: content,
161
+ history: _history,
162
+ sandbox: send_to_sandbox(remove_code_block(content)),
163
+ state_tab: gr.update(active_key="render"),
164
+ code_drawer: gr.update(open=False),
165
+ }
166
+ else:
167
+ yield {
168
+ code_output: content,
169
+ state_tab: gr.update(active_key="loading"),
170
+ code_drawer: gr.update(open=True),
171
+ }
172
+ else:
173
+ raise ValueError(
174
+ f'Request id: {response.request_id}, Status code: {response.status_code}, '
175
+ f'error code: {response.code}, error message: {response.message}'
176
+ )
177
+
178
+ # Connect event handlers
179
+ btn.click(
180
+ generation_code,
181
+ inputs=[input, setting, history],
182
+ outputs=[code_output, history, sandbox, state_tab, code_drawer]
183
+ )
184
+
185
+ settingPromptBtn.click(
186
+ lambda: gr.update(open=True),
187
+ outputs=[system_prompt_modal]
188
+ )
189
+
190
+ system_prompt_modal.ok(
191
+ lambda input: ({"system": input}, gr.update(open=False)),
192
+ inputs=[systemPromptInput],
193
+ outputs=[setting, system_prompt_modal]
194
+ )
195
+
196
+ system_prompt_modal.cancel(
197
+ lambda: gr.update(open=False),
198
+ outputs=[system_prompt_modal]
199
+ )
200
+
201
+ codeBtn.click(
202
+ lambda: gr.update(open=True),
203
+ outputs=[code_drawer]
204
+ )
205
+
206
+ code_drawer.close(
207
+ lambda: gr.update(open=False),
208
+ outputs=[code_drawer]
209
+ )
210
+
211
+ historyBtn.click(
212
+ history_render,
213
+ inputs=[history],
214
+ outputs=[history_drawer, history_output]
215
+ )
216
+
217
+ history_drawer.close(
218
+ lambda: gr.update(open=False),
219
+ outputs=[history_drawer]
220
+ )
221
+
222
+ clear_btn.click(clear_history, outputs=[history])
223
+
224
+ if __name__ == "__main__":
225
+ demo.queue(default_concurrency_limit=20).launch(
226
+ server_name="0.0.0.0",
227
+ server_port=7860,
228
+ share=True,
229
+ ssr_mode=False
230
+ )