Commit
·
5328a20
1
Parent(s):
d2924de
Update files/functions.py
Browse files- files/functions.py +516 -0
files/functions.py
CHANGED
|
@@ -178,3 +178,519 @@ id2label_layoutxlm = model_layoutxlm.config.id2label
|
|
| 178 |
label2id_layoutxlm = model_layoutxlm.config.label2id
|
| 179 |
num_labels_layoutxlm = len(id2label_layoutxlm)
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
label2id_layoutxlm = model_layoutxlm.config.label2id
|
| 179 |
num_labels_layoutxlm = len(id2label_layoutxlm)
|
| 180 |
|
| 181 |
+
## PDf processing
|
| 182 |
+
|
| 183 |
+
# get filename and images of PDF pages
|
| 184 |
+
def pdf_to_images(uploaded_pdf):
|
| 185 |
+
|
| 186 |
+
# Check if None object
|
| 187 |
+
if uploaded_pdf is None:
|
| 188 |
+
path_to_file = pdf_blank
|
| 189 |
+
filename = path_to_file.replace(examples_dir,"")
|
| 190 |
+
msg = "Invalid PDF file."
|
| 191 |
+
images = [Image.open(image_blank)]
|
| 192 |
+
else:
|
| 193 |
+
# path to the uploaded PDF
|
| 194 |
+
path_to_file = uploaded_pdf.name
|
| 195 |
+
filename = path_to_file# .replace("/tmp/","")
|
| 196 |
+
|
| 197 |
+
try:
|
| 198 |
+
PdfReader(path_to_file)
|
| 199 |
+
except PdfReadError:
|
| 200 |
+
path_to_file = pdf_blank
|
| 201 |
+
filename = path_to_file.replace(examples_dir,"")
|
| 202 |
+
msg = "Invalid PDF file."
|
| 203 |
+
images = [Image.open(image_blank)]
|
| 204 |
+
else:
|
| 205 |
+
try:
|
| 206 |
+
# images = convert_from_path(path_to_file, last_page=max_imgboxes)
|
| 207 |
+
|
| 208 |
+
pdf = pdfium.PdfDocument(str(filename))
|
| 209 |
+
version = pdf.get_version() # get the PDF standard version
|
| 210 |
+
n_pages = len(pdf) # get the number of pages in the document
|
| 211 |
+
last_page = max_imgboxes
|
| 212 |
+
page_indices = [i for i in range(last_page)] # pages until last_page
|
| 213 |
+
images = list(pdf.render(
|
| 214 |
+
pdfium.PdfBitmap.to_pil,
|
| 215 |
+
page_indices = page_indices,
|
| 216 |
+
scale = 300/72, # 300dpi resolution
|
| 217 |
+
))
|
| 218 |
+
|
| 219 |
+
num_imgs = len(images)
|
| 220 |
+
msg = f'The PDF "{filename}" was converted into {num_imgs} images.'
|
| 221 |
+
except:
|
| 222 |
+
msg = f'Error with the PDF "{filename}": it was not converted into images.'
|
| 223 |
+
images = [Image.open(image_wo_content)]
|
| 224 |
+
|
| 225 |
+
return filename, msg, images
|
| 226 |
+
|
| 227 |
+
# Extraction of image data (text and bounding boxes)
|
| 228 |
+
def extraction_data_from_image(images):
|
| 229 |
+
|
| 230 |
+
num_imgs = len(images)
|
| 231 |
+
|
| 232 |
+
if num_imgs > 0:
|
| 233 |
+
|
| 234 |
+
# https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
|
| 235 |
+
custom_config = r'--oem 3 --psm 3 -l eng' # default config PyTesseract: --oem 3 --psm 3 -l eng+deu+fra+jpn+por+spa+rus+hin+chi_sim
|
| 236 |
+
results, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes, images_pixels = dict(), dict(), dict(), dict(), dict(), dict(), dict(), dict(), dict()
|
| 237 |
+
images_ids_list, texts_lines_list, texts_pars_list, texts_lines_par_list, par_boxes_list, line_boxes_list, lines_par_boxes_list, images_list, images_pixels_list, page_no_list, num_pages_list = list(), list(), list(), list(), list(), list(), list(), list(), list(), list(), list()
|
| 238 |
+
|
| 239 |
+
try:
|
| 240 |
+
for i,image in enumerate(images):
|
| 241 |
+
# image preprocessing
|
| 242 |
+
# https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html
|
| 243 |
+
img = image.copy()
|
| 244 |
+
factor, path_to_img = set_image_dpi_resize(img) # Rescaling to 300dpi
|
| 245 |
+
img = Image.open(path_to_img)
|
| 246 |
+
img = np.array(img, dtype='uint8') # convert PIL to cv2
|
| 247 |
+
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
|
| 248 |
+
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
|
| 249 |
+
|
| 250 |
+
# OCR PyTesseract | get langs of page
|
| 251 |
+
txt = pytesseract.image_to_string(img, config=custom_config)
|
| 252 |
+
txt = txt.strip().lower()
|
| 253 |
+
txt = re.sub(r" +", " ", txt) # multiple space
|
| 254 |
+
txt = re.sub(r"(\n\s*)+\n+", "\n", txt) # multiple line
|
| 255 |
+
# txt = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
| 256 |
+
try:
|
| 257 |
+
langs = detect_langs(txt)
|
| 258 |
+
langs = [langdetect2Tesseract[langs[i].lang] for i in range(len(langs))]
|
| 259 |
+
langs_string = '+'.join(langs)
|
| 260 |
+
except:
|
| 261 |
+
langs_string = "eng"
|
| 262 |
+
langs_string += '+osd'
|
| 263 |
+
custom_config = f'--oem 3 --psm 3 -l {langs_string}' # default config PyTesseract: --oem 3 --psm 3
|
| 264 |
+
|
| 265 |
+
# OCR PyTesseract | get data
|
| 266 |
+
results[i] = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT)
|
| 267 |
+
# results[i] = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
| 268 |
+
|
| 269 |
+
# get image pixels
|
| 270 |
+
images_pixels[i] = feature_extractor(images[i], return_tensors="pt").pixel_values
|
| 271 |
+
|
| 272 |
+
texts_lines[i], texts_pars[i], texts_lines_par[i], row_indexes[i], par_boxes[i], line_boxes[i], lines_par_boxes[i] = get_data_paragraph(results[i], factor, conf_min=0)
|
| 273 |
+
texts_lines_list.append(texts_lines[i])
|
| 274 |
+
texts_pars_list.append(texts_pars[i])
|
| 275 |
+
texts_lines_par_list.append(texts_lines_par[i])
|
| 276 |
+
par_boxes_list.append(par_boxes[i])
|
| 277 |
+
line_boxes_list.append(line_boxes[i])
|
| 278 |
+
lines_par_boxes_list.append(lines_par_boxes[i])
|
| 279 |
+
images_ids_list.append(i)
|
| 280 |
+
images_pixels_list.append(images_pixels[i])
|
| 281 |
+
images_list.append(images[i])
|
| 282 |
+
page_no_list.append(i)
|
| 283 |
+
num_pages_list.append(num_imgs)
|
| 284 |
+
|
| 285 |
+
except:
|
| 286 |
+
print(f"There was an error within the extraction of PDF text by the OCR!")
|
| 287 |
+
else:
|
| 288 |
+
from datasets import Dataset
|
| 289 |
+
dataset = Dataset.from_dict({"images_ids": images_ids_list, "images": images_list, "images_pixels": images_pixels_list, "page_no": page_no_list, "num_pages": num_pages_list, "texts_line": texts_lines_list, "texts_par": texts_pars_list, "texts_lines_par": texts_lines_par_list, "bboxes_par": par_boxes_list, "bboxes_lines_par":lines_par_boxes_list})
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# print(f"The text data was successfully extracted by the OCR!")
|
| 293 |
+
|
| 294 |
+
return dataset, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
|
| 295 |
+
|
| 296 |
+
## Inference
|
| 297 |
+
|
| 298 |
+
def prepare_inference_features_paragraph(example, tokenizer, max_length, cls_box, sep_box):
|
| 299 |
+
|
| 300 |
+
images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list, images_pixels_list = list(), list(), list(), list(), list(), list()
|
| 301 |
+
|
| 302 |
+
# get batch
|
| 303 |
+
# batch_page_hash = example["page_hash"]
|
| 304 |
+
batch_images_ids = example["images_ids"]
|
| 305 |
+
batch_images = example["images"]
|
| 306 |
+
batch_images_pixels = example["images_pixels"]
|
| 307 |
+
batch_bboxes_par = example["bboxes_par"]
|
| 308 |
+
batch_texts_par = example["texts_par"]
|
| 309 |
+
batch_images_size = [image.size for image in batch_images]
|
| 310 |
+
|
| 311 |
+
batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
|
| 312 |
+
|
| 313 |
+
# add a dimension if not a batch but only one image
|
| 314 |
+
if not isinstance(batch_images_ids, list):
|
| 315 |
+
batch_images_ids = [batch_images_ids]
|
| 316 |
+
batch_images = [batch_images]
|
| 317 |
+
batch_images_pixels = [batch_images_pixels]
|
| 318 |
+
batch_bboxes_par = [batch_bboxes_par]
|
| 319 |
+
batch_texts_par = [batch_texts_par]
|
| 320 |
+
batch_width, batch_height = [batch_width], [batch_height]
|
| 321 |
+
|
| 322 |
+
# process all images of the batch
|
| 323 |
+
for num_batch, (image_id, image_pixels, boxes, texts_par, width, height) in enumerate(zip(batch_images_ids, batch_images_pixels, batch_bboxes_par, batch_texts_par, batch_width, batch_height)):
|
| 324 |
+
tokens_list = []
|
| 325 |
+
bboxes_list = []
|
| 326 |
+
|
| 327 |
+
# add a dimension if only on image
|
| 328 |
+
if not isinstance(texts_par, list):
|
| 329 |
+
texts_par, boxes = [texts_par], [boxes]
|
| 330 |
+
|
| 331 |
+
# convert boxes to original
|
| 332 |
+
normalize_bboxes_par = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
|
| 333 |
+
|
| 334 |
+
# sort boxes with texts
|
| 335 |
+
# we want sorted lists from top to bottom of the image
|
| 336 |
+
boxes, texts_par = sort_data_wo_labels(normalize_bboxes_par, texts_par)
|
| 337 |
+
|
| 338 |
+
count = 0
|
| 339 |
+
for box, text_par in zip(boxes, texts_par):
|
| 340 |
+
tokens_par = tokenizer.tokenize(text_par)
|
| 341 |
+
num_tokens_par = len(tokens_par) # get number of tokens
|
| 342 |
+
tokens_list.extend(tokens_par)
|
| 343 |
+
bboxes_list.extend([box] * num_tokens_par) # number of boxes must be the same as the number of tokens
|
| 344 |
+
|
| 345 |
+
# use of return_overflowing_tokens=True / stride=doc_stride
|
| 346 |
+
# to get parts of image with overlap
|
| 347 |
+
# source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
|
| 348 |
+
encodings = tokenizer(" ".join(texts_par),
|
| 349 |
+
truncation=True,
|
| 350 |
+
padding="max_length",
|
| 351 |
+
max_length=max_length,
|
| 352 |
+
stride=doc_stride,
|
| 353 |
+
return_overflowing_tokens=True,
|
| 354 |
+
return_offsets_mapping=True
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
otsm = encodings.pop("overflow_to_sample_mapping")
|
| 358 |
+
offset_mapping = encodings.pop("offset_mapping")
|
| 359 |
+
|
| 360 |
+
# Let's label those examples and get their boxes
|
| 361 |
+
sequence_length_prev = 0
|
| 362 |
+
for i, offsets in enumerate(offset_mapping):
|
| 363 |
+
# truncate tokens, boxes and labels based on length of chunk - 2 (special tokens <s> and </s>)
|
| 364 |
+
sequence_length = len(encodings.input_ids[i]) - 2
|
| 365 |
+
if i == 0: start = 0
|
| 366 |
+
else: start += sequence_length_prev - doc_stride
|
| 367 |
+
end = start + sequence_length
|
| 368 |
+
sequence_length_prev = sequence_length
|
| 369 |
+
|
| 370 |
+
# get tokens, boxes and labels of this image chunk
|
| 371 |
+
bb = [cls_box] + bboxes_list[start:end] + [sep_box]
|
| 372 |
+
|
| 373 |
+
# as the last chunk can have a length < max_length
|
| 374 |
+
# we must to add [tokenizer.pad_token] (tokens), [sep_box] (boxes) and [-100] (labels)
|
| 375 |
+
if len(bb) < max_length:
|
| 376 |
+
bb = bb + [sep_box] * (max_length - len(bb))
|
| 377 |
+
|
| 378 |
+
# append results
|
| 379 |
+
input_ids_list.append(encodings["input_ids"][i])
|
| 380 |
+
attention_mask_list.append(encodings["attention_mask"][i])
|
| 381 |
+
bb_list.append(bb)
|
| 382 |
+
images_ids_list.append(image_id)
|
| 383 |
+
chunks_ids_list.append(i)
|
| 384 |
+
images_pixels_list.append(image_pixels)
|
| 385 |
+
|
| 386 |
+
return {
|
| 387 |
+
"images_ids": images_ids_list,
|
| 388 |
+
"chunk_ids": chunks_ids_list,
|
| 389 |
+
"input_ids": input_ids_list,
|
| 390 |
+
"attention_mask": attention_mask_list,
|
| 391 |
+
"normalized_bboxes": bb_list,
|
| 392 |
+
"images_pixels": images_pixels_list
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
from torch.utils.data import Dataset
|
| 396 |
+
|
| 397 |
+
class CustomDataset(Dataset):
|
| 398 |
+
def __init__(self, dataset, tokenizer):
|
| 399 |
+
self.dataset = dataset
|
| 400 |
+
self.tokenizer = tokenizer
|
| 401 |
+
|
| 402 |
+
def __len__(self):
|
| 403 |
+
return len(self.dataset)
|
| 404 |
+
|
| 405 |
+
def __getitem__(self, idx):
|
| 406 |
+
# get item
|
| 407 |
+
example = self.dataset[idx]
|
| 408 |
+
encoding = dict()
|
| 409 |
+
encoding["images_ids"] = example["images_ids"]
|
| 410 |
+
encoding["chunk_ids"] = example["chunk_ids"]
|
| 411 |
+
encoding["input_ids"] = example["input_ids"]
|
| 412 |
+
encoding["attention_mask"] = example["attention_mask"]
|
| 413 |
+
encoding["bbox"] = example["normalized_bboxes"]
|
| 414 |
+
encoding["images_pixels"] = example["images_pixels"]
|
| 415 |
+
|
| 416 |
+
return encoding
|
| 417 |
+
|
| 418 |
+
import torch.nn.functional as F
|
| 419 |
+
|
| 420 |
+
# get predictions at token level
|
| 421 |
+
def predictions_token_level(images, custom_encoded_dataset, model_id, model):
|
| 422 |
+
|
| 423 |
+
num_imgs = len(images)
|
| 424 |
+
if num_imgs > 0:
|
| 425 |
+
|
| 426 |
+
chunk_ids, input_ids, bboxes, pixels_values, outputs, token_predictions = dict(), dict(), dict(), dict(), dict(), dict()
|
| 427 |
+
images_ids_list = list()
|
| 428 |
+
|
| 429 |
+
for i,encoding in enumerate(custom_encoded_dataset):
|
| 430 |
+
|
| 431 |
+
# get custom encoded data
|
| 432 |
+
image_id = encoding['images_ids']
|
| 433 |
+
chunk_id = encoding['chunk_ids']
|
| 434 |
+
input_id = torch.tensor(encoding['input_ids'])[None]
|
| 435 |
+
attention_mask = torch.tensor(encoding['attention_mask'])[None]
|
| 436 |
+
bbox = torch.tensor(encoding['bbox'])[None]
|
| 437 |
+
pixel_values = torch.tensor(encoding["images_pixels"])
|
| 438 |
+
|
| 439 |
+
# save data in dictionnaries
|
| 440 |
+
if image_id not in images_ids_list: images_ids_list.append(image_id)
|
| 441 |
+
|
| 442 |
+
if image_id in chunk_ids: chunk_ids[image_id].append(chunk_id)
|
| 443 |
+
else: chunk_ids[image_id] = [chunk_id]
|
| 444 |
+
|
| 445 |
+
if image_id in input_ids: input_ids[image_id].append(input_id)
|
| 446 |
+
else: input_ids[image_id] = [input_id]
|
| 447 |
+
|
| 448 |
+
if image_id in bboxes: bboxes[image_id].append(bbox)
|
| 449 |
+
else: bboxes[image_id] = [bbox]
|
| 450 |
+
|
| 451 |
+
if image_id in pixels_values: pixels_values[image_id].append(pixel_values)
|
| 452 |
+
else: pixels_values[image_id] = [pixel_values]
|
| 453 |
+
|
| 454 |
+
# get prediction with forward pass
|
| 455 |
+
with torch.no_grad():
|
| 456 |
+
|
| 457 |
+
if model_id == model_id_lilt:
|
| 458 |
+
output = model(
|
| 459 |
+
input_ids=input_id.to(device),
|
| 460 |
+
attention_mask=attention_mask.to(device),
|
| 461 |
+
bbox=bbox.to(device),
|
| 462 |
+
)
|
| 463 |
+
elif model_id == model_id_layoutxlm:
|
| 464 |
+
output = model(
|
| 465 |
+
input_ids=input_id.to(device),
|
| 466 |
+
attention_mask=attention_mask.to(device),
|
| 467 |
+
bbox=bbox.to(device),
|
| 468 |
+
image=pixel_values.to(device)
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# save probabilities of predictions in dictionnary
|
| 472 |
+
if image_id in outputs: outputs[image_id].append(F.softmax(output.logits.squeeze(), dim=-1))
|
| 473 |
+
else: outputs[image_id] = [F.softmax(output.logits.squeeze(), dim=-1)]
|
| 474 |
+
|
| 475 |
+
return outputs, images_ids_list, chunk_ids, input_ids, bboxes
|
| 476 |
+
|
| 477 |
+
else:
|
| 478 |
+
print("An error occurred while getting predictions!")
|
| 479 |
+
|
| 480 |
+
from functools import reduce
|
| 481 |
+
|
| 482 |
+
# Get predictions (line level)
|
| 483 |
+
def predictions_paragraph_level(max_length, tokenizer, id2label, dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes, cls_box, sep_box):
|
| 484 |
+
|
| 485 |
+
ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
|
| 486 |
+
bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
|
| 487 |
+
|
| 488 |
+
if len(images_ids_list) > 0:
|
| 489 |
+
|
| 490 |
+
for i, image_id in enumerate(images_ids_list):
|
| 491 |
+
|
| 492 |
+
# get image information
|
| 493 |
+
images_list = dataset.filter(lambda example: example["images_ids"] == image_id)["images"]
|
| 494 |
+
image = images_list[0]
|
| 495 |
+
width, height = image.size
|
| 496 |
+
|
| 497 |
+
# get data
|
| 498 |
+
chunk_ids_list = chunk_ids[image_id]
|
| 499 |
+
outputs_list = outputs[image_id]
|
| 500 |
+
input_ids_list = input_ids[image_id]
|
| 501 |
+
bboxes_list = bboxes[image_id]
|
| 502 |
+
|
| 503 |
+
# create zeros tensors
|
| 504 |
+
ten_probs = torch.zeros((outputs_list[0].shape[0] - 2)*len(outputs_list), outputs_list[0].shape[1])
|
| 505 |
+
ten_input_ids = torch.ones(size=(1, (outputs_list[0].shape[0] - 2)*len(outputs_list)), dtype =int)
|
| 506 |
+
ten_bboxes = torch.zeros(size=(1, (outputs_list[0].shape[0] - 2)*len(outputs_list), 4), dtype =int)
|
| 507 |
+
|
| 508 |
+
if len(outputs_list) > 1:
|
| 509 |
+
|
| 510 |
+
for num_output, (output, input_id, bbox) in enumerate(zip(outputs_list, input_ids_list, bboxes_list)):
|
| 511 |
+
start = num_output*(max_length - 2) - max(0,num_output)*doc_stride
|
| 512 |
+
end = start + (max_length - 2)
|
| 513 |
+
|
| 514 |
+
if num_output == 0:
|
| 515 |
+
ten_probs[start:end,:] += output[1:-1]
|
| 516 |
+
ten_input_ids[:,start:end] = input_id[:,1:-1]
|
| 517 |
+
ten_bboxes[:,start:end,:] = bbox[:,1:-1,:]
|
| 518 |
+
else:
|
| 519 |
+
ten_probs[start:start + doc_stride,:] += output[1:1 + doc_stride]
|
| 520 |
+
ten_probs[start:start + doc_stride,:] = ten_probs[start:start + doc_stride,:] * 0.5
|
| 521 |
+
ten_probs[start + doc_stride:end,:] += output[1 + doc_stride:-1]
|
| 522 |
+
|
| 523 |
+
ten_input_ids[:,start:start + doc_stride] = input_id[:,1:1 + doc_stride]
|
| 524 |
+
ten_input_ids[:,start + doc_stride:end] = input_id[:,1 + doc_stride:-1]
|
| 525 |
+
|
| 526 |
+
ten_bboxes[:,start:start + doc_stride,:] = bbox[:,1:1 + doc_stride,:]
|
| 527 |
+
ten_bboxes[:,start + doc_stride:end,:] = bbox[:,1 + doc_stride:-1,:]
|
| 528 |
+
|
| 529 |
+
else:
|
| 530 |
+
ten_probs += outputs_list[0][1:-1]
|
| 531 |
+
ten_input_ids = input_ids_list[0][:,1:-1]
|
| 532 |
+
ten_bboxes = bboxes_list[0][:,1:-1]
|
| 533 |
+
|
| 534 |
+
ten_probs_list, ten_input_ids_list, ten_bboxes_list = ten_probs.tolist(), ten_input_ids.tolist()[0], ten_bboxes.tolist()[0]
|
| 535 |
+
bboxes_list = list()
|
| 536 |
+
input_ids_dict, probs_dict = dict(), dict()
|
| 537 |
+
bbox_prev = [-100, -100, -100, -100]
|
| 538 |
+
for probs, input_id, bbox in zip(ten_probs_list, ten_input_ids_list, ten_bboxes_list):
|
| 539 |
+
bbox = denormalize_box(bbox, width, height)
|
| 540 |
+
if bbox != bbox_prev and bbox != cls_box and bbox != sep_box and bbox[0] != bbox[2] and bbox[1] != bbox[3]:
|
| 541 |
+
bboxes_list.append(bbox)
|
| 542 |
+
input_ids_dict[str(bbox)] = [input_id]
|
| 543 |
+
probs_dict[str(bbox)] = [probs]
|
| 544 |
+
elif bbox != cls_box and bbox != sep_box and bbox[0] != bbox[2] and bbox[1] != bbox[3]:
|
| 545 |
+
input_ids_dict[str(bbox)].append(input_id)
|
| 546 |
+
probs_dict[str(bbox)].append(probs)
|
| 547 |
+
bbox_prev = bbox
|
| 548 |
+
|
| 549 |
+
probs_bbox = dict()
|
| 550 |
+
for i,bbox in enumerate(bboxes_list):
|
| 551 |
+
probs = probs_dict[str(bbox)]
|
| 552 |
+
probs = np.array(probs).T.tolist()
|
| 553 |
+
|
| 554 |
+
probs_label = list()
|
| 555 |
+
for probs_list in probs:
|
| 556 |
+
prob_label = reduce(lambda x, y: x*y, probs_list)
|
| 557 |
+
prob_label = prob_label**(1./(len(probs_list))) # normalization
|
| 558 |
+
probs_label.append(prob_label)
|
| 559 |
+
max_value = max(probs_label)
|
| 560 |
+
max_index = probs_label.index(max_value)
|
| 561 |
+
probs_bbox[str(bbox)] = max_index
|
| 562 |
+
|
| 563 |
+
bboxes_list_dict[image_id] = bboxes_list
|
| 564 |
+
input_ids_dict_dict[image_id] = input_ids_dict
|
| 565 |
+
probs_dict_dict[image_id] = probs_bbox
|
| 566 |
+
|
| 567 |
+
df[image_id] = pd.DataFrame()
|
| 568 |
+
df[image_id]["bboxes"] = bboxes_list
|
| 569 |
+
df[image_id]["texts"] = [tokenizer.decode(input_ids_dict[str(bbox)]) for bbox in bboxes_list]
|
| 570 |
+
df[image_id]["labels"] = [id2label[probs_bbox[str(bbox)]] for bbox in bboxes_list]
|
| 571 |
+
|
| 572 |
+
return probs_bbox, bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df
|
| 573 |
+
|
| 574 |
+
else:
|
| 575 |
+
print("An error occurred while getting predictions!")
|
| 576 |
+
|
| 577 |
+
# Get labeled images with lines bounding boxes
|
| 578 |
+
def get_labeled_images(id2label, dataset, images_ids_list, bboxes_list_dict, probs_dict_dict):
|
| 579 |
+
|
| 580 |
+
labeled_images = list()
|
| 581 |
+
|
| 582 |
+
for i, image_id in enumerate(images_ids_list):
|
| 583 |
+
|
| 584 |
+
# get image
|
| 585 |
+
images_list = dataset.filter(lambda example: example["images_ids"] == image_id)["images"]
|
| 586 |
+
image = images_list[0]
|
| 587 |
+
width, height = image.size
|
| 588 |
+
|
| 589 |
+
# get predicted boxes and labels
|
| 590 |
+
bboxes_list = bboxes_list_dict[image_id]
|
| 591 |
+
probs_bbox = probs_dict_dict[image_id]
|
| 592 |
+
|
| 593 |
+
draw = ImageDraw.Draw(image)
|
| 594 |
+
# https://stackoverflow.com/questions/66274858/choosing-a-pil-imagefont-by-font-name-rather-than-filename-and-cross-platform-f
|
| 595 |
+
font = font_manager.FontProperties(family='sans-serif', weight='bold')
|
| 596 |
+
font_file = font_manager.findfont(font)
|
| 597 |
+
font_size = 30
|
| 598 |
+
font = ImageFont.truetype(font_file, font_size)
|
| 599 |
+
|
| 600 |
+
for bbox in bboxes_list:
|
| 601 |
+
predicted_label = id2label[probs_bbox[str(bbox)]]
|
| 602 |
+
draw.rectangle(bbox, outline=label2color[predicted_label])
|
| 603 |
+
draw.text((bbox[0] + 10, bbox[1] - font_size), text=predicted_label, fill=label2color[predicted_label], font=font)
|
| 604 |
+
|
| 605 |
+
labeled_images.append(image)
|
| 606 |
+
|
| 607 |
+
return labeled_images
|
| 608 |
+
|
| 609 |
+
# get data of encoded chunk
|
| 610 |
+
def get_encoded_chunk_inference(tokenizer, dataset, encoded_dataset, index_chunk=None):
|
| 611 |
+
|
| 612 |
+
# get datasets
|
| 613 |
+
example = dataset
|
| 614 |
+
encoded_example = encoded_dataset
|
| 615 |
+
|
| 616 |
+
# get randomly a document in dataset
|
| 617 |
+
if index_chunk == None: index_chunk = random.randint(0, len(encoded_example)-1)
|
| 618 |
+
encoded_example = encoded_example[index_chunk]
|
| 619 |
+
encoded_image_ids = encoded_example["images_ids"]
|
| 620 |
+
|
| 621 |
+
# get the image
|
| 622 |
+
example = example.filter(lambda example: example["images_ids"] == encoded_image_ids)[0]
|
| 623 |
+
image = example["images"] # original image
|
| 624 |
+
width, height = image.size
|
| 625 |
+
page_no = example["page_no"]
|
| 626 |
+
num_pages = example["num_pages"]
|
| 627 |
+
|
| 628 |
+
# get boxes, texts, categories
|
| 629 |
+
bboxes, input_ids = encoded_example["normalized_bboxes"][1:-1], encoded_example["input_ids"][1:-1]
|
| 630 |
+
bboxes = [denormalize_box(bbox, width, height) for bbox in bboxes]
|
| 631 |
+
num_tokens = len(input_ids) + 2
|
| 632 |
+
|
| 633 |
+
# get unique bboxes and corresponding labels
|
| 634 |
+
bboxes_list, input_ids_list = list(), list()
|
| 635 |
+
input_ids_dict = dict()
|
| 636 |
+
bbox_prev = [-100, -100, -100, -100]
|
| 637 |
+
for i, (bbox, input_id) in enumerate(zip(bboxes, input_ids)):
|
| 638 |
+
if bbox != bbox_prev:
|
| 639 |
+
bboxes_list.append(bbox)
|
| 640 |
+
input_ids_dict[str(bbox)] = [input_id]
|
| 641 |
+
else:
|
| 642 |
+
input_ids_dict[str(bbox)].append(input_id)
|
| 643 |
+
|
| 644 |
+
# start_indexes_list.append(i)
|
| 645 |
+
bbox_prev = bbox
|
| 646 |
+
|
| 647 |
+
# do not keep "</s><pad><pad>..."
|
| 648 |
+
if input_ids_dict[str(bboxes_list[-1])][0] == (tokenizer.convert_tokens_to_ids('</s>')):
|
| 649 |
+
del input_ids_dict[str(bboxes_list[-1])]
|
| 650 |
+
bboxes_list = bboxes_list[:-1]
|
| 651 |
+
|
| 652 |
+
# get texts by line
|
| 653 |
+
input_ids_list = input_ids_dict.values()
|
| 654 |
+
texts_list = [tokenizer.decode(input_ids) for input_ids in input_ids_list]
|
| 655 |
+
|
| 656 |
+
# display DataFrame
|
| 657 |
+
df = pd.DataFrame({"texts": texts_list, "input_ids": input_ids_list, "bboxes": bboxes_list})
|
| 658 |
+
|
| 659 |
+
return image, df, num_tokens, page_no, num_pages
|
| 660 |
+
|
| 661 |
+
# display chunk of PDF image and its data
|
| 662 |
+
def display_chunk_lines_inference(dataset, encoded_dataset, index_chunk=None):
|
| 663 |
+
|
| 664 |
+
# get image and image data
|
| 665 |
+
image, df, num_tokens, page_no, num_pages = get_encoded_chunk_inference(dataset, encoded_dataset, index_chunk=index_chunk)
|
| 666 |
+
|
| 667 |
+
# get data from dataframe
|
| 668 |
+
input_ids = df["input_ids"]
|
| 669 |
+
texts = df["texts"]
|
| 670 |
+
bboxes = df["bboxes"]
|
| 671 |
+
|
| 672 |
+
print(f'Chunk ({num_tokens} tokens) of the PDF (page: {page_no+1} / {num_pages})\n')
|
| 673 |
+
|
| 674 |
+
# display image with bounding boxes
|
| 675 |
+
print(">> PDF image with bounding boxes of lines\n")
|
| 676 |
+
draw = ImageDraw.Draw(image)
|
| 677 |
+
|
| 678 |
+
labels = list()
|
| 679 |
+
for box, text in zip(bboxes, texts):
|
| 680 |
+
color = "red"
|
| 681 |
+
draw.rectangle(box, outline=color)
|
| 682 |
+
|
| 683 |
+
# resize image to original
|
| 684 |
+
width, height = image.size
|
| 685 |
+
image = image.resize((int(0.5*width), int(0.5*height)))
|
| 686 |
+
|
| 687 |
+
# convert to cv and display
|
| 688 |
+
img = np.array(image, dtype='uint8') # PIL to cv2
|
| 689 |
+
cv2_imshow(img)
|
| 690 |
+
cv2.waitKey(0)
|
| 691 |
+
|
| 692 |
+
# display image dataframe
|
| 693 |
+
print("\n>> Dataframe of annotated lines\n")
|
| 694 |
+
cols = ["texts", "bboxes"]
|
| 695 |
+
df = df[cols]
|
| 696 |
+
display(df)
|