sanjay9876 commited on
Commit
12b794e
·
verified ·
1 Parent(s): e983e78

Update app.py

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