seawolf2357 commited on
Commit
0085f6d
Β·
verified Β·
1 Parent(s): 9d4cb1a

Create app-backup1.py

Browse files
Files changed (1) hide show
  1. app-backup1.py +196 -0
app-backup1.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
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]]
24
+
25
+ def history_to_messages(history: History, system: str) -> Messages:
26
+ messages = [{'role': Role.SYSTEM, 'content': system}]
27
+ for h in history:
28
+ messages.append({'role': Role.USER, 'content': h[0]})
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)
42
+ if match:
43
+ return match.group(1).strip()
44
+ else:
45
+ return text.strip()
46
+
47
+ def history_render(history: History):
48
+ return gr.update(open=True), history
49
+
50
+ def clear_history():
51
+ return []
52
+
53
+ def send_to_sandbox(code):
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']
60
+ return DEMO_LIST[index]['description']
61
+
62
+ with gr.Blocks(css_paths="app.css") as demo:
63
+ history = gr.State([])
64
+ setting = gr.State({
65
+ "system": SystemPrompt,
66
+ })
67
+
68
+ with ms.Application() as app:
69
+ with antd.ConfigProvider():
70
+ with antd.Row(gutter=[32, 12]) as layout:
71
+ with antd.Col(span=24, md=8):
72
+ with antd.Flex(vertical=True, gap="middle", wrap=True):
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
+
84
+ antd.Divider("examples")
85
+ with antd.Flex(gap="small", wrap=True):
86
+ with ms.Each(DEMO_LIST):
87
+ with antd.Card(hoverable=True, as_item="card") as demoCard:
88
+ antd.CardMeta()
89
+ demoCard.click(demo_card_click, outputs=[input])
90
+
91
+ antd.Divider("setting")
92
+
93
+ with antd.Flex(gap="small", wrap=True):
94
+ settingPromptBtn = antd.Button(
95
+ "βš™οΈ set system Prompt", type="default")
96
+ codeBtn = antd.Button("πŸ§‘β€πŸ’» view code", type="default")
97
+ historyBtn = antd.Button("πŸ“œ history", type="default")
98
+
99
+ with antd.Modal(open=False, title="set system Prompt", width="800px") as system_prompt_modal:
100
+ systemPromptInput = antd.InputTextarea(
101
+ SystemPrompt, auto_size=True)
102
+
103
+ settingPromptBtn.click(lambda: gr.update(
104
+ open=True), inputs=[], outputs=[system_prompt_modal])
105
+ system_prompt_modal.ok(lambda input: ({"system": input}, gr.update(
106
+ open=False)), inputs=[systemPromptInput], outputs=[setting, system_prompt_modal])
107
+ system_prompt_modal.cancel(lambda: gr.update(
108
+ open=False), outputs=[system_prompt_modal])
109
+
110
+ with antd.Drawer(open=False, title="code", placement="left", width="750px") as code_drawer:
111
+ code_output = legacy.Markdown()
112
+
113
+ codeBtn.click(lambda: gr.update(open=True),
114
+ inputs=[], outputs=[code_drawer])
115
+ code_drawer.close(lambda: gr.update(
116
+ open=False), inputs=[], outputs=[code_drawer])
117
+
118
+ with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
119
+ history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
120
+
121
+ historyBtn.click(history_render, inputs=[history], outputs=[history_drawer, history_output])
122
+ history_drawer.close(lambda: gr.update(
123
+ open=False), inputs=[], outputs=[history_drawer])
124
+
125
+ with antd.Col(span=24, md=16):
126
+ with ms.Div(elem_classes="right_panel"):
127
+ gr.HTML('<div class="render_header"><span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span></div>')
128
+ with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
129
+ with antd.Tabs.Item(key="empty"):
130
+ empty = antd.Empty(description="empty input", elem_classes="right_content")
131
+ with antd.Tabs.Item(key="loading"):
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
+ system_message = messages[0]['content']
144
+
145
+ claude_messages = [
146
+ {"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]}
147
+ for msg in messages[1:] + [{'role': Role.USER, 'content': query}]
148
+ ]
149
+
150
+ try:
151
+ # 쀑간 μƒνƒœ ν‘œμ‹œ
152
+ yield [
153
+ "Generating code...", # code_output
154
+ _history, # history
155
+ None, # sandbox
156
+ gr.update(active_key="loading"), # state_tab
157
+ gr.update(open=True) # code_drawer
158
+ ]
159
+
160
+ response = client.messages.create(
161
+ model="claude-3-5-sonnet-20241022",
162
+ max_tokens=7800,
163
+ system=system_message,
164
+ messages=claude_messages
165
+ )
166
+
167
+ content = response.content[0].text
168
+ _history = messages_to_history([
169
+ {'role': Role.SYSTEM, 'content': system_message}
170
+ ] + claude_messages + [{
171
+ 'role': Role.ASSISTANT,
172
+ 'content': content
173
+ }])
174
+
175
+ # μ΅œμ’… κ²°κ³Ό λ°˜ν™˜
176
+ yield [
177
+ content, # code_output
178
+ _history, # history
179
+ send_to_sandbox(remove_code_block(content)), # sandbox
180
+ gr.update(active_key="render"), # state_tab
181
+ gr.update(open=True) # code_drawer
182
+ ]
183
+
184
+ except Exception as e:
185
+ raise ValueError(f'Error calling Claude API: {str(e)}')
186
+
187
+ btn.click(
188
+ generation_code,
189
+ inputs=[input, setting, history],
190
+ outputs=[code_output, history, sandbox, state_tab, code_drawer]
191
+ )
192
+
193
+ clear_btn.click(clear_history, inputs=[], outputs=[history])
194
+
195
+ if __name__ == "__main__":
196
+ demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)