Commit
·
c45522e
1
Parent(s):
6dbb555
Update files/functions.py
Browse files- files/functions.py +97 -60
files/functions.py
CHANGED
|
@@ -117,7 +117,7 @@ langdetect2Tesseract = {v:k for k,v in Tesseract2langdetect.items()}
|
|
| 117 |
# get text and bounding boxes from an image
|
| 118 |
# https://stackoverflow.com/questions/61347755/how-can-i-get-line-coordinates-that-readed-by-tesseract
|
| 119 |
# https://medium.com/geekculture/tesseract-ocr-understanding-the-contents-of-documents-beyond-their-text-a98704b7c655
|
| 120 |
-
def
|
| 121 |
|
| 122 |
data = {}
|
| 123 |
for i in range(len(results['line_num'])):
|
|
@@ -160,43 +160,55 @@ def get_data(results, factor, conf_min=0):
|
|
| 160 |
par_idx += 1
|
| 161 |
|
| 162 |
# get lines of texts, grouped by paragraph
|
| 163 |
-
|
| 164 |
row_indexes = list()
|
|
|
|
|
|
|
| 165 |
row_index = 0
|
| 166 |
for _,par in par_data.items():
|
| 167 |
count_lines = 0
|
|
|
|
| 168 |
for _,line in par.items():
|
| 169 |
if count_lines == 0: row_indexes.append(row_index)
|
| 170 |
line_text = ' '.join([item[0] for item in line])
|
| 171 |
-
|
|
|
|
| 172 |
count_lines += 1
|
| 173 |
row_index += 1
|
| 174 |
# lines.append("\n")
|
| 175 |
row_index += 1
|
|
|
|
|
|
|
| 176 |
# lines = lines[:-1]
|
| 177 |
|
| 178 |
# get paragraphes boxes (par_boxes)
|
| 179 |
# get lines boxes (line_boxes)
|
| 180 |
par_boxes = list()
|
| 181 |
par_idx = 1
|
| 182 |
-
line_boxes = list()
|
| 183 |
line_idx = 1
|
| 184 |
for _, par in par_data.items():
|
| 185 |
xmins, ymins, xmaxs, ymaxs = list(), list(), list(), list()
|
|
|
|
|
|
|
| 186 |
for _, line in par.items():
|
| 187 |
xmin, ymin = line[0][1], line[0][2]
|
| 188 |
xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
|
| 189 |
line_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
|
|
|
|
| 190 |
xmins.append(xmin)
|
| 191 |
ymins.append(ymin)
|
| 192 |
xmaxs.append(xmax)
|
| 193 |
ymaxs.append(ymax)
|
| 194 |
line_idx += 1
|
|
|
|
| 195 |
xmin, ymin, xmax, ymax = min(xmins), min(ymins), max(xmaxs), max(ymaxs)
|
| 196 |
-
|
|
|
|
|
|
|
| 197 |
par_idx += 1
|
| 198 |
|
| 199 |
-
return
|
| 200 |
|
| 201 |
# rescale image to get 300dpi
|
| 202 |
def set_image_dpi_resize(image):
|
|
@@ -259,7 +271,8 @@ def original_box(box, original_width, original_height, coco_width, coco_height):
|
|
| 259 |
]
|
| 260 |
|
| 261 |
def get_blocks(bboxes_block, categories, texts):
|
| 262 |
-
|
|
|
|
| 263 |
bbox_block_dict, bboxes_block_list, bbox_block_prec = dict(), list(), list()
|
| 264 |
for count_block, bbox_block in enumerate(bboxes_block):
|
| 265 |
if bbox_block != bbox_block_prec:
|
|
@@ -324,7 +337,7 @@ def sort_data_wo_labels(bboxes, texts):
|
|
| 324 |
|
| 325 |
return sorted_bboxes, sorted_texts
|
| 326 |
|
| 327 |
-
##
|
| 328 |
|
| 329 |
# get filename and images of PDF pages
|
| 330 |
def pdf_to_images(uploaded_pdf):
|
|
@@ -358,6 +371,44 @@ def pdf_to_images(uploaded_pdf):
|
|
| 358 |
|
| 359 |
return filename, msg, images
|
| 360 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
# Extraction of image data (text and bounding boxes)
|
| 362 |
def extraction_data_from_image(images):
|
| 363 |
|
|
@@ -367,8 +418,8 @@ def extraction_data_from_image(images):
|
|
| 367 |
|
| 368 |
# https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
|
| 369 |
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
|
| 370 |
-
results,
|
| 371 |
-
images_ids_list,
|
| 372 |
|
| 373 |
try:
|
| 374 |
for i,image in enumerate(images):
|
|
@@ -380,14 +431,13 @@ def extraction_data_from_image(images):
|
|
| 380 |
img = np.array(img, dtype='uint8') # convert PIL to cv2
|
| 381 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
|
| 382 |
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
|
| 383 |
-
|
| 384 |
# OCR PyTesseract | get langs of page
|
| 385 |
txt = pytesseract.image_to_string(img, config=custom_config)
|
| 386 |
txt = txt.strip().lower()
|
| 387 |
txt = re.sub(r" +", " ", txt) # multiple space
|
| 388 |
txt = re.sub(r"(\n\s*)+\n+", "\n", txt) # multiple line
|
| 389 |
# txt = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
| 390 |
-
|
| 391 |
try:
|
| 392 |
langs = detect_langs(txt)
|
| 393 |
langs = [langdetect2Tesseract[langs[i].lang] for i in range(len(langs))]
|
|
@@ -395,36 +445,37 @@ def extraction_data_from_image(images):
|
|
| 395 |
except:
|
| 396 |
langs_string = "eng"
|
| 397 |
langs_string += '+osd'
|
| 398 |
-
|
| 399 |
-
custom_config = f'--oem 3 --psm 3 -l {langs_string} tsv' # default config PyTesseract: --oem 3 --psm 3
|
| 400 |
|
| 401 |
# OCR PyTesseract | get data
|
| 402 |
results[i] = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT)
|
| 403 |
# results[i] = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
| 404 |
|
| 405 |
-
|
| 406 |
-
|
|
|
|
|
|
|
| 407 |
par_boxes_list.append(par_boxes[i])
|
| 408 |
line_boxes_list.append(line_boxes[i])
|
|
|
|
| 409 |
images_ids_list.append(i)
|
| 410 |
images_list.append(images[i])
|
| 411 |
page_no_list.append(i)
|
| 412 |
-
num_pages_list.append(num_imgs)
|
| 413 |
|
| 414 |
except:
|
| 415 |
print(f"There was an error within the extraction of PDF text by the OCR!")
|
| 416 |
else:
|
| 417 |
from datasets import Dataset
|
| 418 |
-
dataset = Dataset.from_dict({"images_ids": images_ids_list, "images": images_list, "page_no": page_no_list, "num_pages": num_pages_list, "
|
| 419 |
|
| 420 |
-
print(f"The text data was successfully extracted by the OCR!")
|
| 421 |
|
| 422 |
-
return dataset,
|
| 423 |
|
| 424 |
## Inference
|
| 425 |
|
| 426 |
-
|
| 427 |
-
def prepare_inference_features(example):
|
| 428 |
|
| 429 |
images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list = list(), list(), list(), list(), list()
|
| 430 |
|
|
@@ -433,7 +484,7 @@ def prepare_inference_features(example):
|
|
| 433 |
batch_images_ids = example["images_ids"]
|
| 434 |
batch_images = example["images"]
|
| 435 |
batch_bboxes_par = example["bboxes_par"]
|
| 436 |
-
|
| 437 |
batch_images_size = [image.size for image in batch_images]
|
| 438 |
|
| 439 |
batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
|
|
@@ -443,50 +494,36 @@ def prepare_inference_features(example):
|
|
| 443 |
batch_images_ids = [batch_images_ids]
|
| 444 |
batch_images = [batch_images]
|
| 445 |
batch_bboxes_par = [batch_bboxes_par]
|
| 446 |
-
|
| 447 |
batch_width, batch_height = [batch_width], [batch_height]
|
| 448 |
-
|
| 449 |
# process all images of the batch
|
| 450 |
-
for num_batch, (image_id, boxes,
|
| 451 |
tokens_list = []
|
| 452 |
bboxes_list = []
|
| 453 |
|
| 454 |
# add a dimension if only on image
|
| 455 |
-
if not isinstance(
|
| 456 |
-
|
| 457 |
|
| 458 |
# convert boxes to original
|
| 459 |
normalize_bboxes_par = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
|
| 460 |
|
| 461 |
# sort boxes with texts
|
| 462 |
# we want sorted lists from top to bottom of the image
|
| 463 |
-
boxes,
|
| 464 |
-
|
| 465 |
-
bboxes_unique_list, texts_blocks = list(), list()
|
| 466 |
-
bbox_prev = [-100, -100, -100, -100]
|
| 467 |
-
for bbox, text in zip(boxes, texts):
|
| 468 |
-
if bbox != bbox_prev and bbox != cls_box:
|
| 469 |
-
bboxes_unique_list.append(bbox)
|
| 470 |
-
texts_block = text
|
| 471 |
-
else:
|
| 472 |
-
if bbox != cls_box:
|
| 473 |
-
texts_block += '\n' + text
|
| 474 |
-
else:
|
| 475 |
-
texts_blocks.append(texts_block)
|
| 476 |
-
bbox_prev = bbox
|
| 477 |
|
| 478 |
count = 0
|
| 479 |
-
for box,
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
tokens_list.extend(
|
| 483 |
-
|
| 484 |
-
bboxes_list.extend([box] * num_tokens) # number of boxes must be the same as the number of tokens
|
| 485 |
|
| 486 |
# use of return_overflowing_tokens=True / stride=doc_stride
|
| 487 |
# to get parts of image with overlap
|
| 488 |
# source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
|
| 489 |
-
encodings = tokenizer(" ".join(
|
| 490 |
truncation=True,
|
| 491 |
padding="max_length",
|
| 492 |
max_length=max_length,
|
|
@@ -531,7 +568,7 @@ def prepare_inference_features(example):
|
|
| 531 |
"normalized_bboxes": bb_list,
|
| 532 |
}
|
| 533 |
|
| 534 |
-
from torch.utils.data import Dataset
|
| 535 |
|
| 536 |
class CustomDataset(Dataset):
|
| 537 |
def __init__(self, dataset, tokenizer):
|
|
@@ -550,11 +587,10 @@ class CustomDataset(Dataset):
|
|
| 550 |
encoding["input_ids"] = example["input_ids"]
|
| 551 |
encoding["attention_mask"] = example["attention_mask"]
|
| 552 |
encoding["bbox"] = example["normalized_bboxes"]
|
| 553 |
-
# encoding["labels"] = example["labels"]
|
| 554 |
|
| 555 |
return encoding
|
| 556 |
-
|
| 557 |
-
import torch.nn.functional as F
|
| 558 |
|
| 559 |
# get predictions at token level
|
| 560 |
def predictions_token_level(images, custom_encoded_dataset):
|
|
@@ -563,6 +599,7 @@ def predictions_token_level(images, custom_encoded_dataset):
|
|
| 563 |
if num_imgs > 0:
|
| 564 |
|
| 565 |
chunk_ids, input_ids, bboxes, outputs, token_predictions = dict(), dict(), dict(), dict(), dict()
|
|
|
|
| 566 |
images_ids_list = list()
|
| 567 |
|
| 568 |
for i,encoding in enumerate(custom_encoded_dataset):
|
|
@@ -605,8 +642,8 @@ def predictions_token_level(images, custom_encoded_dataset):
|
|
| 605 |
|
| 606 |
from functools import reduce
|
| 607 |
|
| 608 |
-
# Get predictions (
|
| 609 |
-
def
|
| 610 |
|
| 611 |
ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
|
| 612 |
bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
|
|
@@ -672,7 +709,7 @@ def predictions_paragraph_level(dataset, outputs, images_ids_list, chunk_ids, in
|
|
| 672 |
input_ids_dict[str(bbox)].append(input_id)
|
| 673 |
probs_dict[str(bbox)].append(probs)
|
| 674 |
bbox_prev = bbox
|
| 675 |
-
|
| 676 |
probs_bbox = dict()
|
| 677 |
for i,bbox in enumerate(bboxes_list):
|
| 678 |
probs = probs_dict[str(bbox)]
|
|
@@ -700,8 +737,8 @@ def predictions_paragraph_level(dataset, outputs, images_ids_list, chunk_ids, in
|
|
| 700 |
else:
|
| 701 |
print("An error occurred while getting predictions!")
|
| 702 |
|
| 703 |
-
# Get labeled images with
|
| 704 |
-
def
|
| 705 |
|
| 706 |
labeled_images = list()
|
| 707 |
|
|
@@ -775,7 +812,7 @@ def get_encoded_chunk_inference(index_chunk=None):
|
|
| 775 |
del input_ids_dict[str(bboxes_list[-1])]
|
| 776 |
bboxes_list = bboxes_list[:-1]
|
| 777 |
|
| 778 |
-
# get texts by
|
| 779 |
input_ids_list = input_ids_dict.values()
|
| 780 |
texts_list = [tokenizer.decode(input_ids) for input_ids in input_ids_list]
|
| 781 |
|
|
@@ -816,7 +853,7 @@ def display_chunk_paragraphs_inference(index_chunk=None):
|
|
| 816 |
cv2.waitKey(0)
|
| 817 |
|
| 818 |
# display image dataframe
|
| 819 |
-
print("\n>> Dataframe of annotated
|
| 820 |
cols = ["texts", "bboxes"]
|
| 821 |
df = df[cols]
|
| 822 |
display(df)
|
|
|
|
| 117 |
# get text and bounding boxes from an image
|
| 118 |
# https://stackoverflow.com/questions/61347755/how-can-i-get-line-coordinates-that-readed-by-tesseract
|
| 119 |
# https://medium.com/geekculture/tesseract-ocr-understanding-the-contents-of-documents-beyond-their-text-a98704b7c655
|
| 120 |
+
def get_data_paragraph(results, factor, conf_min=0):
|
| 121 |
|
| 122 |
data = {}
|
| 123 |
for i in range(len(results['line_num'])):
|
|
|
|
| 160 |
par_idx += 1
|
| 161 |
|
| 162 |
# get lines of texts, grouped by paragraph
|
| 163 |
+
texts_pars = list()
|
| 164 |
row_indexes = list()
|
| 165 |
+
texts_lines = list()
|
| 166 |
+
texts_lines_par = list()
|
| 167 |
row_index = 0
|
| 168 |
for _,par in par_data.items():
|
| 169 |
count_lines = 0
|
| 170 |
+
lines_par = list()
|
| 171 |
for _,line in par.items():
|
| 172 |
if count_lines == 0: row_indexes.append(row_index)
|
| 173 |
line_text = ' '.join([item[0] for item in line])
|
| 174 |
+
texts_lines.append(line_text)
|
| 175 |
+
lines_par.append(line_text)
|
| 176 |
count_lines += 1
|
| 177 |
row_index += 1
|
| 178 |
# lines.append("\n")
|
| 179 |
row_index += 1
|
| 180 |
+
texts_lines_par.append(lines_par)
|
| 181 |
+
texts_pars.append(' '.join(lines_par))
|
| 182 |
# lines = lines[:-1]
|
| 183 |
|
| 184 |
# get paragraphes boxes (par_boxes)
|
| 185 |
# get lines boxes (line_boxes)
|
| 186 |
par_boxes = list()
|
| 187 |
par_idx = 1
|
| 188 |
+
line_boxes, lines_par_boxes = list(), list()
|
| 189 |
line_idx = 1
|
| 190 |
for _, par in par_data.items():
|
| 191 |
xmins, ymins, xmaxs, ymaxs = list(), list(), list(), list()
|
| 192 |
+
line_boxes_par = list()
|
| 193 |
+
count_line_par = 0
|
| 194 |
for _, line in par.items():
|
| 195 |
xmin, ymin = line[0][1], line[0][2]
|
| 196 |
xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
|
| 197 |
line_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
|
| 198 |
+
line_boxes_par.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
|
| 199 |
xmins.append(xmin)
|
| 200 |
ymins.append(ymin)
|
| 201 |
xmaxs.append(xmax)
|
| 202 |
ymaxs.append(ymax)
|
| 203 |
line_idx += 1
|
| 204 |
+
count_line_par += 1
|
| 205 |
xmin, ymin, xmax, ymax = min(xmins), min(ymins), max(xmaxs), max(ymaxs)
|
| 206 |
+
par_bbox = [int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)]
|
| 207 |
+
par_boxes.append(par_bbox)
|
| 208 |
+
lines_par_boxes.append(line_boxes_par)
|
| 209 |
par_idx += 1
|
| 210 |
|
| 211 |
+
return texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
|
| 212 |
|
| 213 |
# rescale image to get 300dpi
|
| 214 |
def set_image_dpi_resize(image):
|
|
|
|
| 271 |
]
|
| 272 |
|
| 273 |
def get_blocks(bboxes_block, categories, texts):
|
| 274 |
+
|
| 275 |
+
# get list of unique block boxes
|
| 276 |
bbox_block_dict, bboxes_block_list, bbox_block_prec = dict(), list(), list()
|
| 277 |
for count_block, bbox_block in enumerate(bboxes_block):
|
| 278 |
if bbox_block != bbox_block_prec:
|
|
|
|
| 337 |
|
| 338 |
return sorted_bboxes, sorted_texts
|
| 339 |
|
| 340 |
+
## PDf Processing
|
| 341 |
|
| 342 |
# get filename and images of PDF pages
|
| 343 |
def pdf_to_images(uploaded_pdf):
|
|
|
|
| 371 |
|
| 372 |
return filename, msg, images
|
| 373 |
|
| 374 |
+
# get filename and images of PDF pages
|
| 375 |
+
def pdf_to_images(uploaded_pdf):
|
| 376 |
+
|
| 377 |
+
# file name of the uploaded PDF
|
| 378 |
+
filename = next(iter(uploaded_pdf))
|
| 379 |
+
|
| 380 |
+
try:
|
| 381 |
+
PdfReader(filename)
|
| 382 |
+
except PdfReadError:
|
| 383 |
+
print("Invalid PDF file.")
|
| 384 |
+
else:
|
| 385 |
+
try:
|
| 386 |
+
images = convert_from_path(str(filename))
|
| 387 |
+
num_imgs = len(images)
|
| 388 |
+
print(f'The PDF "{filename}"" was converted into {num_imgs} images.')
|
| 389 |
+
print("Now, you can extract data from theses images (text, bounding boxes...).")
|
| 390 |
+
except:
|
| 391 |
+
print(f"Error with the PDF {filename}:it was not converted into images.")
|
| 392 |
+
print()
|
| 393 |
+
else:
|
| 394 |
+
# display images
|
| 395 |
+
if num_imgs > 0:
|
| 396 |
+
|
| 397 |
+
import matplotlib.pyplot as plt
|
| 398 |
+
%matplotlib inline
|
| 399 |
+
|
| 400 |
+
plt.figure(figsize=(20,10))
|
| 401 |
+
columns = 5
|
| 402 |
+
for i, image in enumerate(images):
|
| 403 |
+
plt.subplot(num_imgs / columns + 1, columns, i + 1)
|
| 404 |
+
plt.xticks(color="white")
|
| 405 |
+
plt.yticks(color="white")
|
| 406 |
+
plt.tick_params(bottom = False)
|
| 407 |
+
plt.tick_params(left = False)
|
| 408 |
+
plt.imshow(image)
|
| 409 |
+
|
| 410 |
+
return filename, images
|
| 411 |
+
|
| 412 |
# Extraction of image data (text and bounding boxes)
|
| 413 |
def extraction_data_from_image(images):
|
| 414 |
|
|
|
|
| 418 |
|
| 419 |
# https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
|
| 420 |
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
|
| 421 |
+
results, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes = dict(), dict(), dict(), dict(), dict(), dict(), dict(), dict()
|
| 422 |
+
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, page_no_list, num_pages_list = list(), list(), list(), list(), list(), list(), list(), list(), list(), list()
|
| 423 |
|
| 424 |
try:
|
| 425 |
for i,image in enumerate(images):
|
|
|
|
| 431 |
img = np.array(img, dtype='uint8') # convert PIL to cv2
|
| 432 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
|
| 433 |
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
|
| 434 |
+
|
| 435 |
# OCR PyTesseract | get langs of page
|
| 436 |
txt = pytesseract.image_to_string(img, config=custom_config)
|
| 437 |
txt = txt.strip().lower()
|
| 438 |
txt = re.sub(r" +", " ", txt) # multiple space
|
| 439 |
txt = re.sub(r"(\n\s*)+\n+", "\n", txt) # multiple line
|
| 440 |
# txt = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
|
|
|
| 441 |
try:
|
| 442 |
langs = detect_langs(txt)
|
| 443 |
langs = [langdetect2Tesseract[langs[i].lang] for i in range(len(langs))]
|
|
|
|
| 445 |
except:
|
| 446 |
langs_string = "eng"
|
| 447 |
langs_string += '+osd'
|
| 448 |
+
custom_config = f'--oem 3 --psm 3 -l {langs_string}' # default config PyTesseract: --oem 3 --psm 3
|
|
|
|
| 449 |
|
| 450 |
# OCR PyTesseract | get data
|
| 451 |
results[i] = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT)
|
| 452 |
# results[i] = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
| 453 |
|
| 454 |
+
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)
|
| 455 |
+
texts_lines_list.append(texts_lines[i])
|
| 456 |
+
texts_pars_list.append(texts_pars[i])
|
| 457 |
+
texts_lines_par_list.append(texts_lines_par[i])
|
| 458 |
par_boxes_list.append(par_boxes[i])
|
| 459 |
line_boxes_list.append(line_boxes[i])
|
| 460 |
+
lines_par_boxes_list.append(lines_par_boxes[i])
|
| 461 |
images_ids_list.append(i)
|
| 462 |
images_list.append(images[i])
|
| 463 |
page_no_list.append(i)
|
| 464 |
+
num_pages_list.append(num_imgs)
|
| 465 |
|
| 466 |
except:
|
| 467 |
print(f"There was an error within the extraction of PDF text by the OCR!")
|
| 468 |
else:
|
| 469 |
from datasets import Dataset
|
| 470 |
+
dataset = Dataset.from_dict({"images_ids": images_ids_list, "images": images_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})
|
| 471 |
|
| 472 |
+
# print(f"The text data was successfully extracted by the OCR!")
|
| 473 |
|
| 474 |
+
return dataset, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
|
| 475 |
|
| 476 |
## Inference
|
| 477 |
|
| 478 |
+
def prepare_inference_features_paragraph(example, cls_box = cls_box, sep_box = sep_box):
|
|
|
|
| 479 |
|
| 480 |
images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list = list(), list(), list(), list(), list()
|
| 481 |
|
|
|
|
| 484 |
batch_images_ids = example["images_ids"]
|
| 485 |
batch_images = example["images"]
|
| 486 |
batch_bboxes_par = example["bboxes_par"]
|
| 487 |
+
batch_texts_par = example["texts_par"]
|
| 488 |
batch_images_size = [image.size for image in batch_images]
|
| 489 |
|
| 490 |
batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
|
|
|
|
| 494 |
batch_images_ids = [batch_images_ids]
|
| 495 |
batch_images = [batch_images]
|
| 496 |
batch_bboxes_par = [batch_bboxes_par]
|
| 497 |
+
batch_texts_par = [batch_texts_par]
|
| 498 |
batch_width, batch_height = [batch_width], [batch_height]
|
| 499 |
+
|
| 500 |
# process all images of the batch
|
| 501 |
+
for num_batch, (image_id, boxes, texts_par, width, height) in enumerate(zip(batch_images_ids, batch_bboxes_par, batch_texts_par, batch_width, batch_height)):
|
| 502 |
tokens_list = []
|
| 503 |
bboxes_list = []
|
| 504 |
|
| 505 |
# add a dimension if only on image
|
| 506 |
+
if not isinstance(texts_par, list):
|
| 507 |
+
texts_par, boxes = [texts_par], [boxes]
|
| 508 |
|
| 509 |
# convert boxes to original
|
| 510 |
normalize_bboxes_par = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
|
| 511 |
|
| 512 |
# sort boxes with texts
|
| 513 |
# we want sorted lists from top to bottom of the image
|
| 514 |
+
boxes, texts_par = sort_data_wo_labels(normalize_bboxes_par, texts_par)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
|
| 516 |
count = 0
|
| 517 |
+
for box, text_par in zip(boxes, texts_par):
|
| 518 |
+
tokens_par = tokenizer.tokenize(text_par)
|
| 519 |
+
num_tokens_par = len(tokens_par) # get number of tokens
|
| 520 |
+
tokens_list.extend(tokens_par)
|
| 521 |
+
bboxes_list.extend([box] * num_tokens_par) # number of boxes must be the same as the number of tokens
|
|
|
|
| 522 |
|
| 523 |
# use of return_overflowing_tokens=True / stride=doc_stride
|
| 524 |
# to get parts of image with overlap
|
| 525 |
# source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
|
| 526 |
+
encodings = tokenizer(" ".join(texts_par),
|
| 527 |
truncation=True,
|
| 528 |
padding="max_length",
|
| 529 |
max_length=max_length,
|
|
|
|
| 568 |
"normalized_bboxes": bb_list,
|
| 569 |
}
|
| 570 |
|
| 571 |
+
from torch.utils.data import Dataset
|
| 572 |
|
| 573 |
class CustomDataset(Dataset):
|
| 574 |
def __init__(self, dataset, tokenizer):
|
|
|
|
| 587 |
encoding["input_ids"] = example["input_ids"]
|
| 588 |
encoding["attention_mask"] = example["attention_mask"]
|
| 589 |
encoding["bbox"] = example["normalized_bboxes"]
|
|
|
|
| 590 |
|
| 591 |
return encoding
|
| 592 |
+
|
| 593 |
+
import torch.nn.functional as F
|
| 594 |
|
| 595 |
# get predictions at token level
|
| 596 |
def predictions_token_level(images, custom_encoded_dataset):
|
|
|
|
| 599 |
if num_imgs > 0:
|
| 600 |
|
| 601 |
chunk_ids, input_ids, bboxes, outputs, token_predictions = dict(), dict(), dict(), dict(), dict()
|
| 602 |
+
normalize_batch_bboxes_lines_pars = dict()
|
| 603 |
images_ids_list = list()
|
| 604 |
|
| 605 |
for i,encoding in enumerate(custom_encoded_dataset):
|
|
|
|
| 642 |
|
| 643 |
from functools import reduce
|
| 644 |
|
| 645 |
+
# Get predictions (line level)
|
| 646 |
+
def predictions_paragraph_level_gradio(dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes):
|
| 647 |
|
| 648 |
ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
|
| 649 |
bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
|
|
|
|
| 709 |
input_ids_dict[str(bbox)].append(input_id)
|
| 710 |
probs_dict[str(bbox)].append(probs)
|
| 711 |
bbox_prev = bbox
|
| 712 |
+
|
| 713 |
probs_bbox = dict()
|
| 714 |
for i,bbox in enumerate(bboxes_list):
|
| 715 |
probs = probs_dict[str(bbox)]
|
|
|
|
| 737 |
else:
|
| 738 |
print("An error occurred while getting predictions!")
|
| 739 |
|
| 740 |
+
# Get labeled images with lines bounding boxes
|
| 741 |
+
def get_labeled_images_gradio(dataset, images_ids_list, bboxes_list_dict, probs_dict_dict):
|
| 742 |
|
| 743 |
labeled_images = list()
|
| 744 |
|
|
|
|
| 812 |
del input_ids_dict[str(bboxes_list[-1])]
|
| 813 |
bboxes_list = bboxes_list[:-1]
|
| 814 |
|
| 815 |
+
# get texts by line
|
| 816 |
input_ids_list = input_ids_dict.values()
|
| 817 |
texts_list = [tokenizer.decode(input_ids) for input_ids in input_ids_list]
|
| 818 |
|
|
|
|
| 853 |
cv2.waitKey(0)
|
| 854 |
|
| 855 |
# display image dataframe
|
| 856 |
+
print("\n>> Dataframe of annotated paragraphs\n")
|
| 857 |
cols = ["texts", "bboxes"]
|
| 858 |
df = df[cols]
|
| 859 |
display(df)
|