Spaces:
Running
on
Zero
Running
on
Zero
Commit
•
1d51385
1
Parent(s):
4a43fef
Update app.py
Browse files
app.py
CHANGED
@@ -1,19 +1,22 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import
|
3 |
-
from PIL import Image
|
4 |
import requests
|
|
|
5 |
import matplotlib.pyplot as plt
|
6 |
import matplotlib.patches as patches
|
7 |
-
import numpy as np
|
8 |
import random
|
|
|
9 |
|
10 |
-
# Load model and processor
|
11 |
model_id = 'microsoft/Florence-2-large'
|
12 |
model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True).eval()
|
13 |
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
14 |
|
15 |
def run_example(task_prompt, image, text_input=None):
|
16 |
-
|
|
|
|
|
|
|
17 |
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
18 |
generated_ids = model.generate(
|
19 |
input_ids=inputs["input_ids"],
|
@@ -25,8 +28,8 @@ def run_example(task_prompt, image, text_input=None):
|
|
25 |
)
|
26 |
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
|
27 |
parsed_answer = processor.post_process_generation(
|
28 |
-
generated_text,
|
29 |
-
task=task_prompt,
|
30 |
image_size=(image.width, image.height)
|
31 |
)
|
32 |
return parsed_answer
|
@@ -39,43 +42,147 @@ def plot_bbox(image, data):
|
|
39 |
rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
|
40 |
ax.add_patch(rect)
|
41 |
plt.text(x1, y1, label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5))
|
42 |
-
|
43 |
-
|
44 |
|
45 |
def draw_polygons(image, prediction, fill_mask=False):
|
46 |
draw = ImageDraw.Draw(image)
|
47 |
-
|
48 |
for polygons, label in zip(prediction['polygons'], prediction['labels']):
|
49 |
color = random.choice(colormap)
|
50 |
-
fill_color =
|
51 |
-
for
|
52 |
-
|
53 |
-
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
|
65 |
-
gr.Markdown("## Florence Model Advanced Tasks")
|
66 |
-
with gr.Row():
|
67 |
-
image_input = gr.Image(type="pil")
|
68 |
-
task_input = gr.Dropdown(label="Select Task", choices=[
|
69 |
-
'<CAPTION>', '<DETAILED_CAPTION>', '<MORE_DETAILED_CAPTION>',
|
70 |
-
'<OD>', '<DENSE_REGION_CAPTION>', '<REGION_PROPOSAL>',
|
71 |
-
'<CAPTION_TO_PHRASE_GROUNDING>', '<REFERRING_EXPRESSION_SEGMENTATION>',
|
72 |
-
'<REGION_TO_SEGMENTATION>', '<OPEN_VOCABULARY_DETECTION>',
|
73 |
-
'<REGION_TO_CATEGORY>', '<REGION_TO_DESCRIPTION>', '<OCR>', '<OCR_WITH_REGION>'
|
74 |
-
])
|
75 |
-
text_input = gr.Textbox(label="Optional Text Input", placeholder="Enter text here if required by the task")
|
76 |
-
submit_btn = gr.Button("Run Task")
|
77 |
-
output = gr.Textbox(label="Output")
|
78 |
-
|
79 |
-
submit_btn.click(fn=gradio_interface, inputs=[image_input, task_input, text_input], outputs=output)
|
80 |
|
81 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
3 |
+
from PIL import Image
|
4 |
import requests
|
5 |
+
import copy
|
6 |
import matplotlib.pyplot as plt
|
7 |
import matplotlib.patches as patches
|
|
|
8 |
import random
|
9 |
+
import numpy as np
|
10 |
|
|
|
11 |
model_id = 'microsoft/Florence-2-large'
|
12 |
model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True).eval()
|
13 |
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
14 |
|
15 |
def run_example(task_prompt, image, text_input=None):
|
16 |
+
if text_input is None:
|
17 |
+
prompt = task_prompt
|
18 |
+
else:
|
19 |
+
prompt = task_prompt + text_input
|
20 |
inputs = processor(text=prompt, images=image, return_tensors="pt")
|
21 |
generated_ids = model.generate(
|
22 |
input_ids=inputs["input_ids"],
|
|
|
28 |
)
|
29 |
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
|
30 |
parsed_answer = processor.post_process_generation(
|
31 |
+
generated_text,
|
32 |
+
task=task_prompt,
|
33 |
image_size=(image.width, image.height)
|
34 |
)
|
35 |
return parsed_answer
|
|
|
42 |
rect = patches.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
|
43 |
ax.add_patch(rect)
|
44 |
plt.text(x1, y1, label, color='white', fontsize=8, bbox=dict(facecolor='red', alpha=0.5))
|
45 |
+
ax.axis('off')
|
46 |
+
return fig
|
47 |
|
48 |
def draw_polygons(image, prediction, fill_mask=False):
|
49 |
draw = ImageDraw.Draw(image)
|
50 |
+
scale = 1
|
51 |
for polygons, label in zip(prediction['polygons'], prediction['labels']):
|
52 |
color = random.choice(colormap)
|
53 |
+
fill_color = random.choice(colormap) if fill_mask else None
|
54 |
+
for _polygon in polygons:
|
55 |
+
_polygon = np.array(_polygon).reshape(-1, 2)
|
56 |
+
if len(_polygon) < 3:
|
57 |
+
print('Invalid polygon:', _polygon)
|
58 |
+
continue
|
59 |
+
_polygon = (_polygon * scale).reshape(-1).tolist()
|
60 |
+
if fill_mask:
|
61 |
+
draw.polygon(_polygon, outline=color, fill=fill_color)
|
62 |
+
else:
|
63 |
+
draw.polygon(_polygon, outline=color)
|
64 |
+
draw.text((_polygon[0] + 8, _polygon[1] + 2), label, fill=color)
|
65 |
+
return image
|
66 |
+
|
67 |
+
def convert_to_od_format(data):
|
68 |
+
bboxes = data.get('bboxes', [])
|
69 |
+
labels = data.get('bboxes_labels', [])
|
70 |
+
od_results = {
|
71 |
+
'bboxes': bboxes,
|
72 |
+
'labels': labels
|
73 |
+
}
|
74 |
+
return od_results
|
75 |
+
|
76 |
+
def draw_ocr_bboxes(image, prediction):
|
77 |
+
scale = 1
|
78 |
+
draw = ImageDraw.Draw(image)
|
79 |
+
bboxes, labels = prediction['quad_boxes'], prediction['labels']
|
80 |
+
for box, label in zip(bboxes, labels):
|
81 |
+
color = random.choice(colormap)
|
82 |
+
new_box = (np.array(box) * scale).tolist()
|
83 |
+
draw.polygon(new_box, width=3, outline=color)
|
84 |
+
draw.text((new_box[0]+8, new_box[1]+2),
|
85 |
+
"{}".format(label),
|
86 |
+
align="right",
|
87 |
+
fill=color)
|
88 |
+
return image
|
89 |
+
|
90 |
+
def process_image(image, task_prompt, text_input=None):
|
91 |
+
if task_prompt == '<CAPTION>':
|
92 |
+
result = run_example(task_prompt, image)
|
93 |
+
return result
|
94 |
+
elif task_prompt == '<DETAILED_CAPTION>':
|
95 |
+
result = run_example(task_prompt, image)
|
96 |
+
return result
|
97 |
+
elif task_prompt == '<MORE_DETAILED_CAPTION>':
|
98 |
+
result = run_example(task_prompt, image)
|
99 |
+
return result
|
100 |
+
elif task_prompt == '<OD>':
|
101 |
+
results = run_example(task_prompt, image)
|
102 |
+
fig = plot_bbox(image, results['<OD>'])
|
103 |
+
return fig
|
104 |
+
elif task_prompt == '<DENSE_REGION_CAPTION>':
|
105 |
+
results = run_example(task_prompt, image)
|
106 |
+
fig = plot_bbox(image, results['<DENSE_REGION_CAPTION>'])
|
107 |
+
return fig
|
108 |
+
elif task_prompt == '<REGION_PROPOSAL>':
|
109 |
+
results = run_example(task_prompt, image)
|
110 |
+
fig = plot_bbox(image, results['<REGION_PROPOSAL>'])
|
111 |
+
return fig
|
112 |
+
elif task_prompt == '<CAPTION_TO_PHRASE_GROUNDING>':
|
113 |
+
results = run_example(task_prompt, image, text_input)
|
114 |
+
fig = plot_bbox(image, results['<CAPTION_TO_PHRASE_GROUNDING>'])
|
115 |
+
return fig
|
116 |
+
elif task_prompt == '<REFERRING_EXPRESSION_SEGMENTATION>':
|
117 |
+
results = run_example(task_prompt, image, text_input)
|
118 |
+
output_image = copy.deepcopy(image)
|
119 |
+
output_image = draw_polygons(output_image, results['<REFERRING_EXPRESSION_SEGMENTATION>'], fill_mask=True)
|
120 |
+
return output_image
|
121 |
+
elif task_prompt == '<REGION_TO_SEGMENTATION>':
|
122 |
+
results = run_example(task_prompt, image, text_input)
|
123 |
+
output_image = copy.deepcopy(image)
|
124 |
+
output_image = draw_polygons(output_image, results['<REGION_TO_SEGMENTATION>'], fill_mask=True)
|
125 |
+
return output_image
|
126 |
+
elif task_prompt == '<OPEN_VOCABULARY_DETECTION>':
|
127 |
+
results = run_example(task_prompt, image, text_input)
|
128 |
+
bbox_results = convert_to_od_format(results['<OPEN_VOCABULARY_DETECTION>'])
|
129 |
+
fig = plot_bbox(image, bbox_results)
|
130 |
+
return fig
|
131 |
+
elif task_prompt == '<REGION_TO_CATEGORY>':
|
132 |
+
results = run_example(task_prompt, image, text_input)
|
133 |
+
return results
|
134 |
+
elif task_prompt == '<REGION_TO_DESCRIPTION>':
|
135 |
+
results = run_example(task_prompt, image, text_input)
|
136 |
+
return results
|
137 |
+
elif task_prompt == '<OCR>':
|
138 |
+
result = run_example(task_prompt, image)
|
139 |
+
return result
|
140 |
+
elif task_prompt == '<OCR_WITH_REGION>':
|
141 |
+
results = run_example(task_prompt, image)
|
142 |
+
output_image = copy.deepcopy(image)
|
143 |
+
output_image = draw_ocr_bboxes(output_image, results['<OCR_WITH_REGION>'])
|
144 |
+
return output_image
|
145 |
+
|
146 |
+
css = """
|
147 |
+
#output {
|
148 |
+
height: 500px;
|
149 |
+
overflow: auto;
|
150 |
+
border: 1px solid #ccc;
|
151 |
+
}
|
152 |
+
"""
|
153 |
+
|
154 |
+
with gr.Blocks(css=css) as demo:
|
155 |
+
gr.HTML("<h1><center>Florence-2 Demo<center><h1>")
|
156 |
+
with gr.Tab(label="Florence-2 Image Captioning"):
|
157 |
+
with gr.Row():
|
158 |
+
with gr.Column():
|
159 |
+
input_img = gr.Image(label="Input Picture")
|
160 |
+
task_prompt = gr.Dropdown(choices=[
|
161 |
+
'<CAPTION>', '<DETAILED_CAPTION>', '<MORE_DETAILED_CAPTION>', '<OD>',
|
162 |
+
'<DENSE_REGION_CAPTION>', '<REGION_PROPOSAL>', '<CAPTION_TO_PHRASE_GROUNDING>',
|
163 |
+
'<REFERRING_EXPRESSION_SEGMENTATION>', '<REGION_TO_SEGMENTATION>',
|
164 |
+
'<OPEN_VOCABULARY_DETECTION>', '<REGION_TO_CATEGORY>', '<REGION_TO_DESCRIPTION>',
|
165 |
+
'<OCR>', '<OCR_WITH_REGION>'
|
166 |
+
], label="Task Prompt")
|
167 |
+
text_input = gr.Textbox(label="Text Input (optional)")
|
168 |
+
submit_btn = gr.Button(value="Submit")
|
169 |
+
with gr.Column():
|
170 |
+
output_text = gr.Textbox(label="Output Text")
|
171 |
+
output_img = gr.Image(label="Output Image")
|
172 |
|
173 |
+
gr.Examples(
|
174 |
+
examples=[
|
175 |
+
["image1.jpg", '<CAPTION>'],
|
176 |
+
["image1.jpg", '<OD>'],
|
177 |
+
["image1.jpg", '<OCR_WITH_REGION>']
|
178 |
+
],
|
179 |
+
inputs=[input_img, task_prompt],
|
180 |
+
outputs=[output_text, output_img],
|
181 |
+
fn=process_image,
|
182 |
+
cache_examples=True,
|
183 |
+
label='Try examples'
|
184 |
+
)
|
185 |
|
186 |
+
submit_btn.click(process_image, [input_img, task_prompt, text_input], [output_text, output_img])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
187 |
|
188 |
+
demo.launch(debug=True)
|