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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import datetime
3
+ import json
4
+ import os
5
+ import time
6
+ from PIL import Image
7
+ import gradio as gr
8
+ import requests
9
+
10
+ from llava.conversation import (default_conversation, conv_templates,
11
+ SeparatorStyle)
12
+ from llava.constants import LOGDIR
13
+ from llava.utils import (build_logger, server_error_msg,
14
+ violates_moderation, moderation_msg)
15
+ import hashlib
16
+
17
+
18
+ logger = build_logger("gradio_web_server", "gradio_web_server.log")
19
+
20
+ headers = {"User-Agent": "LLaVA Client"}
21
+
22
+ no_change_btn = gr.Button.update()
23
+ enable_btn = gr.Button.update(interactive=True)
24
+ disable_btn = gr.Button.update(interactive=False)
25
+
26
+ priority = {
27
+ "vicuna-13b": "aaaaaaa",
28
+ "koala-13b": "aaaaaab",
29
+ }
30
+
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
+
38
+ def get_model_list():
39
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
40
+ assert ret.status_code == 200
41
+ ret = requests.post(args.controller_url + "/list_models")
42
+ models = ret.json()["models"]
43
+ models.sort(key=lambda x: priority.get(x, x))
44
+ logger.info(f"Models: {models}")
45
+ return models
46
+
47
+
48
+ get_window_url_params = """
49
+ function() {
50
+ const params = new URLSearchParams(window.location.search);
51
+ url_params = Object.fromEntries(params);
52
+ console.log(url_params);
53
+ return url_params;
54
+ }
55
+ """
56
+
57
+
58
+ def load_demo(url_params, request: gr.Request):
59
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
60
+
61
+ dropdown_update = gr.Dropdown.update(visible=True)
62
+ if "model" in url_params:
63
+ model = url_params["model"]
64
+ if model in models:
65
+ dropdown_update = gr.Dropdown.update(
66
+ value=model, visible=True)
67
+
68
+ state = default_conversation.copy()
69
+ return state, dropdown_update
70
+
71
+
72
+ def load_demo_refresh_model_list(request: gr.Request):
73
+ logger.info(f"load_demo. ip: {request.client.host}")
74
+ models = get_model_list()
75
+ state = default_conversation.copy()
76
+ dropdown_update = gr.Dropdown.update(
77
+ choices=models,
78
+ value=models[0] if len(models) > 0 else ""
79
+ )
80
+ return state, dropdown_update
81
+
82
+
83
+ def vote_last_response(state, vote_type, model_selector, request: gr.Request):
84
+ with open(get_conv_log_filename(), "a") as fout:
85
+ data = {
86
+ "tstamp": round(time.time(), 4),
87
+ "type": vote_type,
88
+ "model": model_selector,
89
+ "state": state.dict(),
90
+ "ip": request.client.host,
91
+ }
92
+ fout.write(json.dumps(data) + "\n")
93
+
94
+
95
+ def upvote_last_response(state, model_selector, request: gr.Request):
96
+ logger.info(f"upvote. ip: {request.client.host}")
97
+ vote_last_response(state, "upvote", model_selector, request)
98
+ return ("",) + (disable_btn,) * 3
99
+
100
+
101
+ def downvote_last_response(state, model_selector, request: gr.Request):
102
+ logger.info(f"downvote. ip: {request.client.host}")
103
+ vote_last_response(state, "downvote", model_selector, request)
104
+ return ("",) + (disable_btn,) * 3
105
+
106
+
107
+ def flag_last_response(state, model_selector, request: gr.Request):
108
+ logger.info(f"flag. ip: {request.client.host}")
109
+ vote_last_response(state, "flag", model_selector, request)
110
+ return ("",) + (disable_btn,) * 3
111
+
112
+
113
+ def regenerate(state, image_process_mode, request: gr.Request):
114
+ logger.info(f"regenerate. ip: {request.client.host}")
115
+ state.messages[-1][-1] = None
116
+ prev_human_msg = state.messages[-2]
117
+ if type(prev_human_msg[1]) in (tuple, list):
118
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
119
+ state.skip_next = False
120
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
121
+
122
+
123
+ def clear_history(request: gr.Request):
124
+ logger.info(f"clear_history. ip: {request.client.host}")
125
+ state = default_conversation.copy()
126
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
127
+
128
+
129
+
130
+ def add_text(state, text, image, image_process_mode, request: gr.Request):
131
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
132
+ if len(text) <= 0 and image is None:
133
+ state.skip_next = True
134
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
135
+ if args.moderate:
136
+ flagged = violates_moderation(text)
137
+ if flagged:
138
+ state.skip_next = True
139
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
140
+ no_change_btn,) * 5
141
+
142
+ text = text[:1536] # Hard cut-off
143
+ if image is not None:
144
+ text = text[:1200] # Hard cut-off for images
145
+ if '<image>' not in text:
146
+ # text = '<Image><image></Image>' + text
147
+ text = text + '\n<image>'
148
+ text = (text, image, image_process_mode)
149
+ if len(state.get_images(return_pil=True)) > 0:
150
+ state = default_conversation.copy()
151
+ state.append_message(state.roles[0], text)
152
+ state.append_message(state.roles[1], None)
153
+ state.skip_next = False
154
+ return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5
155
+
156
+
157
+ def batch_process_images(folder_path, textbox, model_selector, temperature, top_p, max_output_tokens, request: gr.Request):
158
+ print("calling batch_process_images")
159
+
160
+ for filename in os.listdir(folder_path):
161
+ if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
162
+ image_path = os.path.join(folder_path, filename)
163
+ with Image.open(image_path) as image:
164
+ state = default_conversation.copy()
165
+ state, _, _, _, _, _, _, _, _ = add_text(state, textbox, image, "Default", request)
166
+
167
+ # Call http_bot and iterate over the generator
168
+ response_text = ""
169
+ for state_update in http_bot(state, model_selector, temperature, top_p, max_output_tokens, request):
170
+ # Update state and extract response text
171
+ state, chatbot_output, *_ = state_update
172
+ response_text = chatbot_output
173
+
174
+ # Save the final response to a file
175
+ try:
176
+ with open(os.path.splitext(image_path)[0] + '.txt', 'w') as f:
177
+ f.write(response_text[0][1])
178
+ except Exception as e:
179
+ print(f"An error occurred: {e}")
180
+
181
+ return "Batch processing completed."
182
+
183
+
184
+
185
+
186
+ def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
187
+ logger.info(f"http_bot. ip: {request.client.host}")
188
+ print(f"model_selector {model_selector}")
189
+ start_tstamp = time.time()
190
+ model_name = model_selector
191
+
192
+ if state.skip_next:
193
+ # This generate call is skipped due to invalid inputs
194
+ print("invalid input state.skip_next")
195
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
196
+ return
197
+
198
+ if len(state.messages) == state.offset + 2:
199
+ # First round of conversation
200
+ if "llava" in model_name.lower():
201
+ if 'llama-2' in model_name.lower():
202
+ template_name = "llava_llama_2"
203
+ elif "v1" in model_name.lower():
204
+ if 'mmtag' in model_name.lower():
205
+ template_name = "v1_mmtag"
206
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
207
+ template_name = "v1_mmtag"
208
+ else:
209
+ template_name = "llava_v1"
210
+ elif "mpt" in model_name.lower():
211
+ template_name = "mpt"
212
+ else:
213
+ if 'mmtag' in model_name.lower():
214
+ template_name = "v0_mmtag"
215
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
216
+ template_name = "v0_mmtag"
217
+ else:
218
+ template_name = "llava_v0"
219
+ elif "mpt" in model_name:
220
+ template_name = "mpt_text"
221
+ elif "llama-2" in model_name:
222
+ template_name = "llama_2"
223
+ else:
224
+ template_name = "vicuna_v1"
225
+ print(f"template_name {template_name}")
226
+ new_state = conv_templates[template_name].copy()
227
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
228
+ new_state.append_message(new_state.roles[1], None)
229
+ state = new_state
230
+
231
+ # Query worker address
232
+ controller_url = args.controller_url
233
+ ret = requests.post(controller_url + "/get_worker_address",
234
+ json={"model": model_name})
235
+ worker_addr = ret.json()["address"]
236
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
237
+
238
+ # No available worker
239
+ if worker_addr == "":
240
+ state.messages[-1][-1] = server_error_msg
241
+ print(f"error No available worker")
242
+ yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
243
+ return
244
+
245
+ # Construct prompt
246
+ prompt = state.get_prompt()
247
+
248
+ all_images = state.get_images(return_pil=True)
249
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
250
+ for image, hash in zip(all_images, all_image_hash):
251
+ t = datetime.datetime.now()
252
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
253
+ if not os.path.isfile(filename):
254
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
255
+ image.save(filename)
256
+
257
+ # Make requests
258
+ pload = {
259
+ "model": model_name,
260
+ "prompt": prompt,
261
+ "temperature": float(temperature),
262
+ "top_p": float(top_p),
263
+ "max_new_tokens": min(int(max_new_tokens), 1536),
264
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
265
+ "images": f'List of {len(state.get_images())} images: {all_image_hash}',
266
+ }
267
+ logger.info(f"==== request ====\n{pload}")
268
+
269
+ pload['images'] = state.get_images()
270
+
271
+ state.messages[-1][-1] = "▌"
272
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
273
+ print(f"entering Stream output")
274
+ try:
275
+ # Stream output
276
+ response = requests.post(worker_addr + "/worker_generate_stream",
277
+ headers=headers, json=pload, stream=True, timeout=10)
278
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
279
+ if chunk:
280
+ data = json.loads(chunk.decode())
281
+ if data["error_code"] == 0:
282
+ output = data["text"][len(prompt):].strip()
283
+ state.messages[-1][-1] = output + "▌"
284
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
285
+ else:
286
+ output = data["text"] + f" (error_code: {data['error_code']})"
287
+ state.messages[-1][-1] = output
288
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
289
+ return
290
+ time.sleep(0.03)
291
+ except requests.exceptions.RequestException as e:
292
+ state.messages[-1][-1] = server_error_msg
293
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
294
+ return
295
+
296
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
297
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
298
+
299
+ finish_tstamp = time.time()
300
+ logger.info(f"{output}")
301
+
302
+ with open(get_conv_log_filename(), "a") as fout:
303
+ data = {
304
+ "tstamp": round(finish_tstamp, 4),
305
+ "type": "chat",
306
+ "model": model_name,
307
+ "start": round(start_tstamp, 4),
308
+ "finish": round(finish_tstamp, 4),
309
+ "state": state.dict(),
310
+ "images": all_image_hash,
311
+ "ip": request.client.host,
312
+ }
313
+ fout.write(json.dumps(data) + "\n")
314
+
315
+ title_markdown = ("""
316
+ Most Up To Date Scripts On : https://www.patreon.com/posts/sota-very-best-90744385 \n
317
+ Original Project : https://llava-vl.github.io
318
+ """)
319
+
320
+ tos_markdown = ("""
321
+ ### Terms of use
322
+ By using this service, users are required to agree to the following terms:
323
+ 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.
324
+ Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator.
325
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
326
+ """)
327
+
328
+
329
+ learn_more_markdown = ("""
330
+ ### License
331
+ 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.
332
+ """)
333
+
334
+ block_css = """
335
+
336
+ #buttons button {
337
+ min-width: min(120px,100%);
338
+ }
339
+
340
+ """
341
+
342
+
343
+
344
+
345
+
346
+ def build_demo(embed_mode):
347
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", container=False)
348
+
349
+ # New components for batch processing
350
+ folder_input = gr.Textbox(label="Enter Folder Path for Batch Processing")
351
+ batch_btn = gr.Button("Batch Process")
352
+
353
+ with gr.Blocks(title="LLaVA", theme=gr.themes.Default(), css=block_css) as demo:
354
+ state = gr.State()
355
+
356
+ if not embed_mode:
357
+ gr.Markdown(title_markdown)
358
+
359
+ with gr.Row():
360
+ with gr.Column(scale=3):
361
+ with gr.Row(elem_id="model_selector_row"):
362
+ model_selector = gr.Dropdown(
363
+ choices=models,
364
+ value=models[0] if len(models) > 0 else "",
365
+ interactive=True,
366
+ show_label=False,
367
+ container=False)
368
+
369
+ imagebox = gr.Image(type="pil")
370
+ image_process_mode = gr.Radio(
371
+ ["Crop", "Resize", "Pad", "Default"],
372
+ value="Default",
373
+ label="Preprocess for non-square image", visible=False)
374
+
375
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
376
+ gr.Examples(examples=[
377
+ [f"{cur_dir}/examples/extreme_ironing.jpg", "just caption the image with details, colors, items, objects, emotions, art style, drawing style and objects but do not add any description or comment. do not miss any item in the given image"],
378
+ ], inputs=[imagebox, textbox])
379
+
380
+ with gr.Accordion("Parameters", open=False) as parameter_row:
381
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
382
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
383
+ max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
384
+
385
+ with gr.Column(scale=8):
386
+ chatbot = gr.Chatbot(elem_id="chatbot", label="LLaVA Chatbot", height=550)
387
+ with gr.Row():
388
+ with gr.Column(scale=8):
389
+ textbox.render()
390
+ with gr.Column(scale=1, min_width=50):
391
+ submit_btn = gr.Button(value="Send", variant="primary")
392
+ with gr.Row(elem_id="buttons") as button_row:
393
+ upvote_btn = gr.Button(value="👍 Upvote", interactive=False)
394
+ downvote_btn = gr.Button(value="👎 Downvote", interactive=False)
395
+ flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
396
+ regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False)
397
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=False)
398
+
399
+ url_params = gr.JSON(visible=False)
400
+
401
+ # Add new components for batch processing
402
+ with gr.Row():
403
+ folder_input.render()
404
+ batch_btn.render()
405
+
406
+ # Batch processing button event
407
+ batch_btn.click(
408
+ batch_process_images, # This function needs to be defined to handle batch processing
409
+ inputs=[folder_input, textbox, model_selector , temperature, top_p, max_output_tokens],
410
+ outputs=[]
411
+ )
412
+
413
+ # Register listeners
414
+ btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn]
415
+ upvote_btn.click(
416
+ upvote_last_response,
417
+ [state, model_selector],
418
+ [textbox, upvote_btn, downvote_btn, flag_btn],
419
+ queue=False
420
+ )
421
+ downvote_btn.click(
422
+ downvote_last_response,
423
+ [state, model_selector],
424
+ [textbox, upvote_btn, downvote_btn, flag_btn],
425
+ queue=False
426
+ )
427
+ flag_btn.click(
428
+ flag_last_response,
429
+ [state, model_selector],
430
+ [textbox, upvote_btn, downvote_btn, flag_btn],
431
+ queue=False
432
+ )
433
+
434
+ regenerate_btn.click(
435
+ regenerate,
436
+ [state, image_process_mode],
437
+ [state, chatbot, textbox, imagebox] + btn_list,
438
+ queue=False
439
+ ).then(
440
+ http_bot,
441
+ [state, model_selector, temperature, top_p, max_output_tokens],
442
+ [state, chatbot] + btn_list
443
+ )
444
+
445
+ clear_btn.click(
446
+ clear_history,
447
+ None,
448
+ [state, chatbot, textbox, imagebox] + btn_list,
449
+ queue=False
450
+ )
451
+
452
+ textbox.submit(
453
+ add_text,
454
+ [state, textbox, imagebox, image_process_mode],
455
+ [state, chatbot, textbox, imagebox] + btn_list,
456
+ queue=False
457
+ ).then(
458
+ http_bot,
459
+ [state, model_selector, temperature, top_p, max_output_tokens],
460
+ [state, chatbot] + btn_list
461
+ )
462
+
463
+ submit_btn.click(
464
+ add_text,
465
+ [state, textbox, imagebox, image_process_mode],
466
+ [state, chatbot, textbox, imagebox] + btn_list,
467
+ queue=False
468
+ ).then(
469
+ http_bot,
470
+ [state, model_selector, temperature, top_p, max_output_tokens],
471
+ [state, chatbot] + btn_list
472
+ )
473
+
474
+ if args.model_list_mode == "once":
475
+ demo.load(
476
+ load_demo,
477
+ [url_params],
478
+ [state, model_selector],
479
+ _js=get_window_url_params,
480
+ queue=False
481
+ )
482
+ elif args.model_list_mode == "reload":
483
+ demo.load(
484
+ load_demo_refresh_model_list,
485
+ None,
486
+ [state, model_selector],
487
+ queue=False
488
+ )
489
+ else:
490
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
491
+
492
+ return demo
493
+
494
+
495
+ if __name__ == "__main__":
496
+ parser = argparse.ArgumentParser()
497
+ parser.add_argument("--host", type=str, default="0.0.0.0")
498
+ parser.add_argument("--port", type=int)
499
+ parser.add_argument("--controller-url", type=str, default="http://localhost:10000")
500
+ parser.add_argument("--concurrency-count", type=int, default=10)
501
+ parser.add_argument("--model-list-mode", type=str, default="reload",
502
+ choices=["once", "reload"])
503
+ parser.add_argument("--share", action="store_true")
504
+ parser.add_argument("--moderate", action="store_true")
505
+ parser.add_argument("--embed", action="store_true")
506
+ args = parser.parse_args()
507
+ logger.info(f"args: {args}")
508
+
509
+ models = get_model_list()
510
+
511
+ logger.info(args)
512
+ demo = build_demo(args.embed)
513
+ demo.queue(
514
+ concurrency_count=args.concurrency_count,
515
+ api_open=False
516
+ ).launch(
517
+ server_name=args.host,
518
+ server_port=args.port,
519
+ share=args.share
520
+ )