jadechoghari commited on
Commit
1342b13
β€’
1 Parent(s): a526622
Files changed (1) hide show
  1. app.py +783 -0
app.py ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Usage:
3
+
4
+ python -m ferret.serve.gradio_web_server --controller http://localhost:10000 --add_region_feature
5
+ '''
6
+ import argparse
7
+ import datetime
8
+ import json
9
+ import os
10
+ import time
11
+
12
+ import gradio as gr
13
+ import requests
14
+
15
+ from conversation import (default_conversation, conv_templates,
16
+ SeparatorStyle)
17
+ from constants import LOGDIR
18
+ from utils import (build_logger, server_error_msg,
19
+ violates_moderation, moderation_msg)
20
+ import hashlib
21
+ # Added
22
+ import re
23
+ from copy import deepcopy
24
+ from PIL import ImageDraw, ImageFont
25
+ from gradio import processing_utils
26
+ import numpy as np
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from scipy.ndimage import binary_dilation, binary_erosion
30
+ import pdb
31
+ from gradio_css import code_highlight_css
32
+ import spaces
33
+
34
+ from inference import inference_and_run
35
+
36
+ DEFAULT_REGION_REFER_TOKEN = "[region]"
37
+ DEFAULT_REGION_FEA_TOKEN = "<region_fea>"
38
+
39
+
40
+ logger = build_logger("gradio_web_server", "gradio_web_server.log")
41
+
42
+ headers = {"User-Agent": "FERRET Client"}
43
+
44
+ no_change_btn = gr.Button.update()
45
+ enable_btn = gr.Button.update(interactive=True)
46
+ disable_btn = gr.Button.update(interactive=False)
47
+
48
+ priority = {
49
+ "vicuna-13b": "aaaaaaa",
50
+ "koala-13b": "aaaaaab",
51
+ }
52
+
53
+ VOCAB_IMAGE_W = 1000 # 224
54
+ VOCAB_IMAGE_H = 1000 # 224
55
+
56
+ def generate_mask_for_feature(coor, raw_w, raw_h, mask=None):
57
+ if mask is not None:
58
+ assert mask.shape[0] == raw_w and mask.shape[1] == raw_h
59
+ coor_mask = torch.zeros((raw_w, raw_h))
60
+ # Assume it samples a point.
61
+ if len(coor) == 2:
62
+ # Define window size
63
+ span = 5
64
+ # Make sure the window does not exceed array bounds
65
+ x_min = max(0, coor[0] - span)
66
+ x_max = min(raw_w, coor[0] + span + 1)
67
+ y_min = max(0, coor[1] - span)
68
+ y_max = min(raw_h, coor[1] + span + 1)
69
+ coor_mask[int(x_min):int(x_max), int(y_min):int(y_max)] = 1
70
+ assert (coor_mask==1).any(), f"coor: {coor}, raw_w: {raw_w}, raw_h: {raw_h}"
71
+ elif len(coor) == 4:
72
+ # Box input or Sketch input.
73
+ coor_mask = torch.zeros((raw_w, raw_h))
74
+ coor_mask[coor[0]:coor[2]+1, coor[1]:coor[3]+1] = 1
75
+ if mask is not None:
76
+ coor_mask = coor_mask * mask
77
+ # coor_mask = torch.from_numpy(coor_mask)
78
+ # pdb.set_trace()
79
+ assert len(coor_mask.nonzero()) != 0
80
+ return coor_mask.tolist()
81
+
82
+
83
+ def draw_box(coor, region_mask, region_ph, img, input_mode):
84
+ colors = ["red"]
85
+ draw = ImageDraw.Draw(img)
86
+ font = ImageFont.truetype("./DejaVuSans.ttf", size=18)
87
+ if input_mode == 'Box':
88
+ draw.rectangle([coor[0], coor[1], coor[2], coor[3]], outline=colors[0], width=4)
89
+ draw.rectangle([coor[0], coor[3] - int(font.size * 1.2), coor[0] + int((len(region_ph) + 0.8) * font.size * 0.6), coor[3]], outline=colors[0], fill=colors[0], width=4)
90
+ draw.text([coor[0] + int(font.size * 0.2), coor[3] - int(font.size*1.2)], region_ph, font=font, fill=(255,255,255))
91
+ elif input_mode == 'Point':
92
+ r = 8
93
+ leftUpPoint = (coor[0]-r, coor[1]-r)
94
+ rightDownPoint = (coor[0]+r, coor[1]+r)
95
+ twoPointList = [leftUpPoint, rightDownPoint]
96
+ draw.ellipse(twoPointList, outline=colors[0], width=4)
97
+ draw.rectangle([coor[0], coor[1], coor[0] + int((len(region_ph) + 0.8) * font.size * 0.6), coor[1] + int(font.size * 1.2)], outline=colors[0], fill=colors[0], width=4)
98
+ draw.text([coor[0] + int(font.size * 0.2), coor[1]], region_ph, font=font, fill=(255,255,255))
99
+ elif input_mode == 'Sketch':
100
+ draw.rectangle([coor[0], coor[3] - int(font.size * 1.2), coor[0] + int((len(region_ph) + 0.8) * font.size * 0.6), coor[3]], outline=colors[0], fill=colors[0], width=4)
101
+ draw.text([coor[0] + int(font.size * 0.2), coor[3] - int(font.size*1.2)], region_ph, font=font, fill=(255,255,255))
102
+ # Use morphological operations to find the boundary
103
+ mask = np.array(region_mask)
104
+ dilated = binary_dilation(mask, structure=np.ones((3,3)))
105
+ eroded = binary_erosion(mask, structure=np.ones((3,3)))
106
+ boundary = dilated ^ eroded # XOR operation to find the difference between dilated and eroded mask
107
+ # Loop over the boundary and paint the corresponding pixels
108
+ for i in range(boundary.shape[0]):
109
+ for j in range(boundary.shape[1]):
110
+ if boundary[i, j]:
111
+ # This is a pixel on the boundary, paint it red
112
+ draw.point((i, j), fill=colors[0])
113
+ else:
114
+ NotImplementedError(f'Input mode of {input_mode} is not Implemented.')
115
+ return img
116
+
117
+
118
+ def get_conv_log_filename():
119
+ t = datetime.datetime.now()
120
+ name = os.path.join(LOGDIR, f"{t.year}-{t.month:02d}-{t.day:02d}-conv.json")
121
+ return name
122
+
123
+
124
+ # TODO: return model manually just one for now called "jadechoghari/Ferret-UI-Gemma2b"
125
+ def get_model_list():
126
+ # ret = requests.post(args.controller_url + "/refresh_all_workers")
127
+ # assert ret.status_code == 200
128
+ # ret = requests.post(args.controller_url + "/list_models")
129
+ # models = ret.json()["models"]
130
+ # models.sort(key=lambda x: priority.get(x, x))
131
+ # logger.info(f"Models: {models}")
132
+ # return models
133
+ models = ["jadechoghari/Ferret-UI-Gemma2b"]
134
+ logger.info(f"Models: {models}")
135
+ return models
136
+
137
+
138
+ get_window_url_params = """
139
+ function() {
140
+ const params = new URLSearchParams(window.location.search);
141
+ url_params = Object.fromEntries(params);
142
+ console.log(url_params);
143
+ return url_params;
144
+ }
145
+ """
146
+
147
+
148
+ def load_demo(url_params, request: gr.Request):
149
+ # logger.info(f"load_demo. ip: {request.client.host}. params: {url_params}")
150
+
151
+ dropdown_update = gr.Dropdown.update(visible=True)
152
+ if "model" in url_params:
153
+ model = url_params["model"]
154
+ if model in models:
155
+ dropdown_update = gr.Dropdown.update(
156
+ value=model, visible=True)
157
+
158
+ state = default_conversation.copy()
159
+ print("state", state)
160
+ return (state,
161
+ dropdown_update,
162
+ gr.Chatbot.update(visible=True),
163
+ gr.Textbox.update(visible=True),
164
+ gr.Button.update(visible=True),
165
+ gr.Row.update(visible=True),
166
+ gr.Accordion.update(visible=True))
167
+
168
+
169
+ def load_demo_refresh_model_list(request: gr.Request):
170
+ # logger.info(f"load_demo. ip: {request.client.host}")
171
+ models = get_model_list()
172
+ state = default_conversation.copy()
173
+ return (state, gr.Dropdown.update(
174
+ choices=models,
175
+ value=models[0] if len(models) > 0 else ""),
176
+ gr.Chatbot.update(visible=True),
177
+ gr.Textbox.update(visible=True),
178
+ gr.Button.update(visible=True),
179
+ gr.Row.update(visible=True),
180
+ gr.Accordion.update(visible=True))
181
+
182
+
183
+ def vote_last_response(state, vote_type, model_selector, request: gr.Request):
184
+ with open(get_conv_log_filename(), "a") as fout:
185
+ data = {
186
+ "tstamp": round(time.time(), 4),
187
+ "type": vote_type,
188
+ "model": model_selector,
189
+ "state": state.dict(),
190
+ "ip": request.client.host,
191
+ }
192
+ fout.write(json.dumps(data) + "\n")
193
+
194
+
195
+ def upvote_last_response(state, model_selector, request: gr.Request):
196
+ vote_last_response(state, "upvote", model_selector, request)
197
+ return ("",) + (disable_btn,) * 3
198
+
199
+
200
+ def downvote_last_response(state, model_selector, request: gr.Request):
201
+ vote_last_response(state, "downvote", model_selector, request)
202
+ return ("",) + (disable_btn,) * 3
203
+
204
+
205
+ def flag_last_response(state, model_selector, request: gr.Request):
206
+ vote_last_response(state, "flag", model_selector, request)
207
+ return ("",) + (disable_btn,) * 3
208
+
209
+
210
+ def regenerate(state, image_process_mode, request: gr.Request):
211
+ state.messages[-1][-1] = None
212
+ prev_human_msg = state.messages[-2]
213
+ if type(prev_human_msg[1]) in (tuple, list):
214
+ prev_human_msg[1] = (*prev_human_msg[1][:2], image_process_mode)
215
+ state.skip_next = False
216
+ return (state, state.to_gradio_chatbot(), "") + (disable_btn,) * 5
217
+
218
+
219
+ def clear_history(request: gr.Request):
220
+ state = default_conversation.copy()
221
+ return (state, state.to_gradio_chatbot(), "", None, None) + (disable_btn,) * 5 + \
222
+ (None, {'region_placeholder_tokens':[],'region_coordinates':[],'region_masks':[],'region_masks_in_prompts':[],'masks':[]}, [], None)
223
+
224
+
225
+ def resize_bbox(box, image_w=None, image_h=None, default_wh=VOCAB_IMAGE_W):
226
+ ratio_w = image_w * 1.0 / default_wh
227
+ ratio_h = image_h * 1.0 / default_wh
228
+
229
+ new_box = [int(box[0] * ratio_w), int(box[1] * ratio_h), \
230
+ int(box[2] * ratio_w), int(box[3] * ratio_h)]
231
+ return new_box
232
+
233
+
234
+ def show_location(sketch_pad, chatbot):
235
+ image = sketch_pad['image']
236
+ img_w, img_h = image.size
237
+ new_bboxes = []
238
+ old_bboxes = []
239
+ # chatbot[0] is image.
240
+ text = chatbot[1:]
241
+ for round_i in text:
242
+ human_input = round_i[0]
243
+ model_output = round_i[1]
244
+ # TODO: Difference: vocab representation.
245
+ # pattern = r'\[x\d*=(\d+(?:\.\d+)?), y\d*=(\d+(?:\.\d+)?), x\d*=(\d+(?:\.\d+)?), y\d*=(\d+(?:\.\d+)?)\]'
246
+ pattern = r'\[(\d+(?:\.\d+)?), (\d+(?:\.\d+)?), (\d+(?:\.\d+)?), (\d+(?:\.\d+)?)\]'
247
+ matches = re.findall(pattern, model_output)
248
+ for match in matches:
249
+ x1, y1, x2, y2 = map(int, match)
250
+ new_box = resize_bbox([x1, y1, x2, y2], img_w, img_h)
251
+ new_bboxes.append(new_box)
252
+ old_bboxes.append([x1, y1, x2, y2])
253
+
254
+ set_old_bboxes = sorted(set(map(tuple, old_bboxes)), key=list(map(tuple, old_bboxes)).index)
255
+ list_old_bboxes = list(map(list, set_old_bboxes))
256
+
257
+ set_bboxes = sorted(set(map(tuple, new_bboxes)), key=list(map(tuple, new_bboxes)).index)
258
+ list_bboxes = list(map(list, set_bboxes))
259
+
260
+ output_image = deepcopy(image)
261
+ draw = ImageDraw.Draw(output_image)
262
+ #TODO: change from local to online path
263
+ font = ImageFont.truetype("./DejaVuSans.ttf", 28)
264
+ for i in range(len(list_bboxes)):
265
+ x1, y1, x2, y2 = list_old_bboxes[i]
266
+ x1_new, y1_new, x2_new, y2_new = list_bboxes[i]
267
+ obj_string = '[obj{}]'.format(i)
268
+ for round_i in text:
269
+ model_output = round_i[1]
270
+ model_output = model_output.replace('[{}, {}, {}, {}]'.format(x1, y1, x2, y2), obj_string)
271
+ round_i[1] = model_output
272
+ draw.rectangle([(x1_new, y1_new), (x2_new, y2_new)], outline="red", width=3)
273
+ draw.text((x1_new+2, y1_new+5), obj_string[1:-1], fill="red", font=font)
274
+
275
+ return (output_image, [chatbot[0]] + text, disable_btn)
276
+
277
+
278
+ def add_text(state, text, image_process_mode, original_image, sketch_pad, request: gr.Request):
279
+ image = sketch_pad['image']
280
+
281
+ if len(text) <= 0 and image is None:
282
+ state.skip_next = True
283
+ return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5
284
+ if args.moderate:
285
+ flagged = violates_moderation(text)
286
+ if flagged:
287
+ state.skip_next = True
288
+ return (state, state.to_gradio_chatbot(), moderation_msg, None) + (
289
+ no_change_btn,) * 5
290
+
291
+ text = text[:1536] # Hard cut-off
292
+ if original_image is None:
293
+ assert image is not None
294
+ original_image = image.copy()
295
+ print('No location, copy original image in add_text')
296
+
297
+ if image is not None:
298
+ if state.first_round:
299
+ text = text[:1200] # Hard cut-off for images
300
+ if '<image>' not in text:
301
+ # text = '<Image><image></Image>' + text
302
+ text = text + '\n<image>'
303
+ text = (text, original_image, image_process_mode)
304
+ if len(state.get_images(return_pil=True)) > 0:
305
+ new_state = default_conversation.copy()
306
+ new_state.first_round = False
307
+ state=new_state
308
+ print('First round add image finsihed.')
309
+
310
+ state.append_message(state.roles[0], text)
311
+ state.append_message(state.roles[1], None)
312
+ state.skip_next = False
313
+ return (state, state.to_gradio_chatbot(), "", original_image) + (disable_btn,) * 5
314
+
315
+
316
+ def post_process_code(code):
317
+ sep = "\n```"
318
+ if sep in code:
319
+ blocks = code.split(sep)
320
+ if len(blocks) % 2 == 1:
321
+ for i in range(1, len(blocks), 2):
322
+ blocks[i] = blocks[i].replace("\\_", "_")
323
+ code = sep.join(blocks)
324
+ return code
325
+
326
+
327
+ def find_indices_in_order(str_list, STR):
328
+ indices = []
329
+ i = 0
330
+ while i < len(STR):
331
+ for element in str_list:
332
+ if STR[i:i+len(element)] == element:
333
+ indices.append(str_list.index(element))
334
+ i += len(element) - 1
335
+ break
336
+ i += 1
337
+ return indices
338
+
339
+
340
+ def format_region_prompt(prompt, refer_input_state):
341
+ # Find regions in prompts and assign corresponding region masks
342
+ refer_input_state['region_masks_in_prompts'] = []
343
+ indices_region_placeholder_in_prompt = find_indices_in_order(refer_input_state['region_placeholder_tokens'], prompt)
344
+ refer_input_state['region_masks_in_prompts'] = [refer_input_state['region_masks'][iii] for iii in indices_region_placeholder_in_prompt]
345
+
346
+ # Find regions in prompts and replace with real coordinates and region feature token.
347
+ for region_ph_index, region_ph_i in enumerate(refer_input_state['region_placeholder_tokens']):
348
+ prompt = prompt.replace(region_ph_i, '{} {}'.format(refer_input_state['region_coordinates'][region_ph_index], DEFAULT_REGION_FEA_TOKEN))
349
+ return prompt
350
+
351
+ @spaces.GPU()
352
+ def http_bot(state, model_selector, temperature, top_p, max_new_tokens, refer_input_state, request: gr.Request):
353
+ # def http_bot(state, model_selector, temperature, top_p, max_new_tokens, request: gr.Request):
354
+ start_tstamp = time.time()
355
+ model_name = model_selector
356
+
357
+ if state.skip_next:
358
+ # This generate call is skipped due to invalid inputs
359
+ yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5
360
+ return
361
+
362
+ print("state messages: ", state.messages)
363
+ if len(state.messages) == state.offset + 2:
364
+ # First round of conversation
365
+ # template_name = 'ferret_v1'
366
+ template_name = 'ferret_gemma_instruct'
367
+ # Below is LLaVA's original templates.
368
+ # if "llava" in model_name.lower():
369
+ # if 'llama-2' in model_name.lower():
370
+ # template_name = "llava_llama_2"
371
+ # elif "v1" in model_name.lower():
372
+ # if 'mmtag' in model_name.lower():
373
+ # template_name = "v1_mmtag"
374
+ # elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
375
+ # template_name = "v1_mmtag"
376
+ # else:
377
+ # template_name = "llava_v1"
378
+ # elif "mpt" in model_name.lower():
379
+ # template_name = "mpt"
380
+ # else:
381
+ # if 'mmtag' in model_name.lower():
382
+ # template_name = "v0_mmtag"
383
+ # elif 'plain' in model_name.lower() and 'finetune' not in model_name.lower():
384
+ # template_name = "v0_mmtag"
385
+ # else:
386
+ # template_name = "llava_v0"
387
+ # elif "mpt" in model_name:
388
+ # template_name = "mpt_text"
389
+ # elif "llama-2" in model_name:
390
+ # template_name = "llama_2"
391
+ # else:
392
+ # template_name = "vicuna_v1"
393
+ new_state = conv_templates[template_name].copy()
394
+ new_state.append_message(new_state.roles[0], state.messages[-2][1])
395
+ new_state.append_message(new_state.roles[1], None)
396
+ state = new_state
397
+ state.first_round = False
398
+
399
+ # # Query worker address
400
+ # controller_url = args.controller_url
401
+ # ret = requests.post(controller_url + "/get_worker_address",
402
+ # json={"model": model_name})
403
+ # worker_addr = ret.json()["address"]
404
+ # logger.info(f"model_name: {model_name}, worker_addr: {worker_addr}")
405
+
406
+ # No available worker
407
+ # if worker_addr == "":
408
+ # state.messages[-1][-1] = server_error_msg
409
+ # yield (state, state.to_gradio_chatbot(), disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
410
+ # return
411
+
412
+ # Construct prompt
413
+ prompt = state.get_prompt()
414
+ if args.add_region_feature:
415
+ prompt = format_region_prompt(prompt, refer_input_state)
416
+
417
+ all_images = state.get_images(return_pil=True)
418
+ all_image_hash = [hashlib.md5(image.tobytes()).hexdigest() for image in all_images]
419
+ for image, hash in zip(all_images, all_image_hash):
420
+ t = datetime.datetime.now()
421
+ # fishy can remove it
422
+ filename = os.path.join(LOGDIR, "serve_images", f"{t.year}-{t.month:02d}-{t.day:02d}", f"{hash}.jpg")
423
+ if not os.path.isfile(filename):
424
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
425
+ image.save(filename)
426
+
427
+ # Make requests
428
+ pload = {
429
+ "model": model_name,
430
+ "prompt": prompt,
431
+ "temperature": float(temperature),
432
+ "top_p": float(top_p),
433
+ "max_new_tokens": min(int(max_new_tokens), 1536),
434
+ "stop": state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2,
435
+ "images": f'List of {len(state.get_images())} images: {all_image_hash}',
436
+ }
437
+ logger.info(f"==== request ====\n{pload}")
438
+ if args.add_region_feature:
439
+ pload['region_masks'] = refer_input_state['region_masks_in_prompts']
440
+ logger.info(f"==== add region_masks_in_prompts to request ====\n")
441
+
442
+ pload['images'] = state.get_images()
443
+ print(f'Input Prompt: {prompt}')
444
+ print("all_image_hash", all_image_hash)
445
+
446
+ state.messages[-1][-1] = "β–Œ"
447
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
448
+
449
+ try:
450
+ # Stream output
451
+ stop = state.sep if state.sep_style in [SeparatorStyle.SINGLE, SeparatorStyle.MPT] else state.sep2
452
+ #TODO: define inference and run function
453
+ results, extracted_texts = inference_and_run(
454
+ image_path=all_image_hash[0], # double check this
455
+ prompt=prompt,
456
+ model_path=model_name,
457
+ conv_mode="ferret_gemma_instruct", # Default mode from the original function
458
+ temperature=temperature,
459
+ top_p=top_p,
460
+ max_new_tokens=max_new_tokens,
461
+ stop=stop # Assuming we want to process the image
462
+ )
463
+
464
+ # response = requests.post(worker_addr + "/worker_generate_stream",
465
+ # headers=headers, json=pload, stream=True, timeout=10)
466
+ response = extracted_texts
467
+ logger.info(f"This is the respone {response}")
468
+
469
+ for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
470
+ if chunk:
471
+ data = json.loads(chunk.decode())
472
+ if data["error_code"] == 0:
473
+ output = data["text"][len(prompt):].strip()
474
+ output = post_process_code(output)
475
+ state.messages[-1][-1] = output + "β–Œ"
476
+ yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5
477
+ else:
478
+ output = data["text"] + f" (error_code: {data['error_code']})"
479
+ state.messages[-1][-1] = output
480
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
481
+ return
482
+ time.sleep(0.03)
483
+ except requests.exceptions.RequestException as e:
484
+ state.messages[-1][-1] = server_error_msg
485
+ yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn)
486
+ return
487
+
488
+ state.messages[-1][-1] = state.messages[-1][-1][:-1]
489
+ yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5
490
+
491
+ finish_tstamp = time.time()
492
+ logger.info(f"{output}")
493
+
494
+ with open(get_conv_log_filename(), "a") as fout:
495
+ data = {
496
+ "tstamp": round(finish_tstamp, 4),
497
+ "type": "chat",
498
+ "model": model_name,
499
+ "start": round(start_tstamp, 4),
500
+ "finish": round(start_tstamp, 4),
501
+ "state": state.dict(),
502
+ "images": all_image_hash,
503
+ "ip": request.client.host,
504
+ }
505
+ fout.write(json.dumps(data) + "\n")
506
+
507
+ title_markdown = ("""
508
+ # 🦦 Ferret: Refer and Ground Anything Anywhere at Any Granularity
509
+ """)
510
+ # [[Project Page]](https://llava-vl.github.io) [[Paper]](https://arxiv.org/abs/2304.08485)
511
+
512
+ tos_markdown = ("""
513
+ ### Terms of use
514
+ By using this service, users are required to agree to the following terms: 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.
515
+ """)
516
+
517
+
518
+ learn_more_markdown = ("""
519
+ ### License
520
+ The service is a research preview intended for non-commercial use only
521
+ """)
522
+
523
+
524
+ css = code_highlight_css + """
525
+ pre {
526
+ white-space: pre-wrap; /* Since CSS 2.1 */
527
+ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
528
+ white-space: -pre-wrap; /* Opera 4-6 */
529
+ white-space: -o-pre-wrap; /* Opera 7 */
530
+ word-wrap: break-word; /* Internet Explorer 5.5+ */
531
+ }
532
+ """
533
+
534
+ Instructions = '''
535
+ Instructions:
536
+ 1. Select a 'Referring Input Type'
537
+ 2. Draw on the image to refer to a region/point.
538
+ 3. Copy the region id from 'Referring Input Type' to refer to a region in your chat.
539
+ '''
540
+
541
+ class ImageMask(gr.components.Image):
542
+ """
543
+ Sets: source="canvas", tool="sketch"
544
+ """
545
+
546
+ is_template = True
547
+
548
+ def __init__(self, **kwargs):
549
+ super().__init__(source="upload", tool="sketch", interactive=True, **kwargs)
550
+
551
+ def preprocess(self, x):
552
+ return super().preprocess(x)
553
+
554
+
555
+ def draw(input_mode, input, refer_input_state, refer_text_show, imagebox_refer):
556
+ if type(input) == dict:
557
+ image = deepcopy(input['image'])
558
+ mask = deepcopy(input['mask'])
559
+ else:
560
+ mask = deepcopy(input)
561
+
562
+ # W, H -> H, W, 3
563
+ image_new = np.asarray(image)
564
+ img_height = image_new.shape[0]
565
+ img_width = image_new.shape[1]
566
+
567
+ # W, H, 4 -> H, W
568
+ mask_new = np.asarray(mask)[:,:,0].copy()
569
+ mask_new = torch.from_numpy(mask_new)
570
+ mask_new = (F.interpolate(mask_new.unsqueeze(0).unsqueeze(0), (img_height, img_width), mode='bilinear') > 0)
571
+ mask_new = mask_new[0, 0].transpose(1, 0).long()
572
+
573
+ if len(refer_input_state['masks']) == 0:
574
+ last_mask = torch.zeros_like(mask_new)
575
+ else:
576
+ last_mask = refer_input_state['masks'][-1]
577
+
578
+ diff_mask = mask_new - last_mask
579
+ if torch.all(diff_mask == 0):
580
+ print('Init Uploading Images.')
581
+ return (refer_input_state, refer_text_show, image)
582
+ else:
583
+ refer_input_state['masks'].append(mask_new)
584
+
585
+ if input_mode == 'Point':
586
+ nonzero_points = diff_mask.nonzero()
587
+ nonzero_points_avg_x = torch.median(nonzero_points[:, 0])
588
+ nonzero_points_avg_y = torch.median(nonzero_points[:, 1])
589
+ sampled_coor = [nonzero_points_avg_x, nonzero_points_avg_y]
590
+ # pdb.set_trace()
591
+ cur_region_masks = generate_mask_for_feature(sampled_coor, raw_w=img_width, raw_h=img_height)
592
+ elif input_mode == 'Box' or input_mode == 'Sketch':
593
+ # pdb.set_trace()
594
+ x1x2 = diff_mask.max(1)[0].nonzero()[:, 0]
595
+ y1y2 = diff_mask.max(0)[0].nonzero()[:, 0]
596
+ y1, y2 = y1y2.min(), y1y2.max()
597
+ x1, x2 = x1x2.min(), x1x2.max()
598
+ # pdb.set_trace()
599
+ sampled_coor = [x1, y1, x2, y2]
600
+ if input_mode == 'Box':
601
+ cur_region_masks = generate_mask_for_feature(sampled_coor, raw_w=img_width, raw_h=img_height)
602
+ else:
603
+ cur_region_masks = generate_mask_for_feature(sampled_coor, raw_w=img_width, raw_h=img_height, mask=diff_mask)
604
+ else:
605
+ raise NotImplementedError(f'Input mode of {input_mode} is not Implemented.')
606
+
607
+ # TODO(haoxuan): Hack img_size to be 224 here, need to make it a argument.
608
+ if len(sampled_coor) == 2:
609
+ point_x = int(VOCAB_IMAGE_W * sampled_coor[0] / img_width)
610
+ point_y = int(VOCAB_IMAGE_H * sampled_coor[1] / img_height)
611
+ cur_region_coordinates = f'[{int(point_x)}, {int(point_y)}]'
612
+ elif len(sampled_coor) == 4:
613
+ point_x1 = int(VOCAB_IMAGE_W * sampled_coor[0] / img_width)
614
+ point_y1 = int(VOCAB_IMAGE_H * sampled_coor[1] / img_height)
615
+ point_x2 = int(VOCAB_IMAGE_W * sampled_coor[2] / img_width)
616
+ point_y2 = int(VOCAB_IMAGE_H * sampled_coor[3] / img_height)
617
+ cur_region_coordinates = f'[{int(point_x1)}, {int(point_y1)}, {int(point_x2)}, {int(point_y2)}]'
618
+
619
+ cur_region_id = len(refer_input_state['region_placeholder_tokens'])
620
+ cur_region_token = DEFAULT_REGION_REFER_TOKEN.split(']')[0] + str(cur_region_id) + ']'
621
+ refer_input_state['region_placeholder_tokens'].append(cur_region_token)
622
+ refer_input_state['region_coordinates'].append(cur_region_coordinates)
623
+ refer_input_state['region_masks'].append(cur_region_masks)
624
+ assert len(refer_input_state['region_masks']) == len(refer_input_state['region_coordinates']) == len(refer_input_state['region_placeholder_tokens'])
625
+ refer_text_show.append((cur_region_token, ''))
626
+
627
+ # Show Parsed Referring.
628
+ imagebox_refer = draw_box(sampled_coor, cur_region_masks, \
629
+ cur_region_token, imagebox_refer, input_mode)
630
+
631
+ return (refer_input_state, refer_text_show, imagebox_refer)
632
+
633
+ def build_demo(embed_mode):
634
+ textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", visible=False, container=False)
635
+ with gr.Blocks(title="FERRET", theme=gr.themes.Base(), css=css) as demo:
636
+ state = gr.State()
637
+
638
+ if not embed_mode:
639
+ gr.Markdown(title_markdown)
640
+ gr.Markdown(Instructions)
641
+
642
+ with gr.Row():
643
+ with gr.Column(scale=4):
644
+ with gr.Row(elem_id="model_selector_row"):
645
+ model_selector = gr.Dropdown(
646
+ choices=models,
647
+ value=models[0] if len(models) > 0 else "",
648
+ interactive=True,
649
+ show_label=False,
650
+ container=False)
651
+
652
+ original_image = gr.Image(type="pil", visible=False)
653
+ image_process_mode = gr.Radio(
654
+ ["Raw+Processor", "Crop", "Resize", "Pad"],
655
+ value="Raw+Processor",
656
+ label="Preprocess for non-square image",
657
+ visible=False)
658
+
659
+ # Added for any-format input.
660
+ sketch_pad = ImageMask(label="Image & Sketch", type="pil", elem_id="img2text")
661
+ refer_input_mode = gr.Radio(
662
+ ["Point", "Box", "Sketch"],
663
+ value="Point",
664
+ label="Referring Input Type")
665
+ refer_input_state = gr.State({'region_placeholder_tokens':[],
666
+ 'region_coordinates':[],
667
+ 'region_masks':[],
668
+ 'region_masks_in_prompts':[],
669
+ 'masks':[],
670
+ })
671
+ refer_text_show = gr.HighlightedText(value=[], label="Referring Input Cache")
672
+
673
+ imagebox_refer = gr.Image(type="pil", label="Parsed Referring Input")
674
+ imagebox_output = gr.Image(type="pil", label='Output Vis')
675
+
676
+ cur_dir = os.path.dirname(os.path.abspath(__file__))
677
+ # gr.Examples(examples=[
678
+ # # [f"{cur_dir}/examples/harry-potter-hogwarts.jpg", "What is in [region0]? And what do people use it for?"],
679
+ # # [f"{cur_dir}/examples/ingredients.jpg", "What objects are in [region0] and [region1]?"],
680
+ # # [f"{cur_dir}/examples/extreme_ironing.jpg", "What is unusual about this image? And tell me the coordinates of mentioned objects."],
681
+ # [f"{cur_dir}/examples/ferret.jpg", "What's the relationship between object [region0] and object [region1]?"],
682
+ # [f"{cur_dir}/examples/waterview.jpg", "What are the things I should be cautious about when I visit here? Tell me the coordinates in response."],
683
+ # [f"{cur_dir}/examples/flickr_9472793441.jpg", "Describe the image in details."],
684
+ # # [f"{cur_dir}/examples/coco_000000281759.jpg", "What are the locations of the woman wearing a blue dress, the woman in flowery top, the girl in purple dress, the girl wearing green shirt?"],
685
+ # [f"{cur_dir}/examples/room_planning.jpg", "How to improve the design of the given room?"],
686
+ # [f"{cur_dir}/examples/make_sandwitch.jpg", "How can I make a sandwich with available ingredients?"],
687
+ # [f"{cur_dir}/examples/bathroom.jpg", "What is unusual about this image?"],
688
+ # [f"{cur_dir}/examples/kitchen.png", "Is the object a man or a chicken? Explain the reason."],
689
+ # ], inputs=[sketch_pad, textbox])
690
+
691
+ with gr.Accordion("Parameters", open=False, visible=False) as parameter_row:
692
+ temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.2, step=0.1, interactive=True, label="Temperature",)
693
+ top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.7, step=0.1, interactive=True, label="Top P",)
694
+ max_output_tokens = gr.Slider(minimum=0, maximum=1024, value=512, step=64, interactive=True, label="Max output tokens",)
695
+
696
+ with gr.Column(scale=5):
697
+ chatbot = gr.Chatbot(elem_id="chatbot", label="FERRET", visible=False).style(height=750)
698
+ with gr.Row():
699
+ with gr.Column(scale=8):
700
+ textbox.render()
701
+ with gr.Column(scale=1, min_width=60):
702
+ submit_btn = gr.Button(value="Submit", visible=False)
703
+ with gr.Row(visible=False) as button_row:
704
+ upvote_btn = gr.Button(value="πŸ‘ Upvote", interactive=False)
705
+ downvote_btn = gr.Button(value="πŸ‘Ž Downvote", interactive=False)
706
+ # flag_btn = gr.Button(value="⚠️ Flag", interactive=False)
707
+ #stop_btn = gr.Button(value="⏹️ Stop Generation", interactive=False)
708
+ regenerate_btn = gr.Button(value="πŸ”„ Regenerate", interactive=False)
709
+ clear_btn = gr.Button(value="πŸ—‘οΈ Clear history", interactive=False)
710
+ location_btn = gr.Button(value="πŸͺ„ Show location", interactive=False)
711
+
712
+ if not embed_mode:
713
+ gr.Markdown(tos_markdown)
714
+ gr.Markdown(learn_more_markdown)
715
+ url_params = gr.JSON(visible=False)
716
+
717
+ # Register listeners
718
+ btn_list = [upvote_btn, downvote_btn, location_btn, regenerate_btn, clear_btn]
719
+ upvote_btn.click(upvote_last_response,
720
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, location_btn])
721
+ downvote_btn.click(downvote_last_response,
722
+ [state, model_selector], [textbox, upvote_btn, downvote_btn, location_btn])
723
+ # flag_btn.click(flag_last_response,
724
+ # [state, model_selector], [textbox, upvote_btn, downvote_btn, flag_btn])
725
+ regenerate_btn.click(regenerate, [state, image_process_mode],
726
+ [state, chatbot, textbox] + btn_list).then(
727
+ http_bot, [state, model_selector, temperature, top_p, max_output_tokens, refer_input_state],
728
+ [state, chatbot] + btn_list)
729
+ clear_btn.click(clear_history, None, [state, chatbot, textbox, imagebox_output, original_image] + btn_list + \
730
+ [sketch_pad, refer_input_state, refer_text_show, imagebox_refer])
731
+ location_btn.click(show_location,
732
+ [sketch_pad, chatbot], [imagebox_output, chatbot, location_btn])
733
+
734
+ textbox.submit(add_text, [state, textbox, image_process_mode, original_image, sketch_pad], [state, chatbot, textbox, original_image] + btn_list
735
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens, refer_input_state],
736
+ [state, chatbot] + btn_list)
737
+
738
+ submit_btn.click(add_text, [state, textbox, image_process_mode, original_image, sketch_pad], [state, chatbot, textbox, original_image] + btn_list
739
+ ).then(http_bot, [state, model_selector, temperature, top_p, max_output_tokens, refer_input_state],
740
+ [state, chatbot] + btn_list)
741
+
742
+ sketch_pad.edit(
743
+ draw,
744
+ inputs=[refer_input_mode, sketch_pad, refer_input_state, refer_text_show, imagebox_refer],
745
+ outputs=[refer_input_state, refer_text_show, imagebox_refer],
746
+ queue=True,
747
+ )
748
+
749
+ if args.model_list_mode == "once":
750
+ demo.load(load_demo, [url_params], [state, model_selector,
751
+ chatbot, textbox, submit_btn, button_row, parameter_row],
752
+ _js=get_window_url_params)
753
+ elif args.model_list_mode == "reload":
754
+ demo.load(load_demo_refresh_model_list, None, [state, model_selector,
755
+ chatbot, textbox, submit_btn, button_row, parameter_row])
756
+ else:
757
+ raise ValueError(f"Unknown model list mode: {args.model_list_mode}")
758
+
759
+ return demo
760
+
761
+
762
+ if __name__ == "__main__":
763
+ parser = argparse.ArgumentParser()
764
+ parser.add_argument("--host", type=str, default="0.0.0.0")
765
+ parser.add_argument("--port", type=int)
766
+ parser.add_argument("--controller-url", type=str, default="http://localhost:21001")
767
+ parser.add_argument("--concurrency-count", type=int, default=8)
768
+ parser.add_argument("--model-list-mode", type=str, default="once",
769
+ choices=["once", "reload"])
770
+ parser.add_argument("--share", action="store_true")
771
+ parser.add_argument("--moderate", action="store_true")
772
+ parser.add_argument("--embed", action="store_true")
773
+ parser.add_argument("--add_region_feature", action="store_true")
774
+ args = parser.parse_args()
775
+ logger.info(f"args: {args}")
776
+
777
+ models = get_model_list()
778
+
779
+ logger.info(args)
780
+ demo = build_demo(args.embed)
781
+ demo.queue(concurrency_count=args.concurrency_count, status_update_rate=10,
782
+ api_open=False).launch(
783
+ server_name=args.host, server_port=args.port, share=True)