aifeifei798 commited on
Commit
b3837a7
·
verified ·
1 Parent(s): 03c97ae

Upload 4 files

Browse files
Files changed (3) hide show
  1. app.py +15 -266
  2. feifeilib/feifeiflorencebase.py +236 -0
  3. requirements.txt +1 -2
app.py CHANGED
@@ -1,267 +1,16 @@
1
- import gradio as gr
2
- from transformers import AutoProcessor, AutoModelForCausalLM
3
- import spaces
4
-
5
- import requests
6
- import copy
7
-
8
- from PIL import Image, ImageDraw, ImageFont
9
- import io
10
- import matplotlib.pyplot as plt
11
- import matplotlib.patches as patches
12
-
13
- import random
14
- import numpy as np
15
-
16
- import subprocess
17
- subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
18
-
19
- models = {
20
- 'microsoft/Florence-2-base': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True).to("cuda").eval()
21
- }
22
-
23
- processors = {
24
- 'microsoft/Florence-2-base': AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
25
- }
26
-
27
-
28
- DESCRIPTION = "# [Florence-2 Image to Flux Prompt](https://huggingface.co/microsoft/Florence-2-base)"
29
-
30
- colormap = ['blue','orange','green','purple','brown','pink','gray','olive','cyan','red',
31
- 'lime','indigo','violet','aqua','magenta','coral','gold','tan','skyblue']
32
-
33
- def fig_to_pil(fig):
34
- buf = io.BytesIO()
35
- fig.savefig(buf, format='png')
36
- buf.seek(0)
37
- return Image.open(buf)
38
-
39
- @spaces.GPU
40
- def run_example(task_prompt, image, text_input=None, model_id='microsoft/Florence-2-large'):
41
- model = models[model_id]
42
- processor = processors[model_id]
43
- if text_input is None:
44
- prompt = task_prompt
45
- else:
46
- prompt = task_prompt + text_input
47
- inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
48
- generated_ids = model.generate(
49
- input_ids=inputs["input_ids"],
50
- pixel_values=inputs["pixel_values"],
51
- max_new_tokens=1024,
52
- early_stopping=False,
53
- do_sample=False,
54
- num_beams=3,
55
- )
56
- generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
57
- parsed_answer = processor.post_process_generation(
58
- generated_text,
59
- task=task_prompt,
60
- image_size=(image.width, image.height)
61
- )
62
- return parsed_answer
63
-
64
- def plot_bbox(image, data):
65
- fig, ax = plt.subplots()
66
- ax.imshow(image)
67
- for bbox, label in zip(data['bboxes'], data['labels']):
68
- x1, y1, x2, y2 = bbox
69
- rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
70
- ax.add_patch(rect)
71
- plt.text(x1, y1, label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5))
72
- ax.axis('off')
73
- return fig
74
-
75
- def draw_polygons(image, prediction, fill_mask=False):
76
-
77
- draw = ImageDraw.Draw(image)
78
- scale = 1
79
- for polygons, label in zip(prediction['polygons'], prediction['labels']):
80
- color = random.choice(colormap)
81
- fill_color = random.choice(colormap) if fill_mask else None
82
- for _polygon in polygons:
83
- _polygon = np.array(_polygon).reshape(-1, 2)
84
- if len(_polygon) < 3:
85
- print('Invalid polygon:', _polygon)
86
- continue
87
- _polygon = (_polygon * scale).reshape(-1).tolist()
88
- if fill_mask:
89
- draw.polygon(_polygon, outline=color, fill=fill_color)
90
- else:
91
- draw.polygon(_polygon, outline=color)
92
- draw.text((_polygon[0] + 8, _polygon[1] + 2), label, fill=color)
93
- return image
94
-
95
- def convert_to_od_format(data):
96
- bboxes = data.get('bboxes', [])
97
- labels = data.get('bboxes_labels', [])
98
- od_results = {
99
- 'bboxes': bboxes,
100
- 'labels': labels
101
- }
102
- return od_results
103
-
104
- def draw_ocr_bboxes(image, prediction):
105
- scale = 1
106
- draw = ImageDraw.Draw(image)
107
- bboxes, labels = prediction['quad_boxes'], prediction['labels']
108
- for box, label in zip(bboxes, labels):
109
- color = random.choice(colormap)
110
- new_box = (np.array(box) * scale).tolist()
111
- draw.polygon(new_box, width=3, outline=color)
112
- draw.text((new_box[0]+8, new_box[1]+2),
113
- "{}".format(label),
114
- align="right",
115
- fill=color)
116
- return image
117
-
118
- def process_image(image, task_prompt, text_input=None, model_id='microsoft/Florence-2-base'):
119
- image = Image.fromarray(image) # Convert NumPy array to PIL Image
120
- if task_prompt == 'Caption':
121
- task_prompt = '<CAPTION>'
122
- results = run_example(task_prompt, image, model_id=model_id)
123
- return results, None
124
- elif task_prompt == 'Detailed Caption':
125
- task_prompt = '<DETAILED_CAPTION>'
126
- results = run_example(task_prompt, image, model_id=model_id)
127
- return results, None
128
- elif task_prompt == 'More Detailed Caption':
129
- task_prompt = '<MORE_DETAILED_CAPTION>'
130
- results = run_example(task_prompt, image, model_id=model_id)
131
- results = results['<MORE_DETAILED_CAPTION>']
132
- return results, None
133
- elif task_prompt == 'Caption + Grounding':
134
- task_prompt = '<CAPTION>'
135
- results = run_example(task_prompt, image, model_id=model_id)
136
- text_input = results[task_prompt]
137
- task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
138
- results = run_example(task_prompt, image, text_input, model_id)
139
- results['<CAPTION>'] = text_input
140
- fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
141
- return results, fig_to_pil(fig)
142
- elif task_prompt == 'Detailed Caption + Grounding':
143
- task_prompt = '<DETAILED_CAPTION>'
144
- results = run_example(task_prompt, image, model_id=model_id)
145
- text_input = results[task_prompt]
146
- task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
147
- results = run_example(task_prompt, image, text_input, model_id)
148
- results['<DETAILED_CAPTION>'] = text_input
149
- fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
150
- return results, fig_to_pil(fig)
151
- elif task_prompt == 'More Detailed Caption + Grounding':
152
- task_prompt = '<MORE_DETAILED_CAPTION>'
153
- results = run_example(task_prompt, image, model_id=model_id)
154
- text_input = results[task_prompt]
155
- task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
156
- results = run_example(task_prompt, image, text_input, model_id)
157
- results['<MORE_DETAILED_CAPTION>'] = text_input
158
- fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
159
- return results, fig_to_pil(fig)
160
- elif task_prompt == 'Object Detection':
161
- task_prompt = '<OD>'
162
- results = run_example(task_prompt, image, model_id=model_id)
163
- fig = plot_bbox(image, results['<OD>'])
164
- return results, fig_to_pil(fig)
165
- elif task_prompt == 'Dense Region Caption':
166
- task_prompt = '<DENSE_REGION_CAPTION>'
167
- results = run_example(task_prompt, image, model_id=model_id)
168
- fig = plot_bbox(image, results['<DENSE_REGION_CAPTION>'])
169
- return results, fig_to_pil(fig)
170
- elif task_prompt == 'Region Proposal':
171
- task_prompt = '<REGION_PROPOSAL>'
172
- results = run_example(task_prompt, image, model_id=model_id)
173
- fig = plot_bbox(image, results['<REGION_PROPOSAL>'])
174
- return results, fig_to_pil(fig)
175
- elif task_prompt == 'Caption to Phrase Grounding':
176
- task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
177
- results = run_example(task_prompt, image, text_input, model_id)
178
- fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
179
- return results, fig_to_pil(fig)
180
- elif task_prompt == 'Referring Expression Segmentation':
181
- task_prompt = '<REFERRING_EXPRESSION_SEGMENTATION>'
182
- results = run_example(task_prompt, image, text_input, model_id)
183
- output_image = copy.deepcopy(image)
184
- output_image = draw_polygons(output_image, results['<REFERRING_EXPRESSION_SEGMENTATION>'], fill_mask=True)
185
- return results, output_image
186
- elif task_prompt == 'Region to Segmentation':
187
- task_prompt = '<REGION_TO_SEGMENTATION>'
188
- results = run_example(task_prompt, image, text_input, model_id)
189
- output_image = copy.deepcopy(image)
190
- output_image = draw_polygons(output_image, results['<REGION_TO_SEGMENTATION>'], fill_mask=True)
191
- return results, output_image
192
- elif task_prompt == 'Open Vocabulary Detection':
193
- task_prompt = '<OPEN_VOCABULARY_DETECTION>'
194
- results = run_example(task_prompt, image, text_input, model_id)
195
- bbox_results = convert_to_od_format(results['<OPEN_VOCABULARY_DETECTION>'])
196
- fig = plot_bbox(image, bbox_results)
197
- return results, fig_to_pil(fig)
198
- elif task_prompt == 'Region to Category':
199
- task_prompt = '<REGION_TO_CATEGORY>'
200
- results = run_example(task_prompt, image, text_input, model_id)
201
- return results, None
202
- elif task_prompt == 'Region to Description':
203
- task_prompt = '<REGION_TO_DESCRIPTION>'
204
- results = run_example(task_prompt, image, text_input, model_id)
205
- return results, None
206
- elif task_prompt == 'OCR':
207
- task_prompt = '<OCR>'
208
- results = run_example(task_prompt, image, model_id=model_id)
209
- return results, None
210
- elif task_prompt == 'OCR with Region':
211
- task_prompt = '<OCR_WITH_REGION>'
212
- results = run_example(task_prompt, image, model_id=model_id)
213
- output_image = copy.deepcopy(image)
214
- output_image = draw_ocr_bboxes(output_image, results['<OCR_WITH_REGION>'])
215
- return results, output_image
216
- else:
217
- return "", None # Return empty string and None for unknown task prompts
218
-
219
- css = """
220
- #output {
221
- height: 500px;
222
- overflow: auto;
223
- border: 1px solid #ccc;
224
- }
225
- """
226
-
227
-
228
- single_task_list =[
229
- 'Caption', 'Detailed Caption', 'More Detailed Caption', 'Object Detection',
230
- 'Dense Region Caption', 'Region Proposal', 'Caption to Phrase Grounding',
231
- 'Referring Expression Segmentation', 'Region to Segmentation',
232
- 'Open Vocabulary Detection', 'Region to Category', 'Region to Description',
233
- 'OCR', 'OCR with Region'
234
- ]
235
-
236
- cascased_task_list =[
237
- 'Caption + Grounding', 'Detailed Caption + Grounding', 'More Detailed Caption + Grounding'
238
- ]
239
-
240
-
241
- def update_task_dropdown(choice):
242
- if choice == 'Cascased task':
243
- return gr.Dropdown(choices=cascased_task_list, value='Caption + Grounding')
244
- else:
245
- return gr.Dropdown(choices=single_task_list, value='Caption')
246
-
247
-
248
-
249
- with gr.Blocks(css=css) as demo:
250
- gr.Markdown(DESCRIPTION)
251
- with gr.Tab(label="Florence-2 Image to Flux Prompt"):
252
- with gr.Row():
253
- with gr.Column():
254
- input_img = gr.Image(label="Input Picture",height=320)
255
- model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value='microsoft/Florence-2-base')
256
- task_type = gr.Radio(choices=['Single task', 'Cascased task'], label='Task type selector', value='Single task')
257
- task_prompt = gr.Dropdown(choices=single_task_list, label="Task Prompt", value="More Detailed Caption")
258
- task_type.change(fn=update_task_dropdown, inputs=task_type, outputs=task_prompt)
259
- text_input = gr.Textbox(label="Text Input (optional)")
260
- submit_btn = gr.Button(value="Submit")
261
- with gr.Column():
262
- output_text = gr.Textbox(label="Output Text")
263
- output_img = gr.Image(label="Output Image")
264
-
265
- submit_btn.click(process_image, [input_img, task_prompt, text_input, model_selector], [output_text, output_img])
266
-
267
  demo.launch(debug=True)
 
