pierreguillou commited on
Commit
69136d7
·
1 Parent(s): 4e49717

Update files/functions.py

Browse files
Files changed (1) hide show
  1. files/functions.py +46 -62
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-DocLayNet-base_paragraphs_ml512"
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 get_data_paragraph(results, factor, conf_min=0):
121
 
122
  data = {}
123
  for i in range(len(results['line_num'])):
@@ -160,55 +160,43 @@ def get_data_paragraph(results, factor, conf_min=0):
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):
@@ -337,7 +325,7 @@ def sort_data_wo_labels(bboxes, texts):
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):
@@ -358,7 +346,7 @@ def pdf_to_images(uploaded_pdf):
358
  except PdfReadError:
359
  path_to_file = pdf_blank
360
  filename = path_to_file.replace(examples_dir,"")
361
- msg = "invalid PDF file."
362
  images = [Image.open(image_blank)]
363
  else:
364
  try:
@@ -380,8 +368,8 @@ def extraction_data_from_image(images):
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,7 +381,7 @@ def extraction_data_from_image(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()
@@ -413,40 +401,36 @@ def extraction_data_from_image(images):
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
 
444
- # get batch
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,37 +439,38 @@ def prepare_inference_features_paragraph(example, cls_box = cls_box, sep_box = s
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,7 +515,7 @@ def prepare_inference_features_paragraph(example, cls_box = cls_box, sep_box = s
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):
@@ -552,7 +537,7 @@ class CustomDataset(Dataset):
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,7 +546,6 @@ 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,7 +589,7 @@ def predictions_token_level(images, 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,7 +655,7 @@ def predictions_paragraph_level_gradio(dataset, outputs, images_ids_list, chunk_
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,7 +684,7 @@ def predictions_paragraph_level_gradio(dataset, outputs, images_ids_list, chunk_
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,7 +768,7 @@ def get_encoded_chunk_inference(index_chunk=None):
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,14 +781,14 @@ def display_chunk_paragraphs_inference(index_chunk=None):
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()
804
  for box, text in zip(bboxes, texts):
805
  color = "red"
806
  draw.rectangle(box, outline=color)
807
-
808
  # resize image to original
809
  width, height = image.size
810
  image = image.resize((int(0.5*width), int(0.5*height)))
@@ -815,7 +799,7 @@ def display_chunk_paragraphs_inference(index_chunk=None):
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)
 
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-with-DocLayNet-base-at-linelevel-ml384"
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(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
+ lines = list()
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
+ lines.append(line_text)
 
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
+ par_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
 
 
197
  par_idx += 1
198
 
199
+ return lines, row_indexes, par_boxes, line_boxes #data, par_data #
200
 
201
  # rescale image to get 300dpi
202
  def set_image_dpi_resize(image):
 
325
 
326
  return sorted_bboxes, sorted_texts
327
 
328
+ ## PDF processing
329
 
330
  # get filename and images of PDF pages
331
  def pdf_to_images(uploaded_pdf):
 
346
  except PdfReadError:
347
  path_to_file = pdf_blank
348
  filename = path_to_file.replace(examples_dir,"")
349
+ msg = "Invalid PDF file."
350
  images = [Image.open(image_blank)]
351
  else:
352
  try:
 
368
 
369
  # https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
370
  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
371
+ results, lines, row_indexes, par_boxes, line_boxes = dict(), dict(), dict(), dict(), dict()
372
+ images_ids_list, lines_list, par_boxes_list, line_boxes_list, images_list, page_no_list, num_pages_list = list(), list(), list(), list(), list(), list(), list()
373
 
374
  try:
375
  for i,image in enumerate(images):
 
381
  img = np.array(img, dtype='uint8') # convert PIL to cv2
382
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
383
  ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
384
+
385
  # OCR PyTesseract | get langs of page
386
  txt = pytesseract.image_to_string(img, config=custom_config)
387
  txt = txt.strip().lower()
 
401
  results[i] = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT)
402
  # results[i] = os.popen(f'tesseract {img_filepath} - {custom_config}').read()
403
 
404
+ lines[i], row_indexes[i], par_boxes[i], line_boxes[i] = get_data(results[i], factor, conf_min=0)
405
+ lines_list.append(lines[i])
 
 
406
  par_boxes_list.append(par_boxes[i])
407
  line_boxes_list.append(line_boxes[i])
 
408
  images_ids_list.append(i)
409
  images_list.append(images[i])
410
  page_no_list.append(i)
411
+ num_pages_list.append(num_imgs)
412
 
413
  except:
414
  print(f"There was an error within the extraction of PDF text by the OCR!")
415
  else:
416
  from datasets import Dataset
417
+ dataset = Dataset.from_dict({"images_ids": images_ids_list, "images": images_list, "page_no": page_no_list, "num_pages": num_pages_list, "texts": lines_list, "bboxes_line": line_boxes_list})
418
 
419
  # print(f"The text data was successfully extracted by the OCR!")
420
 
421
+ return dataset, lines, row_indexes, par_boxes, line_boxes
422
 
423
  ## Inference
424
 
425
+ def prepare_inference_features(example, cls_box = cls_box, sep_box = sep_box):
426
 
427
  images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list = list(), list(), list(), list(), list()
428
 
429
+ # get batch
 
430
  batch_images_ids = example["images_ids"]
431
  batch_images = example["images"]
432
+ batch_bboxes_line = example["bboxes_line"]
433
+ batch_texts = example["texts"]
434
  batch_images_size = [image.size for image in batch_images]
435
 
436
  batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
 
439
  if not isinstance(batch_images_ids, list):
440
  batch_images_ids = [batch_images_ids]
441
  batch_images = [batch_images]
442
+ batch_bboxes_line = [batch_bboxes_line]
443
+ batch_texts = [batch_texts]
444
  batch_width, batch_height = [batch_width], [batch_height]
445
 
446
  # process all images of the batch
447
+ for num_batch, (image_id, boxes, texts, width, height) in enumerate(zip(batch_images_ids, batch_bboxes_line, batch_texts, batch_width, batch_height)):
448
  tokens_list = []
449
  bboxes_list = []
450
 
451
  # add a dimension if only on image
452
+ if not isinstance(texts, list):
453
+ texts, boxes = [texts], [boxes]
454
 
455
  # convert boxes to original
456
+ normalize_bboxes_line = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
457
 
458
  # sort boxes with texts
459
  # we want sorted lists from top to bottom of the image
460
+ boxes, texts = sort_data_wo_labels(normalize_bboxes_line, texts)
461
 
462
  count = 0
463
+ for box, text in zip(boxes, texts):
464
+ tokens = tokenizer.tokenize(text)
465
+ num_tokens = len(tokens) # get number of tokens
466
+ tokens_list.extend(tokens)
467
+
468
+ bboxes_list.extend([box] * num_tokens) # number of boxes must be the same as the number of tokens
469
 
470
  # use of return_overflowing_tokens=True / stride=doc_stride
471
  # to get parts of image with overlap
472
  # source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
473
+ encodings = tokenizer(" ".join(texts),
474
  truncation=True,
475
  padding="max_length",
476
  max_length=max_length,
 
515
  "normalized_bboxes": bb_list,
516
  }
517
 
518
+ from torch.utils.data import Dataset
519
 
520
  class CustomDataset(Dataset):
521
  def __init__(self, dataset, tokenizer):
 
537
 
538
  return encoding
539
 
540
+ import torch.nn.functional as F
541
 
542
  # get predictions at token level
543
  def predictions_token_level(images, custom_encoded_dataset):
 
546
  if num_imgs > 0:
547
 
548
  chunk_ids, input_ids, bboxes, outputs, token_predictions = dict(), dict(), dict(), dict(), dict()
 
549
  images_ids_list = list()
550
 
551
  for i,encoding in enumerate(custom_encoded_dataset):
 
589
  from functools import reduce
590
 
591
  # Get predictions (line level)
592
+ def predictions_line_level(dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes):
593
 
594
  ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
595
  bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
 
655
  input_ids_dict[str(bbox)].append(input_id)
656
  probs_dict[str(bbox)].append(probs)
657
  bbox_prev = bbox
658
+
659
  probs_bbox = dict()
660
  for i,bbox in enumerate(bboxes_list):
661
  probs = probs_dict[str(bbox)]
 
684
  print("An error occurred while getting predictions!")
685
 
686
  # Get labeled images with lines bounding boxes
687
+ def get_labeled_images(dataset, images_ids_list, bboxes_list_dict, probs_dict_dict):
688
 
689
  labeled_images = list()
690
 
 
768
  return image, df, num_tokens, page_no, num_pages
769
 
770
  # display chunk of PDF image and its data
771
+ def display_chunk_lines_inference(index_chunk=None):
772
 
773
  # get image and image data
774
  image, df, num_tokens, page_no, num_pages = get_encoded_chunk_inference(index_chunk=index_chunk)
 
781
  print(f'Chunk ({num_tokens} tokens) of the PDF (page: {page_no+1} / {num_pages})\n')
782
 
783
  # display image with bounding boxes
784
+ print(">> PDF image with bounding boxes of lines\n")
785
  draw = ImageDraw.Draw(image)
786
 
787
  labels = list()
788
  for box, text in zip(bboxes, texts):
789
  color = "red"
790
  draw.rectangle(box, outline=color)
791
+
792
  # resize image to original
793
  width, height = image.size
794
  image = image.resize((int(0.5*width), int(0.5*height)))
 
799
  cv2.waitKey(0)
800
 
801
  # display image dataframe
802
+ print("\n>> Dataframe of annotated lines\n")
803
+ cols = ["texts", "bboxes"]
804
  df = df[cols]
805
+ display(df)