aifeifei798 commited on
Commit
1cf97f4
1 Parent(s): 1f2d928

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +266 -0
  2. pre-requirements.txt +1 -0
  3. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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
+ css = """
219
+ #output {
220
+ height: 500px;
221
+ overflow: auto;
222
+ border: 1px solid #ccc;
223
+ }
224
+ """
225
+
226
+
227
+ single_task_list =[
228
+ 'Caption', 'Detailed Caption', 'More Detailed Caption', 'Object Detection',
229
+ 'Dense Region Caption', 'Region Proposal', 'Caption to Phrase Grounding',
230
+ 'Referring Expression Segmentation', 'Region to Segmentation',
231
+ 'Open Vocabulary Detection', 'Region to Category', 'Region to Description',
232
+ 'OCR', 'OCR with Region'
233
+ ]
234
+
235
+ cascased_task_list =[
236
+ 'Caption + Grounding', 'Detailed Caption + Grounding', 'More Detailed Caption + Grounding'
237
+ ]
238
+
239
+
240
+ def update_task_dropdown(choice):
241
+ if choice == 'Cascased task':
242
+ return gr.Dropdown(choices=cascased_task_list, value='Caption + Grounding')
243
+ else:
244
+ return gr.Dropdown(choices=single_task_list, value='Caption')
245
+
246
+
247
+
248
+ with gr.Blocks(css=css) as demo:
249
+ gr.Markdown(DESCRIPTION)
250
+ with gr.Tab(label="Florence-2 Image to Flux Prompt"):
251
+ with gr.Row():
252
+ with gr.Column():
253
+ input_img = gr.Image(label="Input Picture",hight=320)
254
+ model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value='microsoft/Florence-2-base')
255
+ task_type = gr.Radio(choices=['Single task', 'Cascased task'], label='Task type selector', value='Single task')
256
+ task_prompt = gr.Dropdown(choices=single_task_list, label="Task Prompt", value="More Detailed Caption")
257
+ task_type.change(fn=update_task_dropdown, inputs=task_type, outputs=task_prompt)
258
+ text_input = gr.Textbox(label="Text Input (optional)")
259
+ submit_btn = gr.Button(value="Submit")
260
+ with gr.Column():
261
+ output_text = gr.Textbox(label="Output Text")
262
+ output_img = gr.Image(label="Output Image")
263
+
264
+ submit_btn.click(process_image, [input_img, task_prompt, text_input, model_selector], [output_text, output_img])
265
+
266
+ demo.launch(debug=True)
pre-requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ pip>=23.0.0
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ spaces
2
+ transformers
3
+ timm