Lyte commited on
Commit
5831028
·
verified ·
1 Parent(s): 6f10ccc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -200
app.py CHANGED
@@ -1,201 +1,227 @@
1
- import time
2
- import gradio as gr
3
- from openai import OpenAI
4
-
5
- DESCRIPTION = '''
6
- # DeepSeek-R1 Distill Qwen-14B Demo
7
- A reasoning model trained using RL (Reinforcement Learning) that demonstrates structured reasoning capabilities.
8
- '''
9
-
10
- CSS = """
11
- .spinner {
12
- animation: spin 1s linear infinite;
13
- display: inline-block;
14
- margin-right: 8px;
15
- }
16
- @keyframes spin {
17
- from { transform: rotate(0deg); }
18
- to { transform: rotate(360deg); }
19
- }
20
- .thinking-summary {
21
- cursor: pointer;
22
- padding: 8px;
23
- background: #f5f5f5;
24
- border-radius: 4px;
25
- margin: 4px 0;
26
- }
27
- .thought-content {
28
- padding: 10px;
29
- background: #f8f9fa;
30
- border-radius: 4px;
31
- margin: 5px 0;
32
- }
33
- .thinking-container {
34
- border-left: 3px solid #e0e0e0;
35
- padding-left: 10px;
36
- margin: 8px 0;
37
- }
38
- details:not([open]) .thinking-container {
39
- border-left-color: #4CAF50;
40
- }
41
- """
42
-
43
- client = OpenAI(base_url="http://localhost:8080/v1", api_key="no-key-required")
44
-
45
- def user(message, history):
46
- return "", history + [[message, None]]
47
-
48
- class ParserState:
49
- __slots__ = ['answer', 'thought', 'in_think', 'start_time', 'last_pos']
50
- def __init__(self):
51
- self.answer = ""
52
- self.thought = ""
53
- self.in_think = False
54
- self.start_time = 0
55
- self.last_pos = 0
56
-
57
- def parse_response(text, state):
58
- buffer = text[state.last_pos:]
59
- state.last_pos = len(text)
60
-
61
- while buffer:
62
- if not state.in_think:
63
- think_start = buffer.find('<think>')
64
- if think_start != -1:
65
- state.answer += buffer[:think_start]
66
- state.in_think = True
67
- state.start_time = time.perf_counter()
68
- buffer = buffer[think_start + 7:]
69
- else:
70
- state.answer += buffer
71
- break
72
- else:
73
- think_end = buffer.find('</think>')
74
- if think_end != -1:
75
- state.thought += buffer[:think_end]
76
- state.in_think = False
77
- buffer = buffer[think_end + 8:]
78
- else:
79
- state.thought += buffer
80
- break
81
-
82
- elapsed = time.perf_counter() - state.start_time if state.in_think else 0
83
- return state, elapsed
84
-
85
- def format_response(state, elapsed):
86
- answer_part = state.answer.replace('<think>', '').replace('</think>', '')
87
- collapsible = []
88
-
89
- if state.thought or state.in_think:
90
- status = (f"🌀 Thinking for {elapsed:.0f} seconds"
91
- if state.in_think else f"✅ Thought for {elapsed:.0f} seconds")
92
- collapsible.append(
93
- f"<details open><summary>{status}</summary>\n\n<div class='thinking-container'>\n{state.thought}\n</div>\n</details>"
94
- )
95
-
96
- return collapsible, answer_part
97
-
98
- def generate_response(history, temperature, top_p, max_tokens, active_gen):
99
- messages = [{"role": "user", "content": history[-1][0]}]
100
- full_response = ""
101
- state = ParserState()
102
- last_update = 0
103
-
104
- try:
105
- stream = client.chat.completions.create(
106
- model="",
107
- messages=messages,
108
- temperature=temperature,
109
- top_p=top_p,
110
- max_tokens=max_tokens,
111
- stream=True
112
- )
113
-
114
- for chunk in stream:
115
- if not active_gen[0]:
116
- break
117
-
118
- if chunk.choices[0].delta.content:
119
- full_response += chunk.choices[0].delta.content
120
- state, elapsed = parse_response(full_response, state)
121
-
122
- collapsible, answer_part = format_response(state, elapsed)
123
- history[-1][1] = "\n\n".join(collapsible + [answer_part]) # Markdown-safe
124
- yield history
125
-
126
- # Final update
127
- state, elapsed = parse_response(full_response, state)
128
- collapsible, answer_part = format_response(state, elapsed)
129
- history[-1][1] = "\n\n".join(collapsible + [answer_part]) # Markdown-safe
130
- yield history
131
-
132
- except Exception as e:
133
- history[-1][1] = f"Error: {str(e)}"
134
- yield history
135
- finally:
136
- active_gen[0] = False
137
-
138
- with gr.Blocks(css=CSS) as demo:
139
- gr.Markdown(DESCRIPTION)
140
- active_gen = gr.State([False])
141
-
142
- chatbot = gr.Chatbot(
143
- elem_id="chatbot",
144
- height=500,
145
- show_label=False,
146
- render_markdown=True
147
- )
148
-
149
- with gr.Row():
150
- msg = gr.Textbox(
151
- label="Message",
152
- placeholder="Type your message...",
153
- container=False,
154
- scale=4
155
- )
156
- submit_btn = gr.Button("Send", variant='primary', scale=1)
157
-
158
- with gr.Column(scale=2):
159
- with gr.Row():
160
- clear_btn = gr.Button("Clear", variant='secondary')
161
- stop_btn = gr.Button("Stop", variant='stop')
162
-
163
- with gr.Accordion("Parameters", open=False):
164
- temperature = gr.Slider(minimum=0.1, maximum=1.5, value=0.6, label="Temperature")
165
- top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, label="Top-p")
166
- max_tokens = gr.Slider(minimum=2048, maximum=32768, value=4096, step=64, label="Max Tokens")
167
-
168
- gr.Examples(
169
- examples=[
170
- ["How many r's are in the word strawberry?"],
171
- ["Write 10 funny sentences that end in a fruit!"],
172
- ["Explain how RL for LLMs can be done!"]
173
- ],
174
- inputs=msg,
175
- label="Example Prompts"
176
- )
177
-
178
- submit_event = submit_btn.click(
179
- user, [msg, chatbot], [msg, chatbot], queue=False
180
- ).then(
181
- lambda: [True], outputs=active_gen
182
- ).then(
183
- generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
184
- )
185
-
186
- msg.submit(
187
- user, [msg, chatbot], [msg, chatbot], queue=False
188
- ).then(
189
- lambda: [True], outputs=active_gen
190
- ).then(
191
- generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
192
- )
193
-
194
- stop_btn.click(
195
- lambda: [False], None, active_gen, cancels=[submit_event]
196
- )
197
-
198
- clear_btn.click(lambda: None, None, chatbot, queue=False)
199
-
200
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ import time
2
+ import gradio as gr
3
+ from openai import OpenAI
4
+
5
+ def format_time(seconds_float):
6
+ total_seconds = int(round(seconds_float))
7
+ hours = total_seconds // 3600
8
+ remaining_seconds = total_seconds % 3600
9
+ minutes = remaining_seconds // 60
10
+ seconds = remaining_seconds % 60
11
+
12
+ if hours > 0:
13
+ return f"{hours}h {minutes}m {seconds}s"
14
+ elif minutes > 0:
15
+ return f"{minutes}m {seconds}s"
16
+ else:
17
+ return f"{seconds}s"
18
+
19
+ DESCRIPTION = '''
20
+ # Duplicate the space for free private inference.
21
+ ## DeepSeek-R1 Distill Qwen-32B Demo
22
+ A reasoning model trained using RL (Reinforcement Learning) that demonstrates structured reasoning capabilities.
23
+ '''
24
+
25
+ CSS = """
26
+ .spinner {
27
+ animation: spin 1s linear infinite;
28
+ display: inline-block;
29
+ margin-right: 8px;
30
+ }
31
+ @keyframes spin {
32
+ from { transform: rotate(0deg); }
33
+ to { transform: rotate(360deg); }
34
+ }
35
+ .thinking-summary {
36
+ cursor: pointer;
37
+ padding: 8px;
38
+ background: #f5f5f5;
39
+ border-radius: 4px;
40
+ margin: 4px 0;
41
+ }
42
+ .thought-content {
43
+ padding: 10px;
44
+ background: #f8f9fa;
45
+ border-radius: 4px;
46
+ margin: 5px 0;
47
+ }
48
+ .thinking-container {
49
+ border-left: 3px solid #e0e0e0;
50
+ padding-left: 10px;
51
+ margin: 8px 0;
52
+ }
53
+ details:not([open]) .thinking-container {
54
+ border-left-color: #4CAF50;
55
+ }
56
+ """
57
+
58
+ client = OpenAI(base_url="http://localhost:8080/v1", api_key="no-key-required")
59
+
60
+ def user(message, history):
61
+ return "", history + [[message, None]]
62
+
63
+ class ParserState:
64
+ __slots__ = ['answer', 'thought', 'in_think', 'start_time', 'last_pos', 'total_think_time']
65
+ def __init__(self):
66
+ self.answer = ""
67
+ self.thought = ""
68
+ self.in_think = False
69
+ self.start_time = 0
70
+ self.last_pos = 0
71
+ self.total_think_time = 0.0 # Track accumulated think time
72
+
73
+ def parse_response(text, state):
74
+ buffer = text[state.last_pos:]
75
+ state.last_pos = len(text)
76
+
77
+ while buffer:
78
+ if not state.in_think:
79
+ think_start = buffer.find('<think>')
80
+ if think_start != -1:
81
+ state.answer += buffer[:think_start]
82
+ state.in_think = True
83
+ state.start_time = time.perf_counter()
84
+ buffer = buffer[think_start + 7:]
85
+ else:
86
+ state.answer += buffer
87
+ break
88
+ else:
89
+ think_end = buffer.find('</think>')
90
+ if think_end != -1:
91
+ state.thought += buffer[:think_end]
92
+ # Calculate duration and accumulate
93
+ duration = time.perf_counter() - state.start_time
94
+ state.total_think_time += duration
95
+ state.in_think = False
96
+ buffer = buffer[think_end + 8:]
97
+ else:
98
+ state.thought += buffer
99
+ break
100
+
101
+ elapsed = time.perf_counter() - state.start_time if state.in_think else 0
102
+ return state, elapsed
103
+
104
+ def format_response(state, elapsed):
105
+ answer_part = state.answer.replace('<think>', '').replace('</think>', '')
106
+ collapsible = []
107
+
108
+ if state.thought or state.in_think:
109
+ if state.in_think:
110
+ # Ongoing think: total time = accumulated + current elapsed
111
+ total_elapsed = state.total_think_time + elapsed
112
+ formatted_time = format_time(total_elapsed)
113
+ status = f"🌀 Thinking for {formatted_time}"
114
+ else:
115
+ # Finished: show total accumulated time
116
+ formatted_time = format_time(state.total_think_time)
117
+ status = f"✅ Thought for {formatted_time}"
118
+ collapsible.append(
119
+ f"<details open><summary>{status}</summary>\n\n<div class='thinking-container'>\n{state.thought}\n</div>\n</details>"
120
+ )
121
+
122
+ return collapsible, answer_part
123
+
124
+ def generate_response(history, temperature, top_p, max_tokens, active_gen):
125
+ messages = [{"role": "user", "content": history[-1][0]}]
126
+ full_response = ""
127
+ state = ParserState()
128
+ last_update = 0
129
+
130
+ try:
131
+ stream = client.chat.completions.create(
132
+ model="",
133
+ messages=messages,
134
+ temperature=temperature,
135
+ top_p=top_p,
136
+ max_tokens=max_tokens,
137
+ stream=True
138
+ )
139
+
140
+ for chunk in stream:
141
+ if not active_gen[0]:
142
+ break
143
+
144
+ if chunk.choices[0].delta.content:
145
+ full_response += chunk.choices[0].delta.content
146
+ state, elapsed = parse_response(full_response, state)
147
+
148
+ collapsible, answer_part = format_response(state, elapsed)
149
+ history[-1][1] = "\n\n".join(collapsible + [answer_part])
150
+ yield history
151
+
152
+ # Final update to ensure all content is parsed
153
+ state, elapsed = parse_response(full_response, state)
154
+ collapsible, answer_part = format_response(state, elapsed)
155
+ history[-1][1] = "\n\n".join(collapsible + [answer_part])
156
+ yield history
157
+
158
+ except Exception as e:
159
+ history[-1][1] = f"Error: {str(e)}"
160
+ yield history
161
+ finally:
162
+ active_gen[0] = False
163
+
164
+ with gr.Blocks(css=CSS) as demo:
165
+ gr.Markdown(DESCRIPTION)
166
+ active_gen = gr.State([False])
167
+
168
+ chatbot = gr.Chatbot(
169
+ elem_id="chatbot",
170
+ height=500,
171
+ show_label=False,
172
+ render_markdown=True
173
+ )
174
+
175
+ with gr.Row():
176
+ msg = gr.Textbox(
177
+ label="Message",
178
+ placeholder="Type your message...",
179
+ container=False,
180
+ scale=4
181
+ )
182
+ submit_btn = gr.Button("Send", variant='primary', scale=1)
183
+
184
+ with gr.Column(scale=2):
185
+ with gr.Row():
186
+ clear_btn = gr.Button("Clear", variant='secondary')
187
+ stop_btn = gr.Button("Stop", variant='stop')
188
+
189
+ with gr.Accordion("Parameters", open=False):
190
+ temperature = gr.Slider(minimum=0.1, maximum=1.5, value=0.6, label="Temperature")
191
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, label="Top-p")
192
+ max_tokens = gr.Slider(minimum=2048, maximum=32768, value=4096, step=64, label="Max Tokens")
193
+
194
+ gr.Examples(
195
+ examples=[
196
+ ["How many r's are in the word strawberry?"],
197
+ ["Write 10 funny sentences that end in a fruit!"],
198
+ ["Let's play Tic Tac Toe, I'll start and we'll take turns: \nRow 1: -|-|-\nRow 2: -|-|-\nRow 3: -|-|-\nYour Turn!"]
199
+ ],
200
+ inputs=msg,
201
+ label="Example Prompts"
202
+ )
203
+
204
+ submit_event = submit_btn.click(
205
+ user, [msg, chatbot], [msg, chatbot], queue=False
206
+ ).then(
207
+ lambda: [True], outputs=active_gen
208
+ ).then(
209
+ generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
210
+ )
211
+
212
+ msg.submit(
213
+ user, [msg, chatbot], [msg, chatbot], queue=False
214
+ ).then(
215
+ lambda: [True], outputs=active_gen
216
+ ).then(
217
+ generate_response, [chatbot, temperature, top_p, max_tokens, active_gen], chatbot
218
+ )
219
+
220
+ stop_btn.click(
221
+ lambda: [False], None, active_gen, cancels=[submit_event]
222
+ )
223
+
224
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
225
+
226
+ if __name__ == "__main__":
227
  demo.launch(server_name="0.0.0.0", server_port=7860)