linh-truong commited on
Commit
c1b4f26
1 Parent(s): c46566d
Files changed (7) hide show
  1. .gitignore +3 -0
  2. app.py +35 -0
  3. requirements.txt +5 -0
  4. src/feature_extraction.py +193 -0
  5. src/model.py +445 -0
  6. src/ocr.py +79 -0
  7. utils/config.py +13 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__
2
+ **test**
3
+ storage
app.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+
4
+ #Trick to not init function multitime
5
+ if "model" not in st.session_state:
6
+ print("INIT MODEL")
7
+ from src.model import Model
8
+ st.session_state.model = Model()
9
+ print("DONE INIT MODEL")
10
+
11
+ st.set_page_config(page_title="VQA", layout="wide")
12
+ hide_menu_style = """
13
+ <style>
14
+ footer {visibility: hidden;}
15
+ </style>
16
+ """
17
+ st.markdown(hide_menu_style, unsafe_allow_html= True)
18
+
19
+
20
+ image = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png", "webp", ])
21
+
22
+ if image:
23
+ bytes_data = image.getvalue()
24
+ with open("test.png", "wb") as f:
25
+ f.write(bytes_data)
26
+ f.close()
27
+ st.session_state.image = "test.png"
28
+
29
+ if 'image' in st.session_state:
30
+ st.image(st.session_state.image)
31
+ question = st.text_input("Question: ")
32
+ if question:
33
+ answer = st.session_state.model.inference(st.session_state.image, question)
34
+ st.write(f"Answer: {answer}")
35
+
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ paddlepaddle>=2.3.1
2
+ paddleocr==2.6.1.3
3
+ vietocr>=0.3.8
4
+ pillow==9.5.0
5
+ torchvision==0.18.0
src/feature_extraction.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import requests
4
+ from PIL import Image, ImageFont, ImageDraw, ImageTransform
5
+ from transformers import AutoImageProcessor, ViTModel, AutoTokenizer, T5EncoderModel
6
+ from utils.config import Config
7
+ from src.ocr import OCRDetector
8
+
9
+
10
+ class ViT:
11
+ def __init__(self) -> None:
12
+ self.processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
13
+ self.model = ViTModel.from_pretrained("google/vit-base-patch16-224-in21k")
14
+ self.model.to(Config.device)
15
+
16
+ def extraction(self, image_url):
17
+ if image_url.startswith("https://"):
18
+ images = Image.open(requests.get(image_url, stream=True).raw).convert("RGB")
19
+ else:
20
+ images = Image.open(image_url).convert("RGB")
21
+
22
+ inputs = self.processor(images, return_tensors="pt").to(Config.device)
23
+ with torch.no_grad():
24
+ outputs = self.model(**inputs)
25
+ last_hidden_states = outputs.last_hidden_state
26
+ attention_mask = torch.ones((last_hidden_states.shape[0], last_hidden_states.shape[1]))
27
+
28
+ return last_hidden_states.to(Config.device), attention_mask.to(Config.device)
29
+
30
+ def pooling_extraction(self, image):
31
+ image_inputs = self.processor(image, return_tensors="pt").to(Config.device)
32
+
33
+ with torch.no_grad():
34
+ image_outputs = self.model(**image_inputs)
35
+ image_pooler_output = image_outputs.pooler_output
36
+ image_pooler_output = torch.unsqueeze(image_pooler_output, 0)
37
+ image_attention_mask = torch.ones((image_pooler_output.shape[0], image_pooler_output.shape[1]))
38
+
39
+ return image_pooler_output.to(Config.device), image_attention_mask.to(Config.device)
40
+
41
+ class OCR:
42
+ def __init__(self) -> None:
43
+ self.ocr_detector = OCRDetector()
44
+
45
+ def extraction(self, image_dir):
46
+
47
+ ocr_results = self.ocr_detector.text_detector(image_dir)
48
+ if not ocr_results:
49
+ print("NOT OCR1")
50
+
51
+ return "", [], []
52
+
53
+ ocrs = self.post_process(ocr_results)
54
+
55
+ if not ocrs:
56
+
57
+ return "", [], []
58
+
59
+ ocrs.reverse()
60
+
61
+ boxes = []
62
+ texts = []
63
+ for idx, ocr in enumerate(ocrs):
64
+ boxes.append(ocr["box"])
65
+ texts.append(ocr["text"])
66
+
67
+ groups_box, groups_text, paragraph_boxes = OCR.group_boxes(boxes, texts)
68
+ for temp in groups_text:
69
+ print("OCR: ", temp)
70
+
71
+ texts = [" ".join(group_text) for group_text in groups_text]
72
+ ocr_content = "<extra_id_0>".join(texts)
73
+ ocr_content = ocr_content.lower()
74
+ ocr_content = " ".join(ocr_content.split())
75
+ ocr_content = "<extra_id_0>" + ocr_content
76
+
77
+
78
+ return ocr_content, groups_box, paragraph_boxes
79
+
80
+ def post_process(self,ocr_results):
81
+ ocrs = []
82
+ for result in ocr_results:
83
+ text = result["text"]
84
+ # if len(text) <=2:
85
+ # continue
86
+ # if len(set(text.replace(" ", ""))) <=2:
87
+ # continue
88
+ box = result["box"]
89
+
90
+ # (x1, y1), (x2, y2), (x3, y3), (x4, y4) = box
91
+ # w = x2 - x1
92
+ # h = y4 - y1
93
+ # if h > w:
94
+ # continue
95
+
96
+ # if w*h < 300:
97
+ # continue
98
+
99
+ ocrs.append(
100
+ {"text": text.lower(),
101
+ "box": box}
102
+ )
103
+ return ocrs
104
+
105
+ @staticmethod
106
+ def cut_image_polygon(image, box):
107
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = box
108
+ w = x2 - x1
109
+ h = y4 - y1
110
+ scl = h//7
111
+ new_box = [max(x1-scl,0), max(y1 - scl, 0)], [x2+scl, y2-scl], [x3+scl, y3+scl], [x4-scl, y4+scl]
112
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = new_box
113
+ # Define 8-tuple with x,y coordinates of top-left, bottom-left, bottom-right and top-right corners and apply
114
+ transform = [x1, y1, x4, y4, x3, y3, x2, y2]
115
+ result = image.transform((w,h), ImageTransform.QuadTransform(transform))
116
+ return result
117
+
118
+
119
+ @staticmethod
120
+ def check_point_in_rectangle(box, point, padding_devide):
121
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = box
122
+ x_min = min(x1, x4)
123
+ x_max = max(x2, x3)
124
+
125
+ padding = (x_max-x_min)//padding_devide
126
+ x_min = x_min - padding
127
+ x_max = x_max + padding
128
+
129
+ y_min = min(y1, y2)
130
+ y_max = max(y3, y4)
131
+
132
+ y_min = y_min - padding
133
+ y_max = y_max + padding
134
+
135
+ x, y = point
136
+
137
+ if x >= x_min and x <= x_max and y >= y_min and y <= y_max:
138
+ return True
139
+
140
+ return False
141
+
142
+ @staticmethod
143
+ def check_rectangle_overlap(rec1, rec2, padding_devide):
144
+ for point in rec1:
145
+ if OCR.check_point_in_rectangle(rec2, point, padding_devide):
146
+ return True
147
+
148
+ for point in rec2:
149
+ if OCR.check_point_in_rectangle(rec1, point, padding_devide):
150
+ return True
151
+
152
+ return False
153
+
154
+ @staticmethod
155
+ def group_boxes(boxes, texts):
156
+ groups = []
157
+ groups_text = []
158
+ paragraph_boxes = []
159
+ processed = []
160
+ boxes_cp = boxes.copy()
161
+ for i, (box, text) in enumerate(zip(boxes_cp, texts)):
162
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = box
163
+
164
+ if i not in processed:
165
+ processed.append(i)
166
+ else:
167
+ continue
168
+
169
+ groups.append([box])
170
+ groups_text.append([text])
171
+ for j, (box2, text2) in enumerate(zip(boxes_cp[i+1:], texts[i+1:])):
172
+ if j+i+1 in processed:
173
+ continue
174
+ padding_devide = len(groups[-1])*4
175
+ is_overlap = OCR.check_rectangle_overlap(box, box2, padding_devide)
176
+ if is_overlap:
177
+ (xx1, yy1), (xx2, yy2), (xx3, yy3), (xx4, yy4) = box2
178
+ processed.append(j+i+1)
179
+ groups[-1].append(box2)
180
+ groups_text[-1].append(text2)
181
+ new_x1 = min(x1, xx1)
182
+ new_y1 = min(y1, yy1)
183
+ new_x2 = max(x2, xx2)
184
+ new_y2 = min(y2, yy2)
185
+ new_x3 = max(x3, xx3)
186
+ new_y3 = max(y3, yy3)
187
+ new_x4 = min(x4, xx4)
188
+ new_y4 = max(y4, yy4)
189
+
190
+ box = [(new_x1, new_y1), (new_x2, new_y2), (new_x3, new_y3), (new_x4, new_y4)]
191
+
192
+ paragraph_boxes.append(box)
193
+ return groups, groups_text, paragraph_boxes
src/model.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import transformers
2
+ from transformers.models.t5.modeling_t5 import *
3
+ from transformers.models.t5.modeling_t5 import T5Stack
4
+ import os
5
+ import gdown
6
+ import torch
7
+ from typing import *
8
+ from transformers import T5ForConditionalGeneration, AutoTokenizer
9
+ from utils.config import Config
10
+ from src.feature_extraction import ViT, OCR
11
+
12
+ _CONFIG_FOR_DOC = "T5Config"
13
+ _CHECKPOINT_FOR_DOC = "google-t5/t5-small"
14
+
15
+ class CustomT5Stack(T5Stack):
16
+
17
+ def forward(
18
+ self,
19
+ input_ids=None,
20
+ attention_mask=None,
21
+ encoder_hidden_states=None,
22
+ encoder_attention_mask=None,
23
+ inputs_embeds=None,
24
+ head_mask=None,
25
+ cross_attn_head_mask=None,
26
+ past_key_values=None,
27
+ use_cache=None,
28
+ output_attentions=None,
29
+ output_hidden_states=None,
30
+ return_dict=None,
31
+ images_embeds=None,
32
+ ):
33
+ # Model parallel
34
+ if self.model_parallel:
35
+ torch.cuda.set_device(self.first_device)
36
+ self.embed_tokens = self.embed_tokens.to(self.first_device)
37
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
38
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
39
+ output_hidden_states = (
40
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
41
+ )
42
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
43
+
44
+ if input_ids is not None and inputs_embeds is not None:
45
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
46
+ raise ValueError(
47
+ f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
48
+ )
49
+ elif input_ids is not None:
50
+ input_shape = input_ids.size()
51
+ input_ids = input_ids.view(-1, input_shape[-1])
52
+ elif inputs_embeds is not None:
53
+ input_shape = inputs_embeds.size()[:-1]
54
+ else:
55
+ err_msg_prefix = "decoder_" if self.is_decoder else ""
56
+ raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
57
+
58
+ if inputs_embeds is None:
59
+ if self.embed_tokens is None:
60
+ raise ValueError("You have to initialize the model with valid token embeddings")
61
+ inputs_embeds = self.embed_tokens(input_ids)
62
+ if not self.is_decoder and images_embeds is not None:
63
+ inputs_embeds = torch.concat([inputs_embeds, images_embeds], dim=1)
64
+ input_shape = inputs_embeds.size()[:-1]
65
+
66
+ batch_size, seq_length = input_shape
67
+
68
+ # required mask seq length can be calculated via length of past
69
+ mask_seq_length = past_key_values[0][0].shape[2] + seq_length if past_key_values is not None else seq_length
70
+
71
+ if use_cache is True:
72
+ if not self.is_decoder:
73
+ raise ValueError(f"`use_cache` can only be set to `True` if {self} is used as a decoder")
74
+
75
+ # initialize past_key_values with `None` if past does not exist
76
+ if past_key_values is None:
77
+ past_key_values = [None] * len(self.block)
78
+
79
+ if attention_mask is None:
80
+ attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
81
+
82
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
83
+ # ourselves in which case we just need to make it broadcastable to all heads.
84
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
85
+
86
+ # If a 2D or 3D attention mask is provided for the cross-attention
87
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
88
+ if self.is_decoder and encoder_hidden_states is not None:
89
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
90
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
91
+ if encoder_attention_mask is None:
92
+ encoder_attention_mask = torch.ones(
93
+ encoder_hidden_shape, device=inputs_embeds.device, dtype=torch.long
94
+ )
95
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
96
+ else:
97
+ encoder_extended_attention_mask = None
98
+
99
+ if self.gradient_checkpointing and self.training:
100
+ if use_cache:
101
+ logger.warning_once(
102
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
103
+ )
104
+ use_cache = False
105
+
106
+ # Prepare head mask if needed
107
+ head_mask = self.get_head_mask(head_mask, self.config.num_layers)
108
+ cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
109
+ present_key_value_states = () if use_cache else None
110
+ all_hidden_states = () if output_hidden_states else None
111
+ all_attentions = () if output_attentions else None
112
+ all_cross_attentions = () if (output_attentions and self.is_decoder) else None
113
+ position_bias = None
114
+ encoder_decoder_position_bias = None
115
+
116
+ hidden_states = self.dropout(inputs_embeds)
117
+
118
+ for i, (layer_module, past_key_value) in enumerate(zip(self.block, past_key_values)):
119
+ layer_head_mask = head_mask[i]
120
+ cross_attn_layer_head_mask = cross_attn_head_mask[i]
121
+ # Model parallel
122
+ if self.model_parallel:
123
+ torch.cuda.set_device(hidden_states.device)
124
+ # Ensure that attention_mask is always on the same device as hidden_states
125
+ if attention_mask is not None:
126
+ attention_mask = attention_mask.to(hidden_states.device)
127
+ if position_bias is not None:
128
+ position_bias = position_bias.to(hidden_states.device)
129
+ if encoder_hidden_states is not None:
130
+ encoder_hidden_states = encoder_hidden_states.to(hidden_states.device)
131
+ if encoder_extended_attention_mask is not None:
132
+ encoder_extended_attention_mask = encoder_extended_attention_mask.to(hidden_states.device)
133
+ if encoder_decoder_position_bias is not None:
134
+ encoder_decoder_position_bias = encoder_decoder_position_bias.to(hidden_states.device)
135
+ if layer_head_mask is not None:
136
+ layer_head_mask = layer_head_mask.to(hidden_states.device)
137
+ if cross_attn_layer_head_mask is not None:
138
+ cross_attn_layer_head_mask = cross_attn_layer_head_mask.to(hidden_states.device)
139
+ if output_hidden_states:
140
+ all_hidden_states = all_hidden_states + (hidden_states,)
141
+
142
+ if self.gradient_checkpointing and self.training:
143
+ layer_outputs = self._gradient_checkpointing_func(
144
+ layer_module.forward,
145
+ hidden_states,
146
+ extended_attention_mask,
147
+ position_bias,
148
+ encoder_hidden_states,
149
+ encoder_extended_attention_mask,
150
+ encoder_decoder_position_bias,
151
+ layer_head_mask,
152
+ cross_attn_layer_head_mask,
153
+ None, # past_key_value is always None with gradient checkpointing
154
+ use_cache,
155
+ output_attentions,
156
+ )
157
+ else:
158
+ layer_outputs = layer_module(
159
+ hidden_states,
160
+ attention_mask=extended_attention_mask,
161
+ position_bias=position_bias,
162
+ encoder_hidden_states=encoder_hidden_states,
163
+ encoder_attention_mask=encoder_extended_attention_mask,
164
+ encoder_decoder_position_bias=encoder_decoder_position_bias,
165
+ layer_head_mask=layer_head_mask,
166
+ cross_attn_layer_head_mask=cross_attn_layer_head_mask,
167
+ past_key_value=past_key_value,
168
+ use_cache=use_cache,
169
+ output_attentions=output_attentions,
170
+ )
171
+
172
+ # layer_outputs is a tuple with:
173
+ # hidden-states, key-value-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
174
+ if use_cache is False:
175
+ layer_outputs = layer_outputs[:1] + (None,) + layer_outputs[1:]
176
+
177
+ hidden_states, present_key_value_state = layer_outputs[:2]
178
+
179
+ # We share the position biases between the layers - the first layer store them
180
+ # layer_outputs = hidden-states, key-value-states (self-attention position bias), (self-attention weights),
181
+ # (cross-attention position bias), (cross-attention weights)
182
+ position_bias = layer_outputs[2]
183
+ if self.is_decoder and encoder_hidden_states is not None:
184
+ encoder_decoder_position_bias = layer_outputs[4 if output_attentions else 3]
185
+ # append next layer key value states
186
+ if use_cache:
187
+ present_key_value_states = present_key_value_states + (present_key_value_state,)
188
+
189
+ if output_attentions:
190
+ all_attentions = all_attentions + (layer_outputs[3],)
191
+ if self.is_decoder:
192
+ all_cross_attentions = all_cross_attentions + (layer_outputs[5],)
193
+
194
+ # Model Parallel: If it's the last layer for that device, put things on the next device
195
+ if self.model_parallel:
196
+ for k, v in self.device_map.items():
197
+ if i == v[-1] and "cuda:" + str(k) != self.last_device:
198
+ hidden_states = hidden_states.to("cuda:" + str(k + 1))
199
+
200
+ hidden_states = self.final_layer_norm(hidden_states)
201
+ hidden_states = self.dropout(hidden_states)
202
+
203
+ # Add last layer
204
+ if output_hidden_states:
205
+ all_hidden_states = all_hidden_states + (hidden_states,)
206
+
207
+ if not return_dict:
208
+ return tuple(
209
+ v
210
+ for v in [
211
+ hidden_states,
212
+ present_key_value_states,
213
+ all_hidden_states,
214
+ all_attentions,
215
+ all_cross_attentions,
216
+ ]
217
+ if v is not None
218
+ )
219
+ return BaseModelOutputWithPastAndCrossAttentions(
220
+ last_hidden_state=hidden_states,
221
+ past_key_values=present_key_value_states,
222
+ hidden_states=all_hidden_states,
223
+ attentions=all_attentions,
224
+ cross_attentions=all_cross_attentions,
225
+ )
226
+
227
+
228
+ class CustomT5ForConditionalGeneration(T5ForConditionalGeneration):
229
+ @add_start_docstrings_to_model_forward(T5_INPUTS_DOCSTRING)
230
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
231
+ def forward(
232
+ self,
233
+ input_ids: Optional[torch.LongTensor] = None,
234
+ attention_mask: Optional[torch.FloatTensor] = None,
235
+ decoder_input_ids: Optional[torch.LongTensor] = None,
236
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
237
+ head_mask: Optional[torch.FloatTensor] = None,
238
+ decoder_head_mask: Optional[torch.FloatTensor] = None,
239
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
240
+ encoder_outputs: Optional[Tuple[Tuple[torch.Tensor]]] = None,
241
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
242
+ inputs_embeds: Optional[torch.FloatTensor] = None,
243
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
244
+ labels: Optional[torch.LongTensor] = None,
245
+ use_cache: Optional[bool] = None,
246
+ output_attentions: Optional[bool] = None,
247
+ output_hidden_states: Optional[bool] = None,
248
+ return_dict: Optional[bool] = None,
249
+ images_embeds: Optional[torch.FloatTensor] = None,
250
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
251
+ r"""
252
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
253
+ Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
254
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
255
+ labels in `[0, ..., config.vocab_size]`
256
+
257
+ Returns:
258
+
259
+ Examples:
260
+
261
+ ```python
262
+ >>> from transformers import AutoTokenizer, T5ForConditionalGeneration
263
+
264
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
265
+ >>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")
266
+
267
+ >>> # training
268
+ >>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
269
+ >>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
270
+ >>> outputs = model(input_ids=input_ids, labels=labels)
271
+ >>> loss = outputs.loss
272
+ >>> logits = outputs.logits
273
+
274
+ >>> # inference
275
+ >>> input_ids = tokenizer(
276
+ ... "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
277
+ ... ).input_ids # Batch size 1
278
+ >>> outputs = model.generate(input_ids)
279
+ >>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
280
+ >>> # studies have shown that owning a dog is good for you.
281
+ ```"""
282
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
283
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
284
+
285
+ # FutureWarning: head_mask was separated into two input args - head_mask, decoder_head_mask
286
+ if head_mask is not None and decoder_head_mask is None:
287
+ if self.config.num_layers == self.config.num_decoder_layers:
288
+ warnings.warn(__HEAD_MASK_WARNING_MSG, FutureWarning)
289
+ decoder_head_mask = head_mask
290
+
291
+ # Encode if needed (training, first prediction pass)
292
+ if encoder_outputs is None:
293
+ # Convert encoder inputs in embeddings if needed
294
+ encoder_outputs = self.encoder(
295
+ input_ids=input_ids,
296
+ attention_mask=attention_mask,
297
+ inputs_embeds=inputs_embeds,
298
+ head_mask=head_mask,
299
+ output_attentions=output_attentions,
300
+ output_hidden_states=output_hidden_states,
301
+ return_dict=return_dict,
302
+ images_embeds=images_embeds
303
+ )
304
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
305
+ encoder_outputs = BaseModelOutput(
306
+ last_hidden_state=encoder_outputs[0],
307
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
308
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
309
+ )
310
+
311
+ hidden_states = encoder_outputs[0]
312
+
313
+ if self.model_parallel:
314
+ torch.cuda.set_device(self.decoder.first_device)
315
+
316
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
317
+ # get decoder inputs from shifting lm labels to the right
318
+ decoder_input_ids = self._shift_right(labels)
319
+
320
+ # Set device for model parallelism
321
+ if self.model_parallel:
322
+ torch.cuda.set_device(self.decoder.first_device)
323
+ hidden_states = hidden_states.to(self.decoder.first_device)
324
+ if decoder_input_ids is not None:
325
+ decoder_input_ids = decoder_input_ids.to(self.decoder.first_device)
326
+ if attention_mask is not None:
327
+ attention_mask = attention_mask.to(self.decoder.first_device)
328
+ if decoder_attention_mask is not None:
329
+ decoder_attention_mask = decoder_attention_mask.to(self.decoder.first_device)
330
+
331
+ # Decode
332
+ decoder_outputs = self.decoder(
333
+ input_ids=decoder_input_ids,
334
+ attention_mask=decoder_attention_mask,
335
+ inputs_embeds=decoder_inputs_embeds,
336
+ past_key_values=past_key_values,
337
+ encoder_hidden_states=hidden_states,
338
+ encoder_attention_mask=attention_mask,
339
+ head_mask=decoder_head_mask,
340
+ cross_attn_head_mask=cross_attn_head_mask,
341
+ use_cache=use_cache,
342
+ output_attentions=output_attentions,
343
+ output_hidden_states=output_hidden_states,
344
+ return_dict=return_dict,
345
+ )
346
+
347
+ sequence_output = decoder_outputs[0]
348
+
349
+ # Set device for model parallelism
350
+ if self.model_parallel:
351
+ torch.cuda.set_device(self.encoder.first_device)
352
+ self.lm_head = self.lm_head.to(self.encoder.first_device)
353
+ sequence_output = sequence_output.to(self.lm_head.weight.device)
354
+
355
+ if self.config.tie_word_embeddings:
356
+ # Rescale output before projecting on vocab
357
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/transformer.py#L586
358
+ sequence_output = sequence_output * (self.model_dim**-0.5)
359
+
360
+ lm_logits = self.lm_head(sequence_output)
361
+
362
+ loss = None
363
+ if labels is not None:
364
+ loss_fct = CrossEntropyLoss(ignore_index=-100)
365
+ # move labels to correct device to enable PP
366
+ labels = labels.to(lm_logits.device)
367
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
368
+ # TODO(thom): Add z_loss https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L666
369
+
370
+ if not return_dict:
371
+ output = (lm_logits,) + decoder_outputs[1:] + encoder_outputs
372
+ return ((loss,) + output) if loss is not None else output
373
+
374
+ return Seq2SeqLMOutput(
375
+ loss=loss,
376
+ logits=lm_logits,
377
+ past_key_values=decoder_outputs.past_key_values,
378
+ decoder_hidden_states=decoder_outputs.hidden_states,
379
+ decoder_attentions=decoder_outputs.attentions,
380
+ cross_attentions=decoder_outputs.cross_attentions,
381
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
382
+ encoder_hidden_states=encoder_outputs.hidden_states,
383
+ encoder_attentions=encoder_outputs.attentions,
384
+ )
385
+
386
+ transformers.models.t5.modeling_t5.T5Stack = CustomT5Stack
387
+ transformers.models.t5.modeling_t5.T5ForConditionalGeneration = CustomT5ForConditionalGeneration
388
+ transformers.T5ForConditionalGeneration = CustomT5ForConditionalGeneration
389
+
390
+
391
+ class Model:
392
+ def __init__(self) -> None:
393
+ os.makedirs("storage", exist_ok=True)
394
+
395
+ if not os.path.exists("storage/vlsp_transfomer_vietocr.pth"):
396
+ print("DOWNLOADING model")
397
+ gdown.download(Config.model_url, output="storage/vlsp_transfomer_vietocr.pth")
398
+ self.vit5_tokenizer = AutoTokenizer.from_pretrained("VietAI/vit5-base")
399
+ self.model = T5ForConditionalGeneration.from_pretrained("truong-xuan-linh/VQA-vit5",
400
+ revision=Config.revision,
401
+ output_attentions=True)
402
+ self.model.to(Config.device)
403
+
404
+ self.vit = ViT()
405
+ self.ocr = OCR()
406
+
407
+ def get_inputs(self, image_dir: str, question: str):
408
+ #VIT
409
+ image_feature, image_mask = self.vit.extraction(image_dir)
410
+
411
+ ocr_content, groups_box, paragraph_boxes = self.ocr.extraction(image_dir)
412
+ print("Input: ", question + " " + ocr_content)
413
+ #VIT5
414
+ input_ = self.vit5_tokenizer(question + " " + ocr_content,
415
+ padding="max_length",
416
+ truncation=True,
417
+ max_length=Config.question_maxlen + Config.ocr_maxlen,
418
+ return_tensors="pt")
419
+
420
+ input_ids = input_.input_ids
421
+ attention_mask = input_.attention_mask
422
+ mask = torch.cat((attention_mask, image_mask), 1)
423
+ return {
424
+ "input_ids": input_ids,
425
+ "attention_mask": mask,
426
+ "images_embeds": image_feature,
427
+ }
428
+
429
+ def inference(self, image_dir: str, question: str):
430
+ inputs = self.get_inputs(image_dir, question)
431
+ with torch.no_grad():
432
+ input_ids = inputs["input_ids"]
433
+ attention_mask = inputs["attention_mask"]
434
+ images_embeds = inputs["images_embeds"]
435
+ generated_ids = self.model.generate(
436
+ input_ids=input_ids, \
437
+ attention_mask=attention_mask, \
438
+ images_embeds=images_embeds, \
439
+ num_beams=2,
440
+ max_length=Config.answer_maxlen
441
+ )
442
+
443
+ pred_answer = self.vit5_tokenizer.decode(generated_ids[0], skip_special_tokens=True)
444
+
445
+ return pred_answer
src/ocr.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from paddleocr import PaddleOCR
2
+ from vietocr.tool.config import Cfg
3
+ from vietocr.tool.predictor import Predictor
4
+ from utils.config import Config
5
+ import requests
6
+ import numpy as np
7
+ from PIL import Image, ImageTransform
8
+
9
+ class OCRDetector:
10
+ def __init__(self) -> None:
11
+ self.paddle_ocr = PaddleOCR(lang='en',
12
+ use_angle_cls=False,
13
+ use_gpu=True if Config.device == "cpu" else False,
14
+ show_log=False )
15
+ # config['weights'] = './weights/transformerocr.pth'
16
+
17
+ vietocr_config = Cfg.load_config_from_name('vgg_transformer')
18
+ vietocr_config['weights'] = Config.ocr_path
19
+ vietocr_config['cnn']['pretrained']=False
20
+ vietocr_config['device'] = Config.device
21
+ vietocr_config['predictor']['beamsearch']=False
22
+ self.viet_ocr = Predictor(vietocr_config)
23
+
24
+ def find_box(self, image):
25
+ '''Xác định box dựa vào mô hình paddle_ocr'''
26
+ result = self.paddle_ocr.ocr(image, cls = False, rec=False)
27
+ result = result[0]
28
+ # Extracting detected components
29
+ boxes = result #[res[0] for res in result]
30
+ boxes = np.array(boxes).astype(int)
31
+
32
+ # scores = [res[1][1] for res in result]
33
+ return boxes
34
+
35
+ def cut_image_polygon(self, image, box):
36
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = box
37
+ w = x2 - x1
38
+ h = y4 - y1
39
+ scl = h//7
40
+ new_box = [max(x1-scl,0), max(y1 - scl, 0)], [x2+scl, y2-scl], [x3+scl, y3+scl], [x4-scl, y4+scl]
41
+ (x1, y1), (x2, y2), (x3, y3), (x4, y4) = new_box
42
+ # Define 8-tuple with x,y coordinates of top-left, bottom-left, bottom-right and top-right corners and apply
43
+ transform = [x1, y1, x4, y4, x3, y3, x2, y2]
44
+ result = image.transform((w,h), ImageTransform.QuadTransform(transform))
45
+ return result
46
+
47
+ def vietnamese_text(self, boxes, image):
48
+ '''Xác định text dựa vào mô hình viet_ocr'''
49
+ results = []
50
+ for box in boxes:
51
+ try:
52
+ cut_image = self.cut_image_polygon(image, box)
53
+ # cut_image = Image.fromarray(np.uint8(cut_image))
54
+ text, score = self.viet_ocr.predict(cut_image, return_prob=True)
55
+ if score > Config.vietocr_threshold:
56
+ results.append({"text": text,
57
+ "score": score,
58
+ "box": box})
59
+ except:
60
+ continue
61
+ return results
62
+
63
+ #Merge
64
+ def text_detector(self, image_path):
65
+ if image_path.startswith("https://"):
66
+ image = Image.open(requests.get(image_path, stream=True).raw).convert("RGB")
67
+ else:
68
+ image = Image.open(image_path).convert("RGB")
69
+ # np_image = np.array(image)
70
+
71
+ boxes = self.find_box(image_path)
72
+ if not boxes.any():
73
+ return None
74
+
75
+ results = self.vietnamese_text(boxes, image)
76
+ if results != []:
77
+ return results
78
+ else:
79
+ return None
utils/config.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class Config:
2
+ device = "cpu"
3
+ model_url = "https://drive.google.com/uc?id=1WqyPOxgTj9vdnEQl_TJwr_U_hdQeI1iz"
4
+ ocr_path = "storage/vlsp_transfomer_vietocr.pth"
5
+ model_path = "storage/vit_base_vit5_base_v2_1.3197_0.4732_3.5212.pt"
6
+ question_maxlen = 32
7
+ vietocr_threshold = 0.5
8
+ answer_maxlen = 56
9
+ ocr_maxlen = 128
10
+ ocr_maxobj = 10000
11
+ num_ocr = 32
12
+ num_beams = 3
13
+ revision = "version_2_with_extra_id_0"