AnwenHu commited on
Commit
a845a91
1 Parent(s): 1c117fc

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +428 -0
app.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import datetime
3
+ import json
4
+ import os
5
+ import time
6
+
7
+ import gradio as gr
8
+ import requests
9
+
10
+ from mplug_docowl.conversation import (default_conversation, conv_templates,
11
+ SeparatorStyle)
12
+ from mplug_docowl.constants import LOGDIR
13
+ from mplug_docowl.utils import (build_logger, server_error_msg,
14
+ violates_moderation, moderation_msg)
15
+ from model_worker import ModelWorker
16
+ import hashlib
17
+
18
+ from huggingface_hub import snapshot_download
19
+ model_dir = snapshot_download('mPLUG/DocOwl1.5-Omni', cache_dir='./')
20
+
21
+ print(os.listdir('./'))
22
+
23
+
24
+ logger = build_logger("gradio_web_server_local", "gradio_web_server_local.log")
25
+
26
+ headers = {"User-Agent": "mPLUG-DocOwl1.5 Client"}
27
+
28
+ no_change_btn = gr.Button.update()
29
+ enable_btn = gr.Button.update(interactive=True)
30
+ disable_btn = gr.Button.update(interactive=False)
31
+
32
+ def get_conv_log_filename():
33
+ t = datetime.datetime.now()
34
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
35
+ return name
36
+
37
+ get_window_url_params = """
38
+ function() {
39
+ const params = new URLSearchParams(window.location.search);
40
+ url_params = Object.fromEntries(params);
41
+ console.log(url_params);
42
+ return url_params;
43
+ }
44
+ """
45
+
46
+
47
+ def load_demo(url_params, request: gr.Request):
48
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
49
+ state = default_conversation.copy()
50
+ return state
51
+
52
+
53
+ def vote_last_response(state, vote_type, request: gr.Request):
54
+ with open(get_conv_log_filename(), "a") as fout:
55
+ data = {
56
+ "tstamp": round(time.time(), 4),
57
+ "type": vote_type,
58
+ "state": state.dict(),
59
+ "ip": request.client.host,
60
+ }
61
+ fout.write(json.dumps(data) + "\n")
62
+
63
+
64
+ def upvote_last_response(state, request: gr.Request):
65
+ logger.info(f"upvote. ip: {request.client.host}")
66
+ vote_last_response(state, "upvote", request)
67
+ return ("",) + (disable_btn,) * 3
68
+
69
+
70
+ def downvote_last_response(state, request: gr.Request):
71
+ logger.info(f"downvote. ip: {request.client.host}")
72
+ vote_last_response(state, "downvote", request)
73
+ return ("",) + (disable_btn,) * 3
74
+
75
+
76
+ def flag_last_response(state, request: gr.Request):
77
+ logger.info(f"flag. ip: {request.client.host}")
78
+ vote_last_response(state, "flag", request)
79
+ return ("",) + (disable_btn,) * 3
80
+
81
+
82
+ def regenerate(state, image_process_mode, request: gr.Request):
83
+ logger.info(f"regenerate. ip: {request.client.host}")
84
+ state.messages[-1][-1] = None
85
+ prev_human_msg = state.messages[-2]
86
+ if type(prev_human_msg[1]) in (tuple, list):
87
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
88
+ state.skip_next = False
89
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
90
+
91
+
92
+ def clear_history(request: gr.Request):
93
+ logger.info(f"clear_history. ip: {request.client.host}")
94
+ state = default_conversation.copy()
95
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
96
+
97
+
98
+ def add_text(state, text, image, image_process_mode, request: gr.Request):
99
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
100
+ if len(text) <= 0 and image is None:
101
+ state.skip_next = True
102
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
103
+ if args.moderate:
104
+ flagged = violates_moderation(text)
105
+ if flagged:
106
+ state.skip_next = True
107
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
108
+ no_change_btn,) * 5
109
+
110
+ text = text[:3584] # Hard cut-off
111
+ if image is not None:
112
+ text = text[:3500] # Hard cut-off for images
113
+ if '<|image|>' not in text:
114
+ text = '<|image|>' + text
115
+ text = (text, image, image_process_mode)
116
+ if len(state.get_images(return_pil=True)) > 0:
117
+ state = default_conversation.copy()
118
+ state.append_message(state.roles[0], text)
119
+ state.append_message(state.roles[1], None)
120
+ state.skip_next = False
121
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
122
+
123
+
124
+ def http_bot(state, temperature, top_p, max_new_tokens, request: gr.Request):
125
+ logger.info(f"http_bot. ip: {request.client.host}")
126
+ start_tstamp = time.time()
127
+
128
+ if state.skip_next:
129
+ # This generate call is skipped due to invalid inputs
130
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
131
+ return
132
+
133
+ if len(state.messages) == state.offset + 2:
134
+ # First round of conversation
135
+ template_name = "mplug_owl2"
136
+ new_state = conv_templates[template_name].copy()
137
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
138
+ new_state.append_message(new_state.roles[1], None)
139
+ state = new_state
140
+
141
+ # Construct prompt
142
+ prompt = state.get_prompt()
143
+
144
+ all_images = state.get_images(return_pil=True)
145
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
146
+ for image, hash in zip(all_images, all_image_hash):
147
+ t = datetime.datetime.now()
148
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
149
+ if not os.path.isfile(filename):
150
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
151
+ image.save(filename)
152
+
153
+ # Make requests
154
+ pload = {
155
+ "prompt": prompt,
156
+ "temperature": float(temperature),
157
+ "top_p": float(top_p),
158
+ "max_new_tokens": min(int(max_new_tokens), 2048),
159
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
160
+ "images": f'List of {len(state.get_images())} images: {all_image_hash}',
161
+ }
162
+
163
+ logger.info(f"==== request ====\n{pload}")
164
+
165
+ pload['images'] = state.get_images()
166
+
167
+ state.messages[-1][-1] = "▌"
168
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
169
+
170
+ try:
171
+ # Stream output
172
+ # response = requests.post(worker_addr + "/worker_generate_stream",
173
+ # headers=headers, json=pload, stream=True, timeout=10)
174
+ # for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
175
+ response = model.generate_stream_gate(pload)
176
+ # print('response:', response)
177
+ for chunk in response:
178
+ if chunk:
179
+ print('chunk:', chunk.decode())
180
+ data = json.loads(chunk.decode())
181
+ if data["error_code"] == 0:
182
+ output = data["text"][len(prompt):].strip()
183
+ state.messages[-1][-1] = output + "▌"
184
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
185
+ else:
186
+ output = data["text"] + f" (error_code: {data['error_code']})"
187
+ state.messages[-1][-1] = output
188
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
189
+ return
190
+ time.sleep(0.03)
191
+ except requests.exceptions.RequestException as e:
192
+ state.messages[-1][-1] = server_error_msg
193
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
194
+ return
195
+
196
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
197
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
198
+
199
+ finish_tstamp = time.time()
200
+ logger.info(f"{output}")
201
+
202
+ with open(get_conv_log_filename(), "a") as fout:
203
+ data = {
204
+ "tstamp": round(finish_tstamp, 4),
205
+ "type": "chat",
206
+ "start": round(start_tstamp, 4),
207
+ "finish": round(start_tstamp, 4),
208
+ "state": state.dict(),
209
+ "images": all_image_hash,
210
+ "ip": request.client.host,
211
+ }
212
+ fout.write(json.dumps(data) + "\n")
213
+
214
+
215
+ title_markdown = ("""
216
+ <h1 align="center"><a href="https://github.com/X-PLUG/mPLUG-DocOwl"><img src="https://github.com/X-PLUG/mPLUG-DocOwl/raw/main/assets/mPLUG_new1.png", alt="mPLUG-DocOwl" border="0" style="margin: 0 auto; height: 200px;" /></a> </h1>
217
+
218
+ <h2 align="center"> mPLUG-DocOwl1.5: Unified Stucture Learning for OCR-free Document Understanding</h2>
219
+
220
+ <h5 align="center"> If you like our project, please give us a star ✨ on Github for latest update. </h2>
221
+
222
+ <h5 align="center"> Note: This demo is temporarily only supported for English Document Understanding. The Chinese-and-English model is under development.</h2>
223
+
224
+ <h5 align="center"> 注意: 当前Demo只支持英文文档理解, 中英模型正在全力开发中。</h2>
225
+
226
+ <h5 align="center"> Note: If you want a detailed explanation, please remember to add a prompot "Give a detailed explanation." after the question.</h2>
227
+
228
+ <h5 align="center"> 注意: 如果你想要详细的推理解释, 请在问题后面加上“Give a detailed explanation.”。</h2>
229
+
230
+ <h5 align="center"> Note: the Line break are temporarily removed by the web code, we will fix this bug soon</h2>
231
+
232
+ <h5 align="center"> 注意: 目前换行符被前端代码移除了, 我们会尽快修复这一问题</h2>
233
+
234
+
235
+
236
+
237
+
238
+ <div align="center">
239
+ <div style="display:flex; gap: 0.25rem;" align="center">
240
+ <a href='https://github.com/X-PLUG/mPLUG-DocOwl'><img src='https://img.shields.io/badge/Github-Code-blue'></a>
241
+ <a href="https://arxiv.org/abs/2403.12895"><img src="https://img.shields.io/badge/Arxiv-2403.12895-red"></a>
242
+ <a href='https://github.com/X-PLUG/mPLUG-DocOwl/stargazers'><img src='https://img.shields.io/github/stars/X-PLUG/mPLUG-DocOwl.svg?style=social'></a>
243
+ </div>
244
+ </div>
245
+
246
+ """)
247
+
248
+
249
+ tos_markdown = ("""
250
+ ### Terms of use
251
+ By using this service, users are required to agree to the following terms:
252
+ The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research.
253
+ Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
254
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
255
+ """)
256
+
257
+
258
+ learn_more_markdown = ("""
259
+ ### License
260
+ The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation.
261
+ """)
262
+
263
+ block_css = """
264
+
265
+ #buttons button {
266
+ min-width: min(120px,100%);
267
+ }
268
+
269
+ """
270
+
271
+ def build_demo(embed_mode):
272
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
273
+ with gr.Blocks(title="mPLUG-DocOwl1.5", theme=gr.themes.Default(), css=block_css) as demo:
274
+ state = gr.State()
275
+
276
+ if not embed_mode:
277
+ gr.Markdown(title_markdown)
278
+
279
+ with gr.Row():
280
+ with gr.Column(scale=3):
281
+ imagebox = gr.Image(type="pil")
282
+ image_process_mode = gr.Radio(
283
+ ["Crop", "Resize", "Pad", "Default"],
284
+ value="Default",
285
+ label="Preprocess for non-square image", visible=False)
286
+
287
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
288
+ gr.Examples(examples=[
289
+ [f"{cur_dir}/examples/cvpr.png", "what is this schedule for? Give detailed explanation."],
290
+ [f"{cur_dir}/examples/fflw0023_1.png", "Parse texts in the image."],
291
+ [f"{cur_dir}/examples/col_type_46452.jpg", "Convert the table into Markdown format."],
292
+ [f"{cur_dir}/examples/col_type_177029.jpg", "What is unusual about this image? Provide detailed explanation."],
293
+ [f"{cur_dir}/examples/multi_col_60204.png", "Convert the illustration into Markdown language."],
294
+ [f"{cur_dir}/examples/Rebecca_(1939_poster)_Small.jpeg", "What is the name of the movie in the poster? Provide detailed explanation."],
295
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image? Provide detailed explanation."],
296
+ ], inputs=[imagebox, textbox])
297
+
298
+ with gr.Accordion("Parameters", open=True) as parameter_row:
299
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.1, interactive=True, label="Temperature",)
300
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
301
+ max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
302
+
303
+ with gr.Column(scale=8):
304
+ chatbot = gr.Chatbot(elem_id="Chatbot", label="mPLUG-DocOwl1.5 Chatbot", height=600)
305
+ with gr.Row():
306
+ with gr.Column(scale=8):
307
+ textbox.render()
308
+ with gr.Column(scale=1, min_width=50):
309
+ submit_btn = gr.Button(value="Send", variant="primary")
310
+ with gr.Row(elem_id="buttons") as button_row:
311
+ upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
312
+ downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
313
+ flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
314
+ #stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
315
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
316
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
317
+
318
+ if not embed_mode:
319
+ gr.Markdown(tos_markdown)
320
+ gr.Markdown(learn_more_markdown)
321
+ url_params = gr.JSON(visible=False)
322
+
323
+ # Register listeners
324
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
325
+ upvote_btn.click(
326
+ upvote_last_response,
327
+ state,
328
+ [textbox, upvote_btn, downvote_btn, flag_btn],
329
+ queue=False
330
+ )
331
+ downvote_btn.click(
332
+ downvote_last_response,
333
+ state,
334
+ [textbox, upvote_btn, downvote_btn, flag_btn],
335
+ queue=False
336
+ )
337
+ flag_btn.click(
338
+ flag_last_response,
339
+ state,
340
+ [textbox, upvote_btn, downvote_btn, flag_btn],
341
+ queue=False
342
+ )
343
+
344
+ regenerate_btn.click(
345
+ regenerate,
346
+ [state, image_process_mode],
347
+ [state, chatbot, textbox, imagebox] + btn_list,
348
+ queue=False
349
+ ).then(
350
+ http_bot,
351
+ [state, temperature, top_p, max_output_tokens],
352
+ [state, chatbot] + btn_list
353
+ )
354
+
355
+ clear_btn.click(
356
+ clear_history,
357
+ None,
358
+ [state, chatbot, textbox, imagebox] + btn_list,
359
+ queue=False
360
+ )
361
+
362
+ textbox.submit(
363
+ add_text,
364
+ [state, textbox, imagebox, image_process_mode],
365
+ [state, chatbot, textbox, imagebox] + btn_list,
366
+ queue=False
367
+ ).then(
368
+ http_bot,
369
+ [state, temperature, top_p, max_output_tokens],
370
+ [state, chatbot] + btn_list
371
+ )
372
+
373
+ submit_btn.click(
374
+ add_text,
375
+ [state, textbox, imagebox, image_process_mode],
376
+ [state, chatbot, textbox, imagebox] + btn_list,
377
+ queue=False
378
+ ).then(
379
+ http_bot,
380
+ [state, temperature, top_p, max_output_tokens],
381
+ [state, chatbot] + btn_list
382
+ )
383
+
384
+ demo.load(
385
+ load_demo,
386
+ [url_params],
387
+ state,
388
+ _js=get_window_url_params,
389
+ queue=False
390
+ )
391
+
392
+ return demo
393
+
394
+
395
+ if __name__ == "__main__":
396
+ parser = argparse.ArgumentParser()
397
+ parser.add_argument("--host", type=str, default="0.0.0.0")
398
+ parser.add_argument("--port", type=int)
399
+ parser.add_argument("--concurrency-count", type=int, default=10)
400
+ parser.add_argument("--model-list-mode", type=str, default="once",
401
+ choices=["once", "reload"])
402
+ parser.add_argument("--model-path", type=str, default="mPLUG/DocOwl1.5-Omni")
403
+ parser.add_argument("--device", type=str, default="cuda")
404
+ parser.add_argument("--load-8bit", action="store_true")
405
+ parser.add_argument("--load-4bit", action="store_true")
406
+ parser.add_argument("--moderate", action="store_true")
407
+ parser.add_argument("--embed", action="store_true")
408
+ args = parser.parse_args()
409
+ logger.info(f"args: {args}")
410
+
411
+ model = ModelWorker(args.model_path, None, None,
412
+ resolution=448,
413
+ anchors='grid_9',
414
+ add_global_img=True,
415
+ load_8bit=args.load_8bit,
416
+ load_4bit=args.load_4bit,
417
+ device=args.device)
418
+
419
+ logger.info(args)
420
+ demo = build_demo(args.embed)
421
+ demo.queue(
422
+ concurrency_count=args.concurrency_count,
423
+ api_open=False
424
+ ).launch(
425
+ server_name=args.host,
426
+ server_port=args.port,
427
+ share=False
428
+ )