pierreguillou
commited on
Commit
•
4e49717
1
Parent(s):
4ea52a3
Update files/functions.py
Browse files- files/functions.py +63 -51
files/functions.py
CHANGED
@@ -57,7 +57,7 @@ sep_box = cls_box
|
|
57 |
from transformers import AutoTokenizer, AutoModelForTokenClassification
|
58 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
59 |
|
60 |
-
model_id = "pierreguillou/lilt-xlm-roberta-base-finetuned-
|
61 |
|
62 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
63 |
model = AutoModelForTokenClassification.from_pretrained(model_id);
|
@@ -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 |
-
## PDF
|
328 |
|
329 |
# get filename and images of PDF pages
|
330 |
def pdf_to_images(uploaded_pdf):
|
@@ -367,8 +380,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 +393,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 +407,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 |
|
@@ -432,8 +445,8 @@ def prepare_inference_features(example):
|
|
432 |
# batch_page_hash = example["page_hash"]
|
433 |
batch_images_ids = example["images_ids"]
|
434 |
batch_images = example["images"]
|
435 |
-
|
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]
|
@@ -442,38 +455,37 @@ def prepare_inference_features(example):
|
|
442 |
if not isinstance(batch_images_ids, list):
|
443 |
batch_images_ids = [batch_images_ids]
|
444 |
batch_images = [batch_images]
|
445 |
-
|
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 |
-
|
460 |
|
461 |
# sort boxes with texts
|
462 |
# we want sorted lists from top to bottom of the image
|
463 |
-
boxes,
|
464 |
|
465 |
count = 0
|
466 |
-
for box,
|
467 |
-
|
468 |
-
|
469 |
-
tokens_list.extend(
|
470 |
-
|
471 |
-
bboxes_list.extend([box] * num_tokens) # number of boxes must be the same as the number of tokens
|
472 |
|
473 |
# use of return_overflowing_tokens=True / stride=doc_stride
|
474 |
# to get parts of image with overlap
|
475 |
# source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
|
476 |
-
encodings = tokenizer(" ".join(
|
477 |
truncation=True,
|
478 |
padding="max_length",
|
479 |
max_length=max_length,
|
@@ -518,7 +530,7 @@ def prepare_inference_features(example):
|
|
518 |
"normalized_bboxes": bb_list,
|
519 |
}
|
520 |
|
521 |
-
from torch.utils.data import Dataset
|
522 |
|
523 |
class CustomDataset(Dataset):
|
524 |
def __init__(self, dataset, tokenizer):
|
@@ -537,11 +549,10 @@ class CustomDataset(Dataset):
|
|
537 |
encoding["input_ids"] = example["input_ids"]
|
538 |
encoding["attention_mask"] = example["attention_mask"]
|
539 |
encoding["bbox"] = example["normalized_bboxes"]
|
540 |
-
# encoding["labels"] = example["labels"]
|
541 |
|
542 |
return encoding
|
543 |
-
|
544 |
-
import torch.nn.functional as F
|
545 |
|
546 |
# get predictions at token level
|
547 |
def predictions_token_level(images, custom_encoded_dataset):
|
@@ -550,6 +561,7 @@ def predictions_token_level(images, custom_encoded_dataset):
|
|
550 |
if num_imgs > 0:
|
551 |
|
552 |
chunk_ids, input_ids, bboxes, outputs, token_predictions = dict(), dict(), dict(), dict(), dict()
|
|
|
553 |
images_ids_list = list()
|
554 |
|
555 |
for i,encoding in enumerate(custom_encoded_dataset):
|
@@ -593,7 +605,7 @@ def predictions_token_level(images, custom_encoded_dataset):
|
|
593 |
from functools import reduce
|
594 |
|
595 |
# Get predictions (line level)
|
596 |
-
def
|
597 |
|
598 |
ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
|
599 |
bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
|
@@ -659,7 +671,7 @@ def predictions_line_level(dataset, outputs, images_ids_list, chunk_ids, input_i
|
|
659 |
input_ids_dict[str(bbox)].append(input_id)
|
660 |
probs_dict[str(bbox)].append(probs)
|
661 |
bbox_prev = bbox
|
662 |
-
|
663 |
probs_bbox = dict()
|
664 |
for i,bbox in enumerate(bboxes_list):
|
665 |
probs = probs_dict[str(bbox)]
|
@@ -688,7 +700,7 @@ def predictions_line_level(dataset, outputs, images_ids_list, chunk_ids, input_i
|
|
688 |
print("An error occurred while getting predictions!")
|
689 |
|
690 |
# Get labeled images with lines bounding boxes
|
691 |
-
def
|
692 |
|
693 |
labeled_images = list()
|
694 |
|
@@ -772,7 +784,7 @@ def get_encoded_chunk_inference(index_chunk=None):
|
|
772 |
return image, df, num_tokens, page_no, num_pages
|
773 |
|
774 |
# display chunk of PDF image and its data
|
775 |
-
def
|
776 |
|
777 |
# get image and image data
|
778 |
image, df, num_tokens, page_no, num_pages = get_encoded_chunk_inference(index_chunk=index_chunk)
|
@@ -785,7 +797,7 @@ def display_chunk_lines_inference(index_chunk=None):
|
|
785 |
print(f'Chunk ({num_tokens} tokens) of the PDF (page: {page_no+1} / {num_pages})\n')
|
786 |
|
787 |
# display image with bounding boxes
|
788 |
-
print(">> PDF image with bounding boxes of
|
789 |
draw = ImageDraw.Draw(image)
|
790 |
|
791 |
labels = list()
|
@@ -803,7 +815,7 @@ def display_chunk_lines_inference(index_chunk=None):
|
|
803 |
cv2.waitKey(0)
|
804 |
|
805 |
# display image dataframe
|
806 |
-
print("\n>> Dataframe of annotated
|
807 |
-
cols = ["texts",
|
808 |
df = df[cols]
|
809 |
display(df)
|
|
|
57 |
from transformers import AutoTokenizer, AutoModelForTokenClassification
|
58 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
59 |
|
60 |
+
model_id = "pierreguillou/lilt-xlm-roberta-base-finetuned-DocLayNet-base_paragraphs_ml512"
|
61 |
|
62 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
63 |
model = AutoModelForTokenClassification.from_pretrained(model_id);
|
|
|
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):
|
|
|
380 |
|
381 |
# https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
|
382 |
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
|
383 |
+
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()
|
384 |
+
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()
|
385 |
|
386 |
try:
|
387 |
for i,image in enumerate(images):
|
|
|
393 |
img = np.array(img, dtype='uint8') # convert PIL to cv2
|
394 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
|
395 |
ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
|
396 |
+
|
397 |
# OCR PyTesseract | get langs of page
|
398 |
txt = pytesseract.image_to_string(img, config=custom_config)
|
399 |
txt = txt.strip().lower()
|
400 |
txt = re.sub(r" +", " ", txt) # multiple space
|
401 |
txt = re.sub(r"(\n\s*)+\n+", "\n", txt) # multiple line
|
402 |
# txt = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
|
|
403 |
try:
|
404 |
langs = detect_langs(txt)
|
405 |
langs = [langdetect2Tesseract[langs[i].lang] for i in range(len(langs))]
|
|
|
407 |
except:
|
408 |
langs_string = "eng"
|
409 |
langs_string += '+osd'
|
410 |
+
custom_config = f'--oem 3 --psm 3 -l {langs_string}' # default config PyTesseract: --oem 3 --psm 3
|
|
|
411 |
|
412 |
# OCR PyTesseract | get data
|
413 |
results[i] = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT)
|
414 |
# results[i] = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
|
415 |
|
416 |
+
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)
|
417 |
+
texts_lines_list.append(texts_lines[i])
|
418 |
+
texts_pars_list.append(texts_pars[i])
|
419 |
+
texts_lines_par_list.append(texts_lines_par[i])
|
420 |
par_boxes_list.append(par_boxes[i])
|
421 |
line_boxes_list.append(line_boxes[i])
|
422 |
+
lines_par_boxes_list.append(lines_par_boxes[i])
|
423 |
images_ids_list.append(i)
|
424 |
images_list.append(images[i])
|
425 |
page_no_list.append(i)
|
426 |
+
num_pages_list.append(num_imgs)
|
427 |
|
428 |
except:
|
429 |
print(f"There was an error within the extraction of PDF text by the OCR!")
|
430 |
else:
|
431 |
from datasets import Dataset
|
432 |
+
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})
|
433 |
|
434 |
+
# print(f"The text data was successfully extracted by the OCR!")
|
435 |
|
436 |
+
return dataset, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
|
437 |
|
438 |
## Inference
|
439 |
|
440 |
+
def prepare_inference_features_paragraph(example, cls_box = cls_box, sep_box = sep_box):
|
|
|
441 |
|
442 |
images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list = list(), list(), list(), list(), list()
|
443 |
|
|
|
445 |
# batch_page_hash = example["page_hash"]
|
446 |
batch_images_ids = example["images_ids"]
|
447 |
batch_images = example["images"]
|
448 |
+
batch_bboxes_par = example["bboxes_par"]
|
449 |
+
batch_texts_par = example["texts_par"]
|
450 |
batch_images_size = [image.size for image in batch_images]
|
451 |
|
452 |
batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
|
|
|
455 |
if not isinstance(batch_images_ids, list):
|
456 |
batch_images_ids = [batch_images_ids]
|
457 |
batch_images = [batch_images]
|
458 |
+
batch_bboxes_par = [batch_bboxes_par]
|
459 |
+
batch_texts_par = [batch_texts_par]
|
460 |
batch_width, batch_height = [batch_width], [batch_height]
|
461 |
+
|
462 |
# process all images of the batch
|
463 |
+
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)):
|
464 |
tokens_list = []
|
465 |
bboxes_list = []
|
466 |
|
467 |
# add a dimension if only on image
|
468 |
+
if not isinstance(texts_par, list):
|
469 |
+
texts_par, boxes = [texts_par], [boxes]
|
470 |
|
471 |
# convert boxes to original
|
472 |
+
normalize_bboxes_par = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
|
473 |
|
474 |
# sort boxes with texts
|
475 |
# we want sorted lists from top to bottom of the image
|
476 |
+
boxes, texts_par = sort_data_wo_labels(normalize_bboxes_par, texts_par)
|
477 |
|
478 |
count = 0
|
479 |
+
for box, text_par in zip(boxes, texts_par):
|
480 |
+
tokens_par = tokenizer.tokenize(text_par)
|
481 |
+
num_tokens_par = len(tokens_par) # get number of tokens
|
482 |
+
tokens_list.extend(tokens_par)
|
483 |
+
bboxes_list.extend([box] * num_tokens_par) # number of boxes must be the same as the number of tokens
|
|
|
484 |
|
485 |
# use of return_overflowing_tokens=True / stride=doc_stride
|
486 |
# to get parts of image with overlap
|
487 |
# source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
|
488 |
+
encodings = tokenizer(" ".join(texts_par),
|
489 |
truncation=True,
|
490 |
padding="max_length",
|
491 |
max_length=max_length,
|
|
|
530 |
"normalized_bboxes": bb_list,
|
531 |
}
|
532 |
|
533 |
+
from torch.utils.data import Dataset
|
534 |
|
535 |
class CustomDataset(Dataset):
|
536 |
def __init__(self, dataset, tokenizer):
|
|
|
549 |
encoding["input_ids"] = example["input_ids"]
|
550 |
encoding["attention_mask"] = example["attention_mask"]
|
551 |
encoding["bbox"] = example["normalized_bboxes"]
|
|
|
552 |
|
553 |
return encoding
|
554 |
+
|
555 |
+
import torch.nn.functional as F
|
556 |
|
557 |
# get predictions at token level
|
558 |
def predictions_token_level(images, custom_encoded_dataset):
|
|
|
561 |
if num_imgs > 0:
|
562 |
|
563 |
chunk_ids, input_ids, bboxes, outputs, token_predictions = dict(), dict(), dict(), dict(), dict()
|
564 |
+
normalize_batch_bboxes_lines_pars = dict()
|
565 |
images_ids_list = list()
|
566 |
|
567 |
for i,encoding in enumerate(custom_encoded_dataset):
|
|
|
605 |
from functools import reduce
|
606 |
|
607 |
# Get predictions (line level)
|
608 |
+
def predictions_paragraph_level_gradio(dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes):
|
609 |
|
610 |
ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
|
611 |
bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
|
|
|
671 |
input_ids_dict[str(bbox)].append(input_id)
|
672 |
probs_dict[str(bbox)].append(probs)
|
673 |
bbox_prev = bbox
|
674 |
+
|
675 |
probs_bbox = dict()
|
676 |
for i,bbox in enumerate(bboxes_list):
|
677 |
probs = probs_dict[str(bbox)]
|
|
|
700 |
print("An error occurred while getting predictions!")
|
701 |
|
702 |
# Get labeled images with lines bounding boxes
|
703 |
+
def get_labeled_images_gradio(dataset, images_ids_list, bboxes_list_dict, probs_dict_dict):
|
704 |
|
705 |
labeled_images = list()
|
706 |
|
|
|
784 |
return image, df, num_tokens, page_no, num_pages
|
785 |
|
786 |
# display chunk of PDF image and its data
|
787 |
+
def display_chunk_paragraphs_inference(index_chunk=None):
|
788 |
|
789 |
# get image and image data
|
790 |
image, df, num_tokens, page_no, num_pages = get_encoded_chunk_inference(index_chunk=index_chunk)
|
|
|
797 |
print(f'Chunk ({num_tokens} tokens) of the PDF (page: {page_no+1} / {num_pages})\n')
|
798 |
|
799 |
# display image with bounding boxes
|
800 |
+
print(">> PDF image with bounding boxes of paragraphs\n")
|
801 |
draw = ImageDraw.Draw(image)
|
802 |
|
803 |
labels = list()
|
|
|
815 |
cv2.waitKey(0)
|
816 |
|
817 |
# display image dataframe
|
818 |
+
print("\n>> Dataframe of annotated paragraphs\n")
|
819 |
+
cols = ["texts", "bboxes"]
|
820 |
df = df[cols]
|
821 |
display(df)
|