1
+ import gradio as gr
2
+ from feifeilib.feifeiflorencebase import process_image
3
+
4
+ with gr.Blocks(css=css) as demo:
5
+ gr.Markdown(DESCRIPTION)
6
+ with gr.Tab(label="Florence-2 Image to Flux Prompt"):
7
+ with gr.Row():
8
+ with gr.Column():
9
+ input_img = gr.Image(label="Input Picture",hight=320)
10
+ submit_btn = gr.Button(value="Submit")
11
+ with gr.Column():
12
+ output_text = gr.Textbox(label="Output Text")
13
+
14
+ submit_btn.click(process_image, [input_img], [output_text])
15
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  demo.launch(debug=True)
feifeilib/feifeiflorencebase.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoProcessor, AutoModelForCausalLM
3
+ import spaces
4
+
5
+ import requests
6
+ import copy
7
+
8
+ from PIL import Image, ImageDraw, ImageFont
9
+ import io
10
+ import matplotlib.pyplot as plt
11
+ import matplotlib.patches as patches
12
+
13
+ import random
14
+ import numpy as np
15
+
16
+ import subprocess
17
+ subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
18
+
19
+ models = {
20
+ 'microsoft/Florence-2-base': AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True).to("cuda").eval()
21
+ }
22
+
23
+ processors = {
24
+ 'microsoft/Florence-2-base': AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
25
+ }
26
+
27
+
28
+ DESCRIPTION = "# [Florence-2 Image to Flux Prompt](https://huggingface.co/microsoft/Florence-2-base)"
29
+
30
+ colormap = ['blue','orange','green','purple','brown','pink','gray','olive','cyan','red',
31
+ 'lime','indigo','violet','aqua','magenta','coral','gold','tan','skyblue']
32
+
33
+ def fig_to_pil(fig):
34
+ buf = io.BytesIO()
35
+ fig.savefig(buf, format='png')
36
+ buf.seek(0)
37
+ return Image.open(buf)
38
+
39
+ @spaces.GPU
40
+ def run_example(task_prompt = "More Detailed Caption", image, text_input=None, model_id='microsoft/Florence-2-base', progress=gr.Progress(track_tqdm=True)):
41
+ model = models[model_id]
42
+ processor = processors[model_id]
43
+ if text_input is None:
44
+ prompt = task_prompt
45
+ else:
46
+ prompt = task_prompt + text_input
47
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to("cuda")
48
+ generated_ids = model.generate(
49
+ input_ids=inputs["input_ids"],
50
+ pixel_values=inputs["pixel_values"],
51
+ max_new_tokens=1024,
52
+ early_stopping=False,
53
+ do_sample=False,
54
+ num_beams=3,
55
+ )
56
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
57
+ parsed_answer = processor.post_process_generation(
58
+ generated_text,
59
+ task=task_prompt,
60
+ image_size=(image.width, image.height)
61
+ )
62
+ return parsed_answer
63
+
64
+ def plot_bbox(image, data):
65
+ fig, ax = plt.subplots()
66
+ ax.imshow(image)
67
+ for bbox, label in zip(data['bboxes'], data['labels']):
68
+ x1, y1, x2, y2 = bbox
69
+ rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
70
+ ax.add_patch(rect)
71
+ plt.text(x1, y1, label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5))
72
+ ax.axis('off')
73
+ return fig
74
+
75
+ def draw_polygons(image, prediction, fill_mask=False):
76
+
77
+ draw = ImageDraw.Draw(image)
78
+ scale = 1
79
+ for polygons, label in zip(prediction['polygons'], prediction['labels']):
80
+ color = random.choice(colormap)
81
+ fill_color = random.choice(colormap) if fill_mask else None
82
+ for _polygon in polygons:
83
+ _polygon = np.array(_polygon).reshape(-1, 2)
84
+ if len(_polygon) < 3:
85
+ print('Invalid polygon:', _polygon)
86
+ continue
87
+ _polygon = (_polygon * scale).reshape(-1).tolist()
88
+ if fill_mask:
89
+ draw.polygon(_polygon, outline=color, fill=fill_color)
90
+ else:
91
+ draw.polygon(_polygon, outline=color)
92
+ draw.text((_polygon[0] + 8, _polygon[1] + 2), label, fill=color)
93
+ return image
94
+
95
+ def convert_to_od_format(data):
96
+ bboxes = data.get('bboxes', [])
97
+ labels = data.get('bboxes_labels', [])
98
+ od_results = {
99
+ 'bboxes': bboxes,
100
+ 'labels': labels
101
+ }
102
+ return od_results
103
+
104
+ def draw_ocr_bboxes(image, prediction):
105
+ scale = 1
106
+ draw = ImageDraw.Draw(image)
107
+ bboxes, labels = prediction['quad_boxes'], prediction['labels']
108
+ for box, label in zip(bboxes, labels):
109
+ color = random.choice(colormap)
110
+ new_box = (np.array(box) * scale).tolist()
111
+ draw.polygon(new_box, width=3, outline=color)
112
+ draw.text((new_box[0]+8, new_box[1]+2),
113
+ "{}".format(label),
114
+ align="right",
115
+ fill=color)
116
+ return image
117
+
118
+ def process_image(image, task_prompt = "More Detailed Caption", text_input=None, model_id='microsoft/Florence-2-base'):
119
+ image = Image.fromarray(image) # Convert NumPy array to PIL Image
120
+ if task_prompt == 'Caption':
121
+ task_prompt = '<CAPTION>'
122
+ results = run_example(task_prompt, image, model_id=model_id)
123
+ return results, None
124
+ elif task_prompt == 'Detailed Caption':
125
+ task_prompt = '<DETAILED_CAPTION>'
126
+ results = run_example(task_prompt, image, model_id=model_id)
127
+ return results, None
128
+ elif task_prompt == 'More Detailed Caption':
129
+ task_prompt = '<MORE_DETAILED_CAPTION>'
130
+ results = run_example(task_prompt, image, model_id=model_id)
131
+ return results, None
132
+ elif task_prompt == 'Caption + Grounding':
133
+ task_prompt = '<CAPTION>'
134
+ results = run_example(task_prompt, image, model_id=model_id)
135
+ text_input = results[task_prompt]
136
+ task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
137
+ results = run_example(task_prompt, image, text_input, model_id)
138
+ results['<CAPTION>'] = text_input
139
+ fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
140
+ return results, fig_to_pil(fig)
141
+ elif task_prompt == 'Detailed Caption + Grounding':
142
+ task_prompt = '<DETAILED_CAPTION>'
143
+ results = run_example(task_prompt, image, model_id=model_id)
144
+ text_input = results[task_prompt]
145
+ task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
146
+ results = run_example(task_prompt, image, text_input, model_id)
147
+ results['<DETAILED_CAPTION>'] = text_input
148
+ fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
149
+ return results, fig_to_pil(fig)
150
+ elif task_prompt == 'More Detailed Caption + Grounding':
151
+ task_prompt = '<MORE_DETAILED_CAPTION>'
152
+ results = run_example(task_prompt, image, model_id=model_id)
153
+ text_input = results[task_prompt]
154
+ task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
155
+ results = run_example(task_prompt, image, text_input, model_id)
156
+ results['<MORE_DETAILED_CAPTION>'] = text_input
157
+ fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
158
+ return results, fig_to_pil(fig)
159
+ elif task_prompt == 'Object Detection':
160
+ task_prompt = '<OD>'
161
+ results = run_example(task_prompt, image, model_id=model_id)
162
+ fig = plot_bbox(image, results['<OD>'])
163
+ return results, fig_to_pil(fig)
164
+ elif task_prompt == 'Dense Region Caption':
165
+ task_prompt = '<DENSE_REGION_CAPTION>'
166
+ results = run_example(task_prompt, image, model_id=model_id)
167
+ fig = plot_bbox(image, results['<DENSE_REGION_CAPTION>'])
168
+ return results, fig_to_pil(fig)
169
+ elif task_prompt == 'Region Proposal':
170
+ task_prompt = '<REGION_PROPOSAL>'
171
+ results = run_example(task_prompt, image, model_id=model_id)
172
+ fig = plot_bbox(image, results['<REGION_PROPOSAL>'])
173
+ return results, fig_to_pil(fig)
174
+ elif task_prompt == 'Caption to Phrase Grounding':
175
+ task_prompt = '<CAPTION_TO_PHRASE_GROUNDING>'
176
+ results = run_example(task_prompt, image, text_input, model_id)
177
+ fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
178
+ return results, fig_to_pil(fig)
179
+ elif task_prompt == 'Referring Expression Segmentation':
180
+ task_prompt = '<REFERRING_EXPRESSION_SEGMENTATION>'
181
+ results = run_example(task_prompt, image, text_input, model_id)
182
+ output_image = copy.deepcopy(image)
183
+ output_image = draw_polygons(output_image, results['<REFERRING_EXPRESSION_SEGMENTATION>'], fill_mask=True)
184
+ return results, output_image
185
+ elif task_prompt == 'Region to Segmentation':
186
+ task_prompt = '<REGION_TO_SEGMENTATION>'
187
+ results = run_example(task_prompt, image, text_input, model_id)
188
+ output_image = copy.deepcopy(image)
189
+ output_image = draw_polygons(output_image, results['<REGION_TO_SEGMENTATION>'], fill_mask=True)
190
+ return results, output_image
191
+ elif task_prompt == 'Open Vocabulary Detection':
192
+ task_prompt = '<OPEN_VOCABULARY_DETECTION>'
193
+ results = run_example(task_prompt, image, text_input, model_id)
194
+ bbox_results = convert_to_od_format(results['<OPEN_VOCABULARY_DETECTION>'])
195
+ fig = plot_bbox(image, bbox_results)
196
+ return results, fig_to_pil(fig)
197
+ elif task_prompt == 'Region to Category':
198
+ task_prompt = '<REGION_TO_CATEGORY>'
199
+ results = run_example(task_prompt, image, text_input, model_id)
200
+ return results, None
201
+ elif task_prompt == 'Region to Description':
202
+ task_prompt = '<REGION_TO_DESCRIPTION>'
203
+ results = run_example(task_prompt, image, text_input, model_id)
204
+ return results, None
205
+ elif task_prompt == 'OCR':
206
+ task_prompt = '<OCR>'
207
+ results = run_example(task_prompt, image, model_id=model_id)
208
+ return results, None
209
+ elif task_prompt == 'OCR with Region':
210
+ task_prompt = '<OCR_WITH_REGION>'
211
+ results = run_example(task_prompt, image, model_id=model_id)
212
+ output_image = copy.deepcopy(image)
213
+ output_image = draw_ocr_bboxes(output_image, results['<OCR_WITH_REGION>'])
214
+ return results, output_image
215
+ else:
216
+ return "", None # Return empty string and None for unknown task prompts
217
+
218
+
219
+ single_task_list =[
220
+ 'Caption', 'Detailed Caption', 'More Detailed Caption', 'Object Detection',
221
+ 'Dense Region Caption', 'Region Proposal', 'Caption to Phrase Grounding',
222
+ 'Referring Expression Segmentation', 'Region to Segmentation',
223
+ 'Open Vocabulary Detection', 'Region to Category', 'Region to Description',
224
+ 'OCR', 'OCR with Region'
225
+ ]
226
+
227
+ cascased_task_list =[
228
+ 'Caption + Grounding', 'Detailed Caption + Grounding', 'More Detailed Caption + Grounding'
229
+ ]
230
+
231
+
232
+ def update_task_dropdown(choice):
233
+ if choice == 'Cascased task':
234
+ return gr.Dropdown(choices=cascased_task_list, value='Caption + Grounding')
235
+ else:
236
+ return gr.Dropdown(choices=single_task_list, value='Caption')
requirements.txt CHANGED
@@ -1,4 +1,3 @@
1
  spaces
2
  transformers
3
- timm
4
- matplotlib
 
1
  spaces
2
  transformers
3
+ timm