Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,20 +3,21 @@ 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 DEMO_LIST, SystemPrompt
|
17 |
|
18 |
-
YOUR_API_TOKEN = os.getenv('
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
History = List[Tuple[str, str]]
|
22 |
Messages = List[Dict[str, str]]
|
@@ -28,15 +29,13 @@ 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)
|
@@ -55,22 +54,6 @@ 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']
|
@@ -90,12 +73,11 @@ with gr.Blocks(css_paths="app.css") as demo:
|
|
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>
|
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 |
|
@@ -150,52 +132,50 @@ with gr.Blocks(css_paths="app.css") as demo:
|
|
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 |
-
|
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 |
btn.click(generation_code,
|
201 |
inputs=[input, setting, history],
|
@@ -204,4 +184,4 @@ with gr.Blocks(css_paths="app.css") as demo:
|
|
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)
|
|
|
3 |
from http import HTTPStatus
|
4 |
from typing import Dict, List, Optional, Tuple
|
5 |
import base64
|
6 |
+
import anthropic
|
7 |
|
|
|
|
|
8 |
import gradio as gr
|
|
|
|
|
|
|
9 |
import modelscope_studio.components.base as ms
|
10 |
import modelscope_studio.components.legacy as legacy
|
11 |
import modelscope_studio.components.antd as antd
|
12 |
from config import DEMO_LIST, SystemPrompt
|
13 |
|
14 |
+
YOUR_API_TOKEN = os.getenv('ANTHROPIC_API_KEY')
|
15 |
+
client = anthropic.Anthropic(api_key=YOUR_API_TOKEN)
|
16 |
+
|
17 |
+
class Role:
|
18 |
+
SYSTEM = "system"
|
19 |
+
USER = "user"
|
20 |
+
ASSISTANT = "assistant"
|
21 |
|
22 |
History = List[Tuple[str, str]]
|
23 |
Messages = List[Dict[str, str]]
|
|
|
29 |
messages.append({'role': Role.ASSISTANT, 'content': h[1]})
|
30 |
return messages
|
31 |
|
32 |
+
def messages_to_history(messages: Messages) -> 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 |
def remove_code_block(text):
|
40 |
pattern = r'```html\n(.+?)\n```'
|
41 |
match = re.search(pattern, text, re.DOTALL)
|
|
|
54 |
encoded_html = base64.b64encode(code.encode('utf-8')).decode('utf-8')
|
55 |
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
56 |
return f"<iframe src=\"{data_uri}\" width=\"100%\" height=\"920px\"></iframe>"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
|
58 |
def demo_card_click(e: gr.EventData):
|
59 |
index = e._data['component']['index']
|
|
|
73 |
header = gr.HTML("""
|
74 |
<div class="left_header">
|
75 |
<img src="//img.alicdn.com/imgextra/i2/O1CN01KDhOma1DUo8oa7OIU_!!6000000000220-1-tps-240-240.gif" width="200px" />
|
76 |
+
<h1>Claude-3-Sonnet Coder</h2>
|
77 |
</div>
|
78 |
""")
|
79 |
input = antd.InputTextarea(
|
80 |
size="large", allow_clear=True, placeholder="Please enter what kind of application you want")
|
|
|
81 |
btn = antd.Button("send", type="primary", size="large")
|
82 |
clear_btn = antd.Button("clear history", type="default", size="large")
|
83 |
|
|
|
132 |
loading = antd.Spin(True, tip="coding...", size="large", elem_classes="right_content")
|
133 |
with antd.Tabs.Item(key="render"):
|
134 |
sandbox = gr.HTML(elem_classes="html_content")
|
|
|
|
|
|
|
|
|
135 |
|
136 |
def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History]):
|
137 |
+
if query is None:
|
138 |
+
query = ''
|
139 |
+
if _history is None:
|
140 |
+
_history = []
|
141 |
+
|
142 |
+
messages = history_to_messages(_history, _setting['system'])
|
143 |
+
messages.append({'role': Role.USER, 'content': query})
|
144 |
+
|
145 |
+
try:
|
146 |
+
# 중간 상태 표시
|
147 |
+
yield {
|
148 |
+
code_output: "Generating code...",
|
149 |
+
state_tab: gr.update(active_key="loading"),
|
150 |
+
code_drawer: gr.update(open=True),
|
151 |
+
}
|
152 |
+
|
153 |
+
response = client.messages.create(
|
154 |
+
model="claude-3-sonnet-20240229",
|
155 |
+
max_tokens=4096,
|
156 |
+
messages=[
|
157 |
+
{"role": msg["role"], "content": msg["content"]}
|
158 |
+
for msg in messages
|
159 |
+
]
|
160 |
+
)
|
161 |
+
|
162 |
+
content = response.content[0].text
|
163 |
+
_history = messages_to_history(messages + [{
|
164 |
+
'role': Role.ASSISTANT,
|
165 |
+
'content': content
|
166 |
+
}])
|
167 |
+
|
168 |
+
# 최종 결과 반환
|
169 |
+
yield {
|
170 |
+
code_output: content,
|
171 |
+
history: _history,
|
172 |
+
sandbox: send_to_sandbox(remove_code_block(content)),
|
173 |
+
state_tab: gr.update(active_key="render"),
|
174 |
+
code_drawer: gr.update(open=False),
|
175 |
+
}
|
176 |
+
|
177 |
+
except Exception as e:
|
178 |
+
raise ValueError(f'Error calling Claude API: {str(e)}')
|
179 |
|
180 |
btn.click(generation_code,
|
181 |
inputs=[input, setting, history],
|
|
|
184 |
clear_btn.click(clear_history, inputs=[], outputs=[history])
|
185 |
|
186 |
if __name__ == "__main__":
|
187 |
+
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|