YPan0 commited on
Commit
b339348
·
1 Parent(s): 73c5d24
Files changed (2) hide show
  1. app.py +892 -4
  2. app_what.py +7 -0
app.py CHANGED
@@ -1,7 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
1
+ from gradio.helpers import Examples
2
+ import argparse
3
+ import base64
4
+ from collections import defaultdict
5
+ import copy
6
+ import datetime
7
+ from functools import partial
8
+ import json
9
+ import os
10
+ import torch
11
+ from pathlib import Path
12
+ import cv2
13
+ import numpy as np
14
+ import re
15
+ import time
16
+ from io import BytesIO
17
+ from PIL import Image
18
+ from PIL import Image as _Image # using _ to minimize namespace pollution
19
+
20
  import gradio as gr
21
+ from gradio import processing_utils, utils
22
+ from gradio_client import utils as client_utils
23
+
24
+ import requests
25
+
26
+ from llava.conversation import (default_conversation, conv_templates,
27
+ SeparatorStyle)
28
+ from llava.constants import LOGDIR
29
+ from llava.utils import (build_logger, server_error_msg,
30
+ violates_moderation, moderation_msg)
31
+ import hashlib
32
+ from llava.serve.utils import annotate_xyxy, show_mask
33
+
34
+ import pycocotools.mask as mask_util
35
+
36
+ R = partial(round, ndigits=2)
37
+
38
+
39
+ class ImageMask(gr.components.Image):
40
+ """
41
+ Sets: source="canvas", tool="sketch"
42
+ """
43
+
44
+ is_template = True
45
+
46
+ def __init__(self, **kwargs):
47
+ super().__init__(source="upload", tool="sketch",
48
+ type='pil', interactive=True, **kwargs)
49
+ # super().__init__(source="upload", tool="boxes", type='pil', interactive=True, **kwargs)
50
+
51
+ def preprocess(self, x):
52
+ # import ipdb; ipdb.set_trace()
53
+
54
+ # a hack to get the mask
55
+ if isinstance(x, str):
56
+ im = processing_utils.decode_base64_to_image(x)
57
+ w, h = im.size
58
+ # a mask, array, uint8
59
+ mask_np = np.zeros((h, w, 4), dtype=np.uint8)
60
+ # to pil
61
+ mask_pil = Image.fromarray(mask_np, mode='RGBA')
62
+ # to base64
63
+ mask_b64 = processing_utils.encode_pil_to_base64(mask_pil)
64
+ x = {
65
+ 'image': x,
66
+ 'mask': mask_b64
67
+ }
68
+
69
+ res = super().preprocess(x)
70
+ # arr -> PIL
71
+ # res['image'] = Image.fromarray(res['image'])
72
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
73
+ # import ipdb; ipdb.set_trace()
74
+ return res
75
+
76
+
77
+ def get_mask_bbox(mask_img: Image):
78
+ # convert to np array
79
+ mask = np.array(mask_img)[..., 0]
80
+
81
+ # check if has masks
82
+ if mask.sum() == 0:
83
+ return None
84
+
85
+ # get coords
86
+ coords = np.argwhere(mask > 0)
87
+
88
+ # calculate bbox
89
+ y0, x0 = coords.min(axis=0)
90
+ y1, x1 = coords.max(axis=0) + 1
91
+
92
+ # get h and w
93
+ h, w = mask.shape[:2]
94
+
95
+ # norm to [0, 1]
96
+ x0, y0, x1, y1 = R(x0 / w), R(y0 / h), R(x1 / w), R(y1 / h)
97
+ return [x0, y0, x1, y1]
98
+
99
+
100
+ def plot_boxes(image: Image, res: dict) -> Image:
101
+ boxes = torch.Tensor(res["boxes"])
102
+ logits = torch.Tensor(res["logits"]) if 'logits' in res else None
103
+ phrases = res["phrases"] if 'phrases' in res else None
104
+ image_source = np.array(image)
105
+ annotated_frame = annotate_xyxy(
106
+ image_source=image_source, boxes=boxes, logits=logits, phrases=phrases)
107
+ return Image.fromarray(annotated_frame)
108
+
109
+
110
+ def plot_masks(image: Image, res: dict) -> Image:
111
+ masks_rle = res["masks_rle"]
112
+ for mask_rle in masks_rle:
113
+ mask = mask_util.decode(mask_rle)
114
+ mask = torch.Tensor(mask)
115
+ image = show_mask(mask, image)
116
+ return image
117
+
118
+
119
+ def plot_points(image: Image, res: dict) -> Image:
120
+ points = torch.Tensor(res["points"])
121
+ point_labels = torch.Tensor(res["point_labels"])
122
+
123
+ points = np.array(points)
124
+ point_labels = np.array(point_labels)
125
+ annotated_frame = np.array(image)
126
+ h, w = annotated_frame.shape[:2]
127
+ for i in range(points.shape[1]):
128
+ color = (0, 255, 0) if point_labels[0, i] == 1 else (0, 0, 255)
129
+ annotated_frame = cv2.circle(annotated_frame, (int(
130
+ points[0, i, 0] * w), int(points[0, i, 1] * h)), 5, color, -1)
131
+ return Image.fromarray(annotated_frame)
132
+
133
+
134
+ logger = build_logger("gradio_web_server", "gradio_web_server.log")
135
+
136
+ headers = {"User-Agent": "MMedAgent Client"}
137
+
138
+ no_change_btn = gr.Button.update()
139
+ enable_btn = gr.Button.update(interactive=True)
140
+ disable_btn = gr.Button.update(interactive=False)
141
+
142
+
143
+ priority = {
144
+ "vicuna-13b": "aaaaaaa",
145
+ "koala-13b": "aaaaaab",
146
+ }
147
+
148
+ R = partial(round, ndigits=2)
149
+
150
+ def b64_encode(img):
151
+ buffered = BytesIO()
152
+ img.save(buffered, format="JPEG")
153
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
154
+ return img_b64_str
155
+
156
+ def get_worker_addr(controller_addr, worker_name):
157
+ # get grounding dino addr
158
+ if worker_name.startswith("http"):
159
+ sub_server_addr = worker_name
160
+ else:
161
+ controller_addr = controller_addr
162
+ ret = requests.post(controller_addr + "/refresh_all_workers")
163
+ assert ret.status_code == 200
164
+ ret = requests.post(controller_addr + "/list_models")
165
+ models = ret.json()["models"]
166
+ models.sort()
167
+ # print(f"Models: {models}")
168
+
169
+ ret = requests.post(
170
+ controller_addr + "/get_worker_address", json={"model": worker_name}
171
+ )
172
+ sub_server_addr = ret.json()["address"]
173
+ # print(f"worker_name: {worker_name}")
174
+ return sub_server_addr
175
+
176
+
177
+ def get_conv_log_filename():
178
+ t = datetime.datetime.now()
179
+ name = os.path.join(
180
+ LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
181
+ return name
182
+
183
+
184
+ def get_model_list():
185
+ ret = requests.post(args.controller_url + "/refresh_all_workers")
186
+ assert ret.status_code == 200
187
+ ret = requests.post(args.controller_url + "/list_models")
188
+ models = ret.json()["models"]
189
+ models.sort(key=lambda x: priority.get(x, x))
190
+ logger.info(f"Models: {models}")
191
+ return models
192
+
193
+
194
+ get_window_url_params = """
195
+ function() {
196
+ const params = new URLSearchParams(window.location.search);
197
+ url_params = Object.fromEntries(params);
198
+ console.log(url_params);
199
+ return url_params;
200
+ }
201
+ """
202
+
203
+
204
+ def load_demo(url_params, request: gr.Request):
205
+ logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
206
+
207
+ dropdown_update = gr.Dropdown.update(visible=True)
208
+ if "model" in url_params:
209
+ model = url_params["model"]
210
+ if model in models:
211
+ dropdown_update = gr.Dropdown.update(
212
+ value=model, visible=True)
213
+
214
+ state = default_conversation.copy()
215
+ return (state,
216
+ dropdown_update,
217
+ gr.Chatbot.update(visible=True),
218
+ gr.Textbox.update(visible=True),
219
+ gr.Button.update(visible=True),
220
+ gr.Row.update(visible=True),
221
+ gr.Accordion.update(visible=True),
222
+ gr.Accordion.update(visible=True))
223
+
224
+
225
+ def load_demo_refresh_model_list(request: gr.Request):
226
+ logger.info(f"load_demo. ip: {request.client.host}")
227
+ models = get_model_list()
228
+ state = default_conversation.copy()
229
+ return (state, gr.Dropdown.update(
230
+ choices=models,
231
+ value=models[0] if len(models) > 0 else ""),
232
+ gr.Chatbot.update(visible=True),
233
+ gr.Textbox.update(visible=True),
234
+ gr.Button.update(visible=True),
235
+ gr.Row.update(visible=True),
236
+ gr.Accordion.update(visible=True),
237
+ gr.Accordion.update(visible=True))
238
+
239
+
240
+ def change_debug_state(state, with_debug_parameter_from_state, request: gr.Request):
241
+ logger.info(f"change_debug_state. ip: {request.client.host}")
242
+ print("with_debug_parameter_from_state: ", with_debug_parameter_from_state)
243
+ with_debug_parameter_from_state = not with_debug_parameter_from_state
244
+
245
+ # modify the text on debug_btn
246
+ debug_btn_value = "🈚 Progress (off)" if not with_debug_parameter_from_state else "🈶 Progress (on)"
247
+
248
+ debug_btn_update = gr.Button.update(
249
+ value=debug_btn_value,
250
+ )
251
+ state_update = with_debug_parameter_from_state
252
+ return (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state), "", None) + (debug_btn_update, state_update)
253
+
254
+
255
+ def add_text(state, text, image_dict, ref_image_dict, image_process_mode, with_debug_parameter_from_state, request: gr.Request):
256
+ # dict_keys(['image', 'mask'])
257
+ if image_dict is not None:
258
+ image = image_dict['image']
259
+ else:
260
+ image = None
261
+ logger.info(f"add_text. ip: {request.client.host}. len: {len(text)}")
262
+ if len(text) <= 0 and image is None:
263
+ state.skip_next = True
264
+ return (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state), "", None) + (no_change_btn,) * 5
265
+ if args.moderate:
266
+ flagged = violates_moderation(text)
267
+ if flagged:
268
+ state.skip_next = True
269
+ return (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state), moderation_msg, None) + (
270
+ no_change_btn,) * 5
271
+
272
+ text = text[:1536] # Hard cut-off
273
+ if image is not None:
274
+ text = text[:1200] # Hard cut-off for images
275
+ if '<image>' not in text:
276
+ text = text + '\n<image>'
277
+ text = (text, image, image_process_mode)
278
+ state = default_conversation.copy()
279
+
280
+ # a hack, for mask
281
+ sketch_mask = image_dict['mask']
282
+ if sketch_mask is not None:
283
+ text = (text[0], text[1], text[2], sketch_mask)
284
+ # check if visual prompt is used
285
+ bounding_box = get_mask_bbox(sketch_mask)
286
+ if bounding_box is not None:
287
+ text_input_new = text[0] + f"\nInput box: {bounding_box}"
288
+ text = (text_input_new, text[1], text[2], text[3])
289
+
290
+ if ref_image_dict is not None:
291
+ # text = (text[0], text[1], text[2], text[3], {
292
+ # 'ref_image': ref_image_dict['image'],
293
+ # 'ref_mask': ref_image_dict['mask']
294
+ # })
295
+ state.reference_image = b64_encode(ref_image_dict['image'])
296
+ state.reference_mask = b64_encode(ref_image_dict['mask'])
297
+
298
+ state.append_message(state.roles[0], text)
299
+ state.append_message(state.roles[1], None)
300
+ state.skip_next = False
301
+ return (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state), "", None, None) + (disable_btn,) * 6
302
+
303
+
304
+ def http_bot(state, model_selector, temperature, top_p, max_new_tokens, with_debug_parameter_from_state, api_key, request: gr.Request):
305
+ logger.info(f"http_bot. ip: {request.client.host}")
306
+ start_tstamp = time.time()
307
+ model_name = model_selector
308
+
309
+ if state.skip_next:
310
+ # This generate call is skipped due to invalid inputs
311
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (no_change_btn,) * 6
312
+ return
313
+
314
+ if len(state.messages) == state.offset + 2:
315
+ # # First round of conversation
316
+
317
+ if "llava" in model_name.lower():
318
+ if 'llama-2' in model_name.lower():
319
+ template_name = "llava_llama_2"
320
+ elif "v1" in model_name.lower():
321
+ if 'mmtag' in model_name.lower():
322
+ template_name = "v1_mmtag"
323
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
324
+ template_name = "v1_mmtag"
325
+ else:
326
+ template_name = "llava_v1"
327
+ elif "mpt" in model_name.lower():
328
+ template_name = "mpt"
329
+ else:
330
+ if 'mmtag' in model_name.lower():
331
+ template_name = "v0_mmtag"
332
+ elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower() and 'tools' not in model_name.lower():
333
+ template_name = "v0_mmtag"
334
+ else:
335
+ template_name = "llava_v0"
336
+ elif "mpt" in model_name:
337
+ template_name = "mpt_text"
338
+ elif "llama-2" in model_name:
339
+ template_name = "llama_2"
340
+ else:
341
+ template_name = "vicuna_v1"
342
+ print("template_name: ", template_name)
343
+
344
+ # # hack:
345
+ # # template_name = "multimodal_tools"
346
+ # # import ipdb; ipdb.set_trace()
347
+ # # image_name = [hashlib.md5(image.tobytes()).hexdigest() for image in state.get_images(return_pil=True)][0]
348
+
349
+ new_state = conv_templates[template_name].copy()
350
+
351
+ # if len(new_state.roles) == 2:
352
+ # new_state.roles = tuple(list(new_state.roles) + ["system"])
353
+ # new_state.append_message(new_state.roles[2], f"receive an image with name `{image_name}.jpg`")
354
+
355
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
356
+ new_state.append_message(new_state.roles[1], None)
357
+
358
+ # for reference image
359
+ new_state.reference_image = getattr(state, 'reference_image', None)
360
+ new_state.reference_mask = getattr(state, 'reference_mask', None)
361
+
362
+ # update
363
+ state = new_state
364
+
365
+ print("Messages:", state.messages)
366
+
367
+ # Query worker address
368
+ controller_url = args.controller_url
369
+ ret = requests.post(controller_url + "/get_worker_address",
370
+ json={"model": model_name})
371
+ worker_addr = ret.json()["address"]
372
+ logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
373
+
374
+ # No available worker
375
+ if worker_addr == "":
376
+ state.messages[-1][-1] = server_error_msg
377
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn, enable_btn)
378
+ return
379
+
380
+ # Construct prompt
381
+ prompt = state.get_prompt()
382
+ # import ipdb; ipdb.set_trace()
383
+
384
+ # Save images
385
+ all_images = state.get_images(return_pil=True)
386
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest()
387
+ for image in all_images]
388
+ for image, hash in zip(all_images, all_image_hash):
389
+ t = datetime.datetime.now()
390
+ filename = os.path.join(
391
+ LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
392
+ if not os.path.isfile(filename):
393
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
394
+ image.save(filename)
395
+ # import ipdb; ipdb.set_trace()
396
+
397
+ # Make requests
398
+ pload = {
399
+ "model": model_selector,
400
+ "prompt": prompt,
401
+ "temperature": float(temperature),
402
+ "top_p": float(top_p),
403
+ "max_new_tokens": min(int(max_new_tokens), 1536),
404
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
405
+ "images": state.get_images(),
406
+ "openai_key": api_key
407
+ }
408
+ logger.info(f"==== request ====\n{pload}\n==== request ====")
409
+
410
+ pload['images'] = state.get_images()
411
+
412
+ state.messages[-1][-1] = "▌"
413
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn,) * 6
414
+
415
+ try:
416
+ # Stream output
417
+ response = requests.post(worker_addr + "/worker_generate_stream",
418
+ headers=headers, json=pload, stream=True, timeout=10)
419
+ # import ipdb; ipdb.set_trace()
420
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
421
+ if chunk:
422
+ data = json.loads(chunk.decode())
423
+ if data["error_code"] == 0:
424
+ output = data["text"][len(prompt):].strip()
425
+ state.messages[-1][-1] = output + "▌"
426
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn,) * 6
427
+ else:
428
+ output = data["text"] + \
429
+ f" (error_code: {data['error_code']})"
430
+ state.messages[-1][-1] = output
431
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn, enable_btn)
432
+ return
433
+ time.sleep(0.03)
434
+ except requests.exceptions.RequestException as e:
435
+ print("error: ", e)
436
+ state.messages[-1][-1] = server_error_msg
437
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn, enable_btn)
438
+ return
439
+
440
+ # remove the cursor
441
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
442
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (enable_btn,) * 6
443
+
444
+ # check if we need tools
445
+ model_output_text = state.messages[-1][1]
446
+ # import ipdb; ipdb.set_trace()
447
+ print("model_output_text: ", model_output_text,
448
+ "Now we are going to parse the output.")
449
+ # parse the output
450
+
451
+ # import ipdb; ipdb.set_trace()
452
+
453
+ try:
454
+ pattern = r'"thoughts🤔"(.*)"actions🚀"(.*)"value👉"(.*)'
455
+ matches = re.findall(pattern, model_output_text, re.DOTALL)
456
+ # import ipdb; ipdb.set_trace()
457
+ if len(matches) > 0:
458
+ # tool_cfg = json.loads(matches[0][1].strip())
459
+ try:
460
+ tool_cfg = json.loads(matches[0][1].strip())
461
+ except Exception as e:
462
+ tool_cfg = json.loads(
463
+ matches[0][1].strip().replace("\'", "\""))
464
+ print("tool_cfg:", tool_cfg)
465
+ else:
466
+ tool_cfg = None
467
+ except Exception as e:
468
+ logger.info(f"Failed to parse tool config: {e}")
469
+ tool_cfg = None
470
+
471
+ # run tool augmentation
472
+ print("trigger tool augmentation with tool_cfg: ", tool_cfg)
473
+ if tool_cfg is not None and len(tool_cfg) > 0:
474
+ assert len(
475
+ tool_cfg) == 1, "Only one tool is supported for now, but got: {}".format(tool_cfg)
476
+ api_name = tool_cfg[0]['API_name']
477
+ print(f"API NAME: {api_name}")
478
+ tool_cfg[0]['API_params'].pop('image', None)
479
+ images = state.get_raw_images()
480
+ if len(images) > 0:
481
+ image = images[0]
482
+ else:
483
+ image = None
484
+ api_paras = {
485
+ 'image': image,
486
+ "prompt": prompt,
487
+ "box_threshold": 0.3,
488
+ "text_threshold": 0.25,
489
+ "openai_key": api_key,
490
+ **tool_cfg[0]['API_params']
491
+ }
492
+ if api_name in ['inpainting']:
493
+ api_paras['mask'] = getattr(state, 'mask_rle', None)
494
+ if api_name in ['openseed', 'controlnet']:
495
+ if api_name == 'controlnet':
496
+ api_paras['mask'] = getattr(state, 'image_seg', None)
497
+ api_paras['mode'] = api_name
498
+ api_name = 'controlnet'
499
+ if api_name == 'seem':
500
+ reference_image = getattr(state, 'reference_image', None)
501
+ reference_mask = getattr(state, 'reference_mask', None)
502
+ api_paras['refimg'] = reference_image
503
+ api_paras['refmask'] = reference_mask
504
+ # extract ref image and mask
505
+
506
+
507
+ # import ipdb; ipdb.set_trace()
508
+ tool_worker_addr = get_worker_addr(controller_url, api_name)
509
+ print("tool_worker_addr: ", tool_worker_addr)
510
+ tool_response = requests.post(
511
+ tool_worker_addr + "/worker_generate",
512
+ headers=headers,
513
+ json=api_paras,
514
+ ).json()
515
+ tool_response_clone = copy.deepcopy(tool_response)
516
+ print("tool_response: ", tool_response)
517
+
518
+ # clean up the response
519
+ masks_rle = None
520
+ edited_image = None
521
+ image_seg = None # for openseed
522
+ iou_sort_masks = None
523
+ if 'boxes' in tool_response:
524
+ try:
525
+ tool_response['boxes'] = [[R(_b) for _b in bb]
526
+ for bb in tool_response['boxes']]
527
+ except:
528
+ pass
529
+ if 'logits' in tool_response:
530
+ try:
531
+ tool_response['logits'] = [R(_l) for _l in tool_response['logits']]
532
+ except:
533
+ pass
534
+ if 'scores' in tool_response:
535
+ try:
536
+ tool_response['scores'] = [R(_s) for _s in tool_response['scores']]
537
+ except:
538
+ pass
539
+ if "masks_rle" in tool_response:
540
+ masks_rle = tool_response.pop("masks_rle")
541
+ if "edited_image" in tool_response:
542
+ edited_image = tool_response.pop("edited_image")
543
+ if "size" in tool_response:
544
+ try:
545
+ _ = tool_response.pop("size")
546
+ except:
547
+ pass
548
+ if api_name == "easyocr":
549
+ _ = tool_response.pop("boxes")
550
+ _ = tool_response.pop("scores")
551
+ if "retrieval_results" in tool_response:
552
+ tool_response['retrieval_results'] = [
553
+ {'caption': i['caption'], 'similarity': R(i['similarity'])}
554
+ for i in tool_response['retrieval_results']
555
+ ]
556
+ if "image_seg" in tool_response:
557
+ image_seg = tool_response.pop("image_seg")
558
+ if "iou_sort_masks" in tool_response:
559
+ iou_sort_masks = tool_response.pop("iou_sort_masks")
560
+ if len(tool_response) == 0:
561
+ tool_response['message'] = f"The {api_name} has processed the image."
562
+ # hack
563
+ if masks_rle is not None:
564
+ state.mask_rle = masks_rle[0]
565
+ if image_seg is not None:
566
+ state.image_seg = image_seg
567
+
568
+ # if edited_image is not None:
569
+ # edited_image
570
+
571
+ # build new response
572
+ new_response = f"{api_name} model outputs: {tool_response}\n\n"
573
+ first_question = state.messages[-2][-1]
574
+ if isinstance(first_question, tuple):
575
+ first_question = first_question[0].replace("<image>", "")
576
+ first_question = first_question.strip()
577
+
578
+ # add new response to the state
579
+ state.append_message(state.roles[0],
580
+ new_response +
581
+ "Please summarize the model outputs and answer my first question: {}".format(
582
+ first_question)
583
+ )
584
+ state.append_message(state.roles[1], None)
585
+
586
+ # Construct prompt
587
+ prompt2 = state.get_prompt()
588
+
589
+ # Make new requests
590
+ pload = {
591
+ "model": model_name,
592
+ "prompt": prompt2,
593
+ "temperature": float(temperature),
594
+ "max_new_tokens": min(int(max_new_tokens), 1536),
595
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
596
+ "images": f'List of {len(state.get_images())} images: {all_image_hash}',
597
+ "openai_key": api_key
598
+ }
599
+ logger.info(f"==== request ====\n{pload}")
600
+ pload['images'] = state.get_images()
601
+
602
+ state.messages[-1][-1] = "▌"
603
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn,) * 6
604
+
605
+ try:
606
+ # Stream output
607
+ response = requests.post(worker_addr + "/worker_generate_stream",
608
+ headers=headers, json=pload, stream=True, timeout=10)
609
+ # import ipdb; ipdb.set_trace()
610
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
611
+ if chunk:
612
+ data = json.loads(chunk.decode())
613
+ if data["error_code"] == 0:
614
+ output = data["text"][len(prompt2):].strip()
615
+ state.messages[-1][-1] = output + "▌"
616
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn,) * 6
617
+ else:
618
+ output = data["text"] + \
619
+ f" (error_code: {data['error_code']})"
620
+ state.messages[-1][-1] = output
621
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn, enable_btn)
622
+ return
623
+ time.sleep(0.03)
624
+ except requests.exceptions.RequestException as e:
625
+ state.messages[-1][-1] = server_error_msg
626
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn, enable_btn)
627
+ return
628
+
629
+ # remove the cursor
630
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
631
+
632
+ # add image(s)
633
+ if edited_image is not None:
634
+ edited_image_pil = Image.open(
635
+ BytesIO(base64.b64decode(edited_image))).convert("RGB")
636
+ state.messages[-1][-1] = (state.messages[-1]
637
+ [-1], edited_image_pil, "Crop")
638
+ if image_seg is not None:
639
+ edited_image_pil = Image.open(
640
+ BytesIO(base64.b64decode(image_seg))).convert("RGB")
641
+ state.messages[-1][-1] = (state.messages[-1]
642
+ [-1], edited_image_pil, "Crop")
643
+ if iou_sort_masks is not None:
644
+ assert isinstance(
645
+ iou_sort_masks, list), "iou_sort_masks should be a list, but got: {}".format(iou_sort_masks)
646
+ edited_image_pil_list = [Image.open(
647
+ BytesIO(base64.b64decode(i))).convert("RGB") for i in iou_sort_masks]
648
+ state.messages[-1][-1] = (state.messages[-1]
649
+ [-1], edited_image_pil_list, "Crop")
650
+ if api_name in ['grounding_dino', 'ram+grounding_dino', 'blip2+grounding_dino', 'grounding dino']:
651
+ edited_image_pil = Image.open(
652
+ BytesIO(base64.b64decode(state.get_images()[0]))).convert("RGB")
653
+ edited_image_pil = plot_boxes(edited_image_pil, tool_response)
654
+ state.messages[-1][-1] = (state.messages[-1]
655
+ [-1], edited_image_pil, "Crop")
656
+ if api_name in ['grounding_dino+sam', 'grounded_sam', 'grounding dino + MedSAM']:
657
+ edited_image_pil = Image.open(
658
+ BytesIO(base64.b64decode(state.get_images()[0]))).convert("RGB")
659
+ edited_image_pil = plot_boxes(edited_image_pil, tool_response)
660
+ edited_image_pil = plot_masks(
661
+ edited_image_pil, tool_response_clone)
662
+ state.messages[-1][-1] = (state.messages[-1]
663
+ [-1], edited_image_pil, "Crop")
664
+ if api_name in ['sam']:
665
+ if 'points' in tool_cfg[0]['API_params']:
666
+ edited_image_pil = Image.open(
667
+ BytesIO(base64.b64decode(state.get_images()[0]))).convert("RGB")
668
+ edited_image_pil = plot_masks(
669
+ edited_image_pil, tool_response_clone)
670
+ tool_response_clone['points'] = tool_cfg[0]['API_params']['points']
671
+ tool_response_clone['point_labels'] = tool_cfg[0]['API_params']['point_labels']
672
+ edited_image_pil = plot_points(
673
+ edited_image_pil, tool_response_clone)
674
+
675
+ state.messages[-1][-1] = (state.messages[-1]
676
+ [-1], edited_image_pil, "Crop")
677
+ else:
678
+ assert 'boxes' in tool_cfg[0]['API_params'], "not find 'boxes' in {}".format(
679
+ tool_cfg[0]['API_params'].keys())
680
+ edited_image_pil = Image.open(
681
+ BytesIO(base64.b64decode(state.get_images()[0]))).convert("RGB")
682
+ edited_image_pil = plot_boxes(edited_image_pil, tool_response)
683
+ tool_response_clone['boxes'] = tool_cfg[0]['API_params']['boxes']
684
+ edited_image_pil = plot_masks(
685
+ edited_image_pil, tool_response_clone)
686
+ state.messages[-1][-1] = (state.messages[-1]
687
+ [-1], edited_image_pil, "Crop")
688
+
689
+ yield (state, state.to_gradio_chatbot(with_debug_parameter=with_debug_parameter_from_state)) + (enable_btn,) * 6
690
+
691
+ finish_tstamp = time.time()
692
+ logger.info(f"{output}")
693
+
694
+ # models = get_model_list()
695
+
696
+ # FIXME: disabled temporarily for image generation.
697
+ with open(get_conv_log_filename(), "a") as fout:
698
+ data = {
699
+ "tstamp": round(finish_tstamp, 4),
700
+ "type": "chat",
701
+ "model": model_name,
702
+ "start": round(start_tstamp, 4),
703
+ "finish": round(start_tstamp, 4),
704
+ "state": state.dict(force_str=True),
705
+ "images": all_image_hash,
706
+ "ip": request.client.host,
707
+ }
708
+ fout.write(json.dumps(data) + "\n")
709
+
710
+
711
+ title_markdown = ("""
712
+ # 👨‍⚕️👩‍⚕️ MMedAgent: Learning to Use Medical Tools with Multi-modal Agent
713
+ [[Paper]](https://arxiv.org/abs/2407.02483) [[Code]](https://github.com/Wangyixinxin/MMedAgent)
714
+ """)
715
+
716
+ tos_markdown = ("""
717
+ ### Terms of use
718
+ By using this service, users are required to agree to the following terms:
719
+ 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.
720
+ For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality.
721
+ """)
722
+
723
+
724
+ learn_more_markdown = ("""
725
+ ### License
726
+ 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.
727
+ """)
728
+
729
+
730
+ def build_demo(embed_mode):
731
+ textbox = gr.Textbox(
732
+ show_label=False, placeholder="Enter text and press ENTER", visible=False, container=False)
733
+ with gr.Blocks(title="LLaVA-Plus", theme=gr.themes.Base()) as demo:
734
+ state = gr.State()
735
+
736
+ if not embed_mode:
737
+ gr.Markdown(title_markdown)
738
+
739
+ with gr.Row():
740
+ with gr.Column(scale=3):
741
+ with gr.Row(elem_id="model_selector_row"):
742
+ model_selector = gr.Dropdown(
743
+ choices=models,
744
+ value=models[0] if len(models) > 0 else "",
745
+ interactive=True,
746
+ show_label=False,
747
+ container=False)
748
+
749
+ imagebox = ImageMask()
750
+
751
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
752
+
753
+ with gr.Accordion("Reference Image", open=False, visible=False) as ref_image_row:
754
+ gr.Markdown(
755
+ "The reference image is for some specific tools, like SEEM.")
756
+ ref_image_box = ImageMask()
757
+
758
+ with gr.Accordion("Parameters", open=False, visible=False) as parameter_row:
759
+ image_process_mode = gr.Radio(
760
+ ["Crop", "Resize", "Pad"],
761
+ value="Crop",
762
+ label="Preprocess for non-square image")
763
+ temperature = gr.Slider(
764
+ minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
765
+ top_p = gr.Slider(
766
+ minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
767
+ max_output_tokens = gr.Slider(
768
+ minimum=0, maximum=2048, value=512, step=64, interactive=True, label="Max output tokens",)
769
+ # with_debug_parameter_check_box = gr.Checkbox(label="With debug parameter", checked=args.with_debug_parameter)
770
+
771
+ api_key_input = gr.Textbox(label="OpenAI API Key", placeholder="Enter your OpenAI API key", type="password")
772
+ with gr.Column(scale=6):
773
+ chatbot = gr.Chatbot(
774
+ elem_id="chatbot", label="LLaVA-Plus Chatbot", height=550)
775
+ with gr.Row():
776
+ with gr.Column(scale=8):
777
+ textbox.render()
778
+ with gr.Column(scale=1, min_width=60):
779
+ submit_btn = gr.Button(value="Submit", visible=False)
780
+ with gr.Row(visible=False) as button_row:
781
+ debug_btn = gr.Button(
782
+ value="🈚 Prog (off)", interactive=True)
783
+ # import ipdb; ipdb.set_trace()
784
+ if args.with_debug_parameter:
785
+ debug_btn.value = "🈶 Prog (on)"
786
+ with_debug_parameter_state = gr.State(
787
+ value=args.with_debug_parameter,
788
+ )
789
+
790
+ with gr.Row():
791
+ with gr.Column():
792
+ gr.Examples(examples=[
793
+ [f"{cur_dir}/examples/cell_00040.bmp",
794
+ "Can you find and count how many cells are there in this image?"],
795
+ [f"{cur_dir}/examples/0007d316f756b3fa0baea2ff514ce945.jpg",
796
+ "Does this x-ray image show a sign of Cardiomegaly? Find the area."],
797
+ [f"{cur_dir}/examples/022_083_t1.jpg",
798
+ "Find if there is a tumor in this image."]
799
+ ], inputs=[imagebox, textbox], label="Grounding Examples: ")
800
+ gr.Examples(examples=[
801
+ [f"{cur_dir}/examples/WORD_0072_0290.jpg",
802
+ "Can you locate and segment the kidneys, spleen, and liver in this 2D abdominal CT image?"],
803
+ [f"{cur_dir}/examples/MCUCXR_0075_0.png",
804
+ "Identify the lungs and segment them in this x-ray image."],
805
+ ], inputs=[imagebox, textbox], label="Grounding + Segmentation Examples: ")
806
+
807
+
808
+ with gr.Column():
809
+ gr.Examples(examples=[
810
+ [f"{cur_dir}/examples/0a4fbc9ade84a7abd1680eb8ba031a9d.jpg",
811
+ "What is the imaging modality used for this medical image?"],
812
+ [f"{cur_dir}/examples/27660471_f14-ott-9-5531.jpg",
813
+ "What is the specific type of histopathology depicted in the image?"],
814
+ [f"{cur_dir}/examples/32535614_f2-amjcaserep-21-e923356.jpg",
815
+ "Can you tell me the modality of this image?"]
816
+ ], inputs=[imagebox, textbox], label="Image Modality Classification Examples: ")
817
+ gr.Examples(examples=[
818
+ [f"{cur_dir}/examples/chest.jpg",
819
+ "Can you generate a report based on this image?"]
820
+ ], inputs=[imagebox, textbox], label="Medical Report Generation Examples: ")
821
+ false_report = """
822
+ This case highlights a critical oversight in a complex medical situation. While the initial focus on the patient's syncope was well-executed, subsequent findings of a 4.9 cm aortic aneurysm with celiac artery involvement were not sufficiently followed up.
823
+ Comprehensive imaging of the entire aorta at the discovery point was crucial and could have potentially led to a more favorable outcome. It should be noted that the radiologist conducting the pulmonary artery CT scan should have autonomously extended the imaging to the full aorta without needing further orders.
824
+ """
825
+
826
+ gr.Examples(examples=[
827
+ ["What is breast cancer and how should I treat it?"],
828
+ ["Here is a report\n"+false_report]],
829
+ inputs=[textbox], label="Retrieval Augmented Generation Examples:"
830
+ )
831
+
832
+
833
+
834
+
835
+ if not embed_mode:
836
+ gr.Markdown(tos_markdown)
837
+ gr.Markdown(learn_more_markdown)
838
+ url_params = gr.JSON(visible=False)
839
+
840
+ # Register listeners
841
+
842
+ textbox.submit(add_text, [state, textbox, imagebox, ref_image_box, image_process_mode, with_debug_parameter_state],
843
+ [state, chatbot, textbox, imagebox, ref_image_box, debug_btn]
844
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens, with_debug_parameter_state, api_key_input],
845
+ [state, chatbot, debug_btn])
846
+
847
+ submit_btn.click(add_text, [state, textbox, imagebox, ref_image_box, image_process_mode, with_debug_parameter_state],
848
+ [state, chatbot, textbox, imagebox, ref_image_box, debug_btn]
849
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens, with_debug_parameter_state, api_key_input],
850
+ [state, chatbot, debug_btn])
851
+
852
+ debug_btn.click(change_debug_state, [state, with_debug_parameter_state], [
853
+ state, chatbot, textbox, imagebox] + [debug_btn, with_debug_parameter_state])
854
+
855
+ if args.model_list_mode == "once":
856
+ demo.load(load_demo, [url_params], [state, model_selector,
857
+ chatbot, textbox, submit_btn, button_row, parameter_row, ref_image_row],
858
+ _js=get_window_url_params)
859
+ elif args.model_list_mode == "reload":
860
+ demo.load(load_demo_refresh_model_list, None, [state, model_selector,
861
+ chatbot, textbox, submit_btn, button_row, parameter_row, ref_image_row])
862
+ else:
863
+ raise ValueError(
864
+ f"Unknown model list mode: {args.model_list_mode}")
865
+
866
+ return demo
867
+
868
+
869
+ if __name__ == "__main__":
870
+ parser = argparse.ArgumentParser()
871
+ parser.add_argument("--host", type=str, default="0.0.0.0")
872
+ parser.add_argument("--port", type=int)
873
+ parser.add_argument("--controller-url", type=str,
874
+ default="http://localhost:20001")
875
+ parser.add_argument("--concurrency-count", type=int, default=8)
876
+ parser.add_argument("--model-list-mode", type=str, default="once",
877
+ choices=["once", "reload"])
878
+ parser.add_argument("--share", action="store_true")
879
+ parser.add_argument("--moderate", action="store_true")
880
+ parser.add_argument("--embed", action="store_true")
881
+ parser.add_argument("--debug", action="store_true")
882
+ parser.add_argument("--with_debug_parameter", action="store_true")
883
+ args = parser.parse_args()
884
+ logger.info(f"args: {args}")
885
 
886
+ models = get_model_list()
887
+ models = [i for i in models if 'llava' in i]
888
 
889
+ logger.info(args)
890
+ demo = build_demo(args.embed)
891
+ _app, local_url, share_url = demo.queue(concurrency_count=args.concurrency_count, status_update_rate=10,
892
+ api_open=True).launch(
893
+ server_name=args.host, server_port=args.port, share=args.share, debug=args.debug)
894
+ print("Local URL: ", local_url)
895
+ print("Share URL: ", share_url)
app_what.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ def greet(name):
4
+ return "Hello " + name + "!!"
5
+
6
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
+ demo.launch()