Use Hyperbolic API to call Qwen coder.
Browse files- app.py +91 -98
- requirements.txt +2 -1
app.py
CHANGED
@@ -1,42 +1,36 @@
|
|
1 |
import os
|
2 |
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 |
-
|
11 |
-
|
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('
|
19 |
-
dashscope.api_key = YOUR_API_TOKEN
|
20 |
|
21 |
History = List[Tuple[str, str]]
|
22 |
Messages = List[Dict[str, str]]
|
23 |
|
24 |
def history_to_messages(history: History, system: str) -> Messages:
|
25 |
-
messages = [{'role':
|
26 |
for h in history:
|
27 |
-
messages.append({'role':
|
28 |
-
messages.append({'role':
|
29 |
return messages
|
30 |
|
31 |
-
|
32 |
-
|
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)
|
@@ -55,29 +49,13 @@ 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': '{"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 |
-
|
81 |
setting = gr.State({
|
82 |
"system": SystemPrompt,
|
83 |
})
|
@@ -88,23 +66,30 @@ with gr.Blocks(css_paths="app.css") as demo:
|
|
88 |
with antd.Col(span=24, md=8):
|
89 |
with antd.Flex(vertical=True, gap="middle", wrap=True):
|
90 |
header = gr.HTML("""
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
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 |
-
|
106 |
-
|
107 |
-
|
108 |
|
109 |
antd.Divider("setting")
|
110 |
|
@@ -136,7 +121,7 @@ with gr.Blocks(css_paths="app.css") as demo:
|
|
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=[
|
140 |
history_drawer.close(lambda: gr.update(
|
141 |
open=False), inputs=[], outputs=[history_drawer])
|
142 |
|
@@ -146,62 +131,70 @@ with gr.Blocks(css_paths="app.css") as demo:
|
|
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 |
-
|
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 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
|
206 |
if __name__ == "__main__":
|
207 |
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|
|
|
|
1 |
import os
|
2 |
import re
|
|
|
|
|
3 |
import base64
|
4 |
+
from typing import Dict, List, Optional, Tuple
|
5 |
|
|
|
|
|
6 |
import gradio as gr
|
7 |
+
|
8 |
+
import hyperbolic_gradio
|
9 |
|
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 |
from config import DEMO_LIST, SystemPrompt
|
14 |
|
15 |
+
YOUR_API_TOKEN = os.getenv('HYPERBOLIC_API_KEY')
|
|
|
16 |
|
17 |
History = List[Tuple[str, str]]
|
18 |
Messages = List[Dict[str, str]]
|
19 |
|
20 |
def history_to_messages(history: History, system: str) -> Messages:
|
21 |
+
messages = [{'role': 'system', 'content': system}]
|
22 |
for h in history:
|
23 |
+
messages.append({'role': 'user', 'content': h[0]})
|
24 |
+
messages.append({'role': 'assistant', 'content': h[1]})
|
25 |
return messages
|
26 |
|
27 |
+
def messages_to_history(messages: Messages) -> History:
|
28 |
+
assert messages[0]['role'] == 'system'
|
|
|
29 |
history = []
|
30 |
for q, r in zip(messages[1::2], messages[2::2]):
|
31 |
history.append([q['content'], r['content']])
|
32 |
return history
|
33 |
|
|
|
34 |
def remove_code_block(text):
|
35 |
pattern = r'```html\n(.+?)\n```'
|
36 |
match = re.search(pattern, text, re.DOTALL)
|
|
|
49 |
encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
|
50 |
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
51 |
return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
def demo_card_click(e: gr.EventData):
|
54 |
index = e._data['component']['index']
|
55 |
return DEMO_LIST[index]['description']
|
56 |
|
57 |
with gr.Blocks(css_paths="app.css") as demo:
|
58 |
+
history_state = gr.State([])
|
59 |
setting = gr.State({
|
60 |
"system": SystemPrompt,
|
61 |
})
|
|
|
66 |
with antd.Col(span=24, md=8):
|
67 |
with antd.Flex(vertical=True, gap="middle", wrap=True):
|
68 |
header = gr.HTML("""
|
69 |
+
<div style="text-align: center;">
|
70 |
+
<!-- Container for GIFs -->
|
71 |
+
<div style="display: flex; justify-content: center; gap: 20px; margin-bottom: 20px;">
|
72 |
+
<!-- First GIF -->
|
73 |
+
<img src="https://raw.githubusercontent.com/HyperbolicLabs/hyperbolic-gradio/master/hyperbolic-animated.gif" width="200px" />
|
74 |
+
<!-- Second GIF -->
|
75 |
+
<img src="//img.alicdn.com/imgextra/i2/O1CN01KDhOma1DUo8oa7OIU_!!6000000000220-1-tps-240-240.gif" width="200px" />
|
76 |
+
</div>
|
77 |
+
<!-- Header Text -->
|
78 |
+
<h1>Qwen2.5-Coder-32B with Hyperbolic API</h1>
|
79 |
+
</div>
|
80 |
+
""")
|
81 |
+
|
82 |
input = antd.InputTextarea(
|
83 |
size="large", allow_clear=True, placeholder="Please enter what kind of application you want")
|
|
|
84 |
btn = antd.Button("send", type="primary", size="large")
|
85 |
clear_btn = antd.Button("clear history", type="default", size="large")
|
86 |
|
87 |
antd.Divider("examples")
|
88 |
with antd.Flex(gap="small", wrap=True):
|
89 |
with ms.Each(DEMO_LIST):
|
90 |
+
with antd.Card(hoverable=True, as_item="card") as demoCard:
|
91 |
+
antd.CardMeta()
|
92 |
+
demoCard.click(demo_card_click, outputs=[input])
|
93 |
|
94 |
antd.Divider("setting")
|
95 |
|
|
|
121 |
with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
|
122 |
history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
|
123 |
|
124 |
+
historyBtn.click(history_render, inputs=[history_state], outputs=[history_drawer, history_output])
|
125 |
history_drawer.close(lambda: gr.update(
|
126 |
open=False), inputs=[], outputs=[history_drawer])
|
127 |
|
|
|
131 |
with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
|
132 |
with antd.Tabs.Item(key="empty"):
|
133 |
empty = antd.Empty(description="empty input", elem_classes="right_content")
|
134 |
+
with antd.Tabs.Item(key="loading"):
|
135 |
+
loading = antd.Spin(True, tip="coding...", size="large", elem_classes="right_content")
|
136 |
+
with antd.Tabs.Item(key="render"):
|
137 |
+
sandbox = gr.HTML(elem_classes="html_content")
|
138 |
+
|
139 |
+
def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
|
140 |
+
if query is None:
|
141 |
+
query = ''
|
142 |
+
if _history is None:
|
143 |
+
_history = []
|
144 |
+
|
145 |
+
# Prepare the preprocess and postprocess functions
|
146 |
+
def preprocess(message, history):
|
147 |
+
messages = [{'role': 'system', 'content': _setting['system']}]
|
148 |
+
for user_msg, assistant_msg in history:
|
149 |
+
messages.append({'role': 'user', 'content': user_msg})
|
150 |
+
messages.append({'role': 'assistant', 'content': assistant_msg})
|
151 |
+
messages.append({'role': 'user', 'content': message})
|
152 |
+
return {'messages': messages}
|
153 |
+
|
154 |
+
def postprocess(response_text):
|
155 |
+
return response_text
|
156 |
+
|
157 |
+
# Get the model from hyperbolic_gradio
|
158 |
+
fn = hyperbolic_gradio.get_fn(
|
159 |
+
model_name='Qwen/Qwen2.5-Coder-32B-Instruct',
|
160 |
+
preprocess=preprocess,
|
161 |
+
postprocess=postprocess,
|
162 |
+
api_key=YOUR_API_TOKEN,
|
163 |
+
base_url="https://api.hyperbolic.xyz/v1"
|
164 |
+
)
|
165 |
+
|
166 |
+
response_text = ''
|
167 |
+
assistant_response = ''
|
168 |
+
local_history = _history.copy()
|
169 |
+
|
170 |
+
for content in fn(query, local_history):
|
171 |
+
response_text = content
|
172 |
+
# Update code_output
|
173 |
+
yield {
|
174 |
+
code_output: response_text,
|
175 |
+
state_tab: gr.update(active_key="loading"),
|
176 |
+
code_drawer: gr.update(open=True),
|
177 |
+
}
|
178 |
+
|
179 |
+
assistant_response = response_text
|
180 |
+
local_history.append([query, assistant_response])
|
181 |
+
|
182 |
+
code = remove_code_block(assistant_response)
|
183 |
+
|
184 |
+
yield {
|
185 |
+
code_output: assistant_response,
|
186 |
+
history_state: local_history,
|
187 |
+
sandbox: send_to_sandbox(code),
|
188 |
+
state_tab: gr.update(active_key="render"),
|
189 |
+
code_drawer: gr.update(open=False),
|
190 |
+
}
|
191 |
+
|
192 |
+
btn.click(generation_code,
|
193 |
+
inputs=[input, setting, history_state],
|
194 |
+
outputs=[code_output, history_state, sandbox, state_tab, code_drawer])
|
195 |
+
|
196 |
+
clear_btn.click(clear_history, inputs=[], outputs=[history_state])
|
197 |
|
198 |
if __name__ == "__main__":
|
199 |
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|
200 |
+
|
requirements.txt
CHANGED
@@ -1,2 +1,3 @@
|
|
1 |
dashscope
|
2 |
-
modelscope_studio~=1.0.0b
|
|
|
|
1 |
dashscope
|
2 |
+
modelscope_studio~=1.0.0b
|
3 |
+
hyperbolic-gradio
|