finalf0 commited on
Commit
1d3dde2
1 Parent(s): 9722d74

support streaming output

Browse files
Files changed (1) hide show
  1. app.py +98 -62
app.py CHANGED
@@ -134,29 +134,33 @@ def create_component(params, comp='Slider'):
134
 
135
  @spaces.GPU(duration=120)
136
  def chat(img, msgs, ctx, params=None, vision_hidden_states=None):
137
- default_params = {"num_beams":3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
138
  if params is None:
139
  params = default_params
140
  if img is None:
141
- return -1, "Error, invalid image, please upload a new image", None, None
142
- try:
143
- image = img.convert('RGB')
144
- answer = model.chat(
145
- image=image,
146
- msgs=msgs,
147
- tokenizer=tokenizer,
148
- **params
149
- )
150
- res = re.sub(r'(<box>.*</box>)', '', answer)
151
- res = res.replace('<ref>', '')
152
- res = res.replace('</ref>', '')
153
- res = res.replace('<box>', '')
154
- answer = res.replace('</box>', '')
155
- return -1, answer, None, None
156
- except Exception as err:
157
- print(err)
158
- traceback.print_exc()
159
- return -1, ERROR_MSG, None, None
 
 
 
 
160
 
161
 
162
  def upload_img(image, _chatbot, _app_session):
@@ -169,46 +173,51 @@ def upload_img(image, _chatbot, _app_session):
169
  return _chatbot, _app_session
170
 
171
 
172
- def respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
 
 
173
  if _app_cfg.get('ctx', None) is None:
174
- _chat_bot.append((_question, 'Please upload an image to start'))
175
- return '', _chat_bot, _app_cfg
176
-
177
- _context = _app_cfg['ctx'].copy()
178
- if _context:
179
- _context.append({"role": "user", "content": _question})
180
  else:
181
- _context = [{"role": "user", "content": _question}]
182
- print('<User>:', _question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
 
184
- if params_form == 'Beam Search':
185
- params = {
186
- 'sampling': False,
187
- 'num_beams': num_beams,
188
- 'repetition_penalty': repetition_penalty,
189
- "max_new_tokens": 896
190
- }
191
- else:
192
- params = {
193
- 'sampling': True,
194
- 'top_p': top_p,
195
- 'top_k': top_k,
196
- 'temperature': temperature,
197
- 'repetition_penalty': repetition_penalty_2,
198
- "max_new_tokens": 896
199
- }
200
- code, _answer, _, sts = chat(_app_cfg['img'], _context, None, params)
201
- print('<Assistant>:', _answer)
202
 
203
- _context.append({"role": "assistant", "content": _answer})
204
- _chat_bot.append((_question, _answer))
205
- if code == 0:
206
- _app_cfg['ctx']=_context
207
- _app_cfg['sts']=sts
208
  return '', _chat_bot, _app_cfg
209
 
210
 
211
- def regenerate_button_clicked(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
212
  if len(_chat_bot) <= 1:
213
  _chat_bot.append(('Regenerate', 'No question for regeneration.'))
214
  return '', _chat_bot, _app_cfg
@@ -218,9 +227,18 @@ def regenerate_button_clicked(_question, _chat_bot, _app_cfg, params_form, num_b
218
  _question = _chat_bot[-1][0]
219
  _chat_bot = _chat_bot[:-1]
220
  _app_cfg['ctx'] = _app_cfg['ctx'][:-2]
221
- return respond(_question, _chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature)
 
222
 
223
 
 
 
 
 
 
 
 
 
224
 
225
  with gr.Blocks() as demo:
226
  with gr.Row():
@@ -235,25 +253,43 @@ with gr.Blocks() as demo:
235
  temperature = create_component(temperature_slider)
236
  repetition_penalty_2 = create_component(repetition_penalty_slider2)
237
  regenerate = create_component({'value': 'Regenerate'}, comp='Button')
 
238
  with gr.Column(scale=3, min_width=500):
239
  app_session = gr.State({'sts':None,'ctx':None,'img':None})
240
  bt_pic = gr.Image(label="Upload an image to start")
241
  chat_bot = gr.Chatbot(label=f"Chat with {model_name}")
242
  txt_message = gr.Textbox(label="Input text")
243
 
244
- regenerate.click(
245
- regenerate_button_clicked,
246
- [txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
247
- [txt_message, chat_bot, app_session]
 
248
  )
249
  txt_message.submit(
250
- respond,
251
- [txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
252
- [txt_message, chat_bot, app_session]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  )
254
  bt_pic.upload(lambda: None, None, chat_bot, queue=False).then(upload_img, inputs=[bt_pic,chat_bot,app_session], outputs=[chat_bot,app_session])
255
 
256
  # launch
257
  #demo.launch(share=False, debug=True, show_api=False, server_port=8080, server_name="0.0.0.0")
 
258
  demo.launch()
259
-
 
134
 
135
  @spaces.GPU(duration=120)
136
  def chat(img, msgs, ctx, params=None, vision_hidden_states=None):
137
+ default_params = {"stream": False, "sampling": False, "num_beams":3, "repetition_penalty": 1.2, "max_new_tokens": 1024}
138
  if params is None:
139
  params = default_params
140
  if img is None:
141
+ yield "Error, invalid image, please upload a new image"
142
+ else:
143
+ try:
144
+ image = img.convert('RGB')
145
+ answer = model.chat(
146
+ image=image,
147
+ msgs=msgs,
148
+ tokenizer=tokenizer,
149
+ **params
150
+ )
151
+ # if params['stream'] is False:
152
+ # res = re.sub(r'(<box>.*</box>)', '', answer)
153
+ # res = res.replace('<ref>', '')
154
+ # res = res.replace('</ref>', '')
155
+ # res = res.replace('<box>', '')
156
+ # answer = res.replace('</box>', '')
157
+ # else:
158
+ for char in answer:
159
+ yield char
160
+ except Exception as err:
161
+ print(err)
162
+ traceback.print_exc()
163
+ yield ERROR_MSG
164
 
165
 
166
  def upload_img(image, _chatbot, _app_session):
 
173
  return _chatbot, _app_session
174
 
175
 
176
+ def respond(_chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature):
177
+ _question = _chat_bot[-1][0]
178
+ print('<Question>:', _question)
179
  if _app_cfg.get('ctx', None) is None:
180
+ _chat_bot[-1][1] = 'Please upload an image to start'
181
+ yield (_chat_bot, _app_cfg)
 
 
 
 
182
  else:
183
+ _context = _app_cfg['ctx'].copy()
184
+ if _context:
185
+ _context.append({"role": "user", "content": _question})
186
+ else:
187
+ _context = [{"role": "user", "content": _question}]
188
+ if params_form == 'Beam Search':
189
+ params = {
190
+ 'sampling': False,
191
+ 'stream': False,
192
+ 'num_beams': num_beams,
193
+ 'repetition_penalty': repetition_penalty,
194
+ "max_new_tokens": 896
195
+ }
196
+ else:
197
+ params = {
198
+ 'sampling': True,
199
+ 'stream': True,
200
+ 'top_p': top_p,
201
+ 'top_k': top_k,
202
+ 'temperature': temperature,
203
+ 'repetition_penalty': repetition_penalty_2,
204
+ "max_new_tokens": 896
205
+ }
206
+
207
+ gen = chat(_app_cfg['img'], _context, None, params)
208
+ _chat_bot[-1][1] = ""
209
+ for _char in gen:
210
+ _chat_bot[-1][1] += _char
211
+ _context[-1]["content"] += _char
212
+ yield (_chat_bot, _app_cfg)
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
+ def request(_question, _chat_bot, _app_cfg):
216
+ _chat_bot.append((_question, None))
 
 
 
217
  return '', _chat_bot, _app_cfg
218
 
219
 
220
+ def regenerate_button_clicked(_question, _chat_bot, _app_cfg):
221
  if len(_chat_bot) <= 1:
222
  _chat_bot.append(('Regenerate', 'No question for regeneration.'))
223
  return '', _chat_bot, _app_cfg
 
227
  _question = _chat_bot[-1][0]
228
  _chat_bot = _chat_bot[:-1]
229
  _app_cfg['ctx'] = _app_cfg['ctx'][:-2]
230
+ return request(_question, _chat_bot, _app_cfg)
231
+ # return respond(_chat_bot, _app_cfg, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature)
232
 
233
 
234
+ def clear_button_clicked(_question, _chat_bot, _app_cfg, _bt_pic):
235
+ _chat_bot.clear()
236
+ _app_cfg['sts'] = None
237
+ _app_cfg['ctx'] = None
238
+ _app_cfg['img'] = None
239
+ _bt_pic = None
240
+ return '', _chat_bot, _app_cfg, _bt_pic
241
+
242
 
243
  with gr.Blocks() as demo:
244
  with gr.Row():
 
253
  temperature = create_component(temperature_slider)
254
  repetition_penalty_2 = create_component(repetition_penalty_slider2)
255
  regenerate = create_component({'value': 'Regenerate'}, comp='Button')
256
+ clear = create_component({'value': 'Clear'}, comp='Button')
257
  with gr.Column(scale=3, min_width=500):
258
  app_session = gr.State({'sts':None,'ctx':None,'img':None})
259
  bt_pic = gr.Image(label="Upload an image to start")
260
  chat_bot = gr.Chatbot(label=f"Chat with {model_name}")
261
  txt_message = gr.Textbox(label="Input text")
262
 
263
+ clear.click(
264
+ clear_button_clicked,
265
+ [txt_message, chat_bot, app_session, bt_pic],
266
+ [txt_message, chat_bot, app_session, bt_pic],
267
+ queue=False
268
  )
269
  txt_message.submit(
270
+ request,
271
+ #[txt_message, chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
272
+ [txt_message, chat_bot, app_session],
273
+ [txt_message, chat_bot, app_session],
274
+ queue=False
275
+ ).then(
276
+ respond,
277
+ [chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
278
+ [chat_bot, app_session]
279
+ )
280
+ regenerate.click(
281
+ regenerate_button_clicked,
282
+ [txt_message, chat_bot, app_session],
283
+ [txt_message, chat_bot, app_session],
284
+ queue=False
285
+ ).then(
286
+ respond,
287
+ [chat_bot, app_session, params_form, num_beams, repetition_penalty, repetition_penalty_2, top_p, top_k, temperature],
288
+ [chat_bot, app_session]
289
  )
290
  bt_pic.upload(lambda: None, None, chat_bot, queue=False).then(upload_img, inputs=[bt_pic,chat_bot,app_session], outputs=[chat_bot,app_session])
291
 
292
  # launch
293
  #demo.launch(share=False, debug=True, show_api=False, server_port=8080, server_name="0.0.0.0")
294
+ demo.queue()
295
  demo.launch()