pierreguillou commited on
Commit
b24b127
1 Parent(s): 0b0cce3

Update files/functions.py

Browse files
Files changed (1) hide show
  1. files/functions.py +57 -45
files/functions.py CHANGED
@@ -98,7 +98,7 @@ from huggingface_hub import hf_hub_download
98
  files = ["example.pdf", "blank.pdf", "blank.png", "languages_iso.csv", "languages_tesseract.csv", "wo_content.png"]
99
  for file_name in files:
100
  path_to_file = hf_hub_download(
101
- repo_id = "pierreguillou/Inference-APP-Document-Understanding-at-linelevel-v2",
102
  filename = "files/" + file_name,
103
  repo_type = "space"
104
  )
@@ -140,10 +140,7 @@ langdetect2Tesseract = {v:k for k,v in Tesseract2langdetect.items()}
140
  import torch
141
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
142
 
143
- # model
144
- from transformers import LayoutLMv2ForTokenClassification
145
-
146
- model_id = "pierreguillou/layout-xlm-base-finetuned-with-DocLayNet-base-at-linelevel-ml384"
147
 
148
  model = LayoutLMv2ForTokenClassification.from_pretrained(model_id);
149
  model.to(device);
@@ -154,7 +151,6 @@ feature_extractor = LayoutLMv2FeatureExtractor(apply_ocr=False)
154
 
155
  # tokenizer
156
  from transformers import AutoTokenizer
157
- tokenizer_id = "xlm-roberta-base"
158
  tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
159
 
160
  # get labels
@@ -167,7 +163,7 @@ num_labels = len(id2label)
167
  # get text and bounding boxes from an image
168
  # https://stackoverflow.com/questions/61347755/how-can-i-get-line-coordinates-that-readed-by-tesseract
169
  # https://medium.com/geekculture/tesseract-ocr-understanding-the-contents-of-documents-beyond-their-text-a98704b7c655
170
- def get_data(results, factor, conf_min=0):
171
 
172
  data = {}
173
  for i in range(len(results['line_num'])):
@@ -210,43 +206,55 @@ def get_data(results, factor, conf_min=0):
210
  par_idx += 1
211
 
212
  # get lines of texts, grouped by paragraph
213
- lines = list()
214
  row_indexes = list()
 
 
215
  row_index = 0
216
  for _,par in par_data.items():
217
  count_lines = 0
 
218
  for _,line in par.items():
219
  if count_lines == 0: row_indexes.append(row_index)
220
  line_text = ' '.join([item[0] for item in line])
221
- lines.append(line_text)
 
222
  count_lines += 1
223
  row_index += 1
224
  # lines.append("\n")
225
  row_index += 1
 
 
226
  # lines = lines[:-1]
227
 
228
  # get paragraphes boxes (par_boxes)
229
  # get lines boxes (line_boxes)
230
  par_boxes = list()
231
  par_idx = 1
232
- line_boxes = list()
233
  line_idx = 1
234
  for _, par in par_data.items():
235
  xmins, ymins, xmaxs, ymaxs = list(), list(), list(), list()
 
 
236
  for _, line in par.items():
237
  xmin, ymin = line[0][1], line[0][2]
238
  xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
239
  line_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
 
240
  xmins.append(xmin)
241
  ymins.append(ymin)
242
  xmaxs.append(xmax)
243
  ymaxs.append(ymax)
244
  line_idx += 1
 
245
  xmin, ymin, xmax, ymax = min(xmins), min(ymins), max(xmaxs), max(ymaxs)
246
- par_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
 
 
247
  par_idx += 1
248
 
249
- return lines, row_indexes, par_boxes, line_boxes #data, par_data #
250
 
251
  # rescale image to get 300dpi
252
  def set_image_dpi_resize(image):
@@ -375,7 +383,7 @@ def sort_data_wo_labels(bboxes, texts):
375
  sorted_texts = np.array(texts, dtype=object)[sorted_bboxes_indexes].tolist()
376
 
377
  return sorted_bboxes, sorted_texts
378
-
379
  ## PDF processing
380
 
381
  # get filename and images of PDF pages
@@ -419,8 +427,8 @@ def extraction_data_from_image(images):
419
 
420
  # https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
421
  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
422
- results, lines, row_indexes, par_boxes, line_boxes, images_pixels = dict(), dict(), dict(), dict(), dict(), dict()
423
- images_ids_list, lines_list, par_boxes_list, line_boxes_list, images_list, images_pixels_list, page_no_list, num_pages_list = list(), list(), list(), list(), list(), list(), list(), list()
424
 
425
  try:
426
  for i,image in enumerate(images):
@@ -432,7 +440,7 @@ def extraction_data_from_image(images):
432
  img = np.array(img, dtype='uint8') # convert PIL to cv2
433
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
434
  ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
435
-
436
  # OCR PyTesseract | get langs of page
437
  txt = pytesseract.image_to_string(img, config=custom_config)
438
  txt = txt.strip().lower()
@@ -455,38 +463,43 @@ def extraction_data_from_image(images):
455
  # get image pixels
456
  images_pixels[i] = feature_extractor(images[i], return_tensors="pt").pixel_values
457
 
458
- lines[i], row_indexes[i], par_boxes[i], line_boxes[i] = get_data(results[i], factor, conf_min=0)
459
- lines_list.append(lines[i])
 
 
460
  par_boxes_list.append(par_boxes[i])
461
  line_boxes_list.append(line_boxes[i])
 
462
  images_ids_list.append(i)
463
  images_pixels_list.append(images_pixels[i])
464
  images_list.append(images[i])
465
  page_no_list.append(i)
466
- num_pages_list.append(num_imgs)
467
 
468
  except:
469
  print(f"There was an error within the extraction of PDF text by the OCR!")
470
  else:
471
  from datasets import Dataset
472
- 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": lines_list, "bboxes_line": line_boxes_list})
473
 
 
474
  # print(f"The text data was successfully extracted by the OCR!")
475
 
476
- return dataset, lines, row_indexes, par_boxes, line_boxes
477
 
478
  ## Inference
479
 
480
- def prepare_inference_features(example, cls_box = cls_box, sep_box = sep_box):
481
 
482
  images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list, images_pixels_list = list(), list(), list(), list(), list(), list()
483
 
484
- # get batch
 
485
  batch_images_ids = example["images_ids"]
486
  batch_images = example["images"]
487
  batch_images_pixels = example["images_pixels"]
488
- batch_bboxes_line = example["bboxes_line"]
489
- batch_texts = example["texts"]
490
  batch_images_size = [image.size for image in batch_images]
491
 
492
  batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
@@ -496,38 +509,37 @@ def prepare_inference_features(example, cls_box = cls_box, sep_box = sep_box):
496
  batch_images_ids = [batch_images_ids]
497
  batch_images = [batch_images]
498
  batch_images_pixels = [batch_images_pixels]
499
- batch_bboxes_line = [batch_bboxes_line]
500
- batch_texts = [batch_texts]
501
  batch_width, batch_height = [batch_width], [batch_height]
502
 
503
  # process all images of the batch
504
- for num_batch, (image_id, image_pixels, boxes, texts, width, height) in enumerate(zip(batch_images_ids, batch_images_pixels, batch_bboxes_line, batch_texts, batch_width, batch_height)):
505
  tokens_list = []
506
  bboxes_list = []
507
 
508
  # add a dimension if only on image
509
- if not isinstance(texts, list):
510
- texts, boxes = [texts], [boxes]
511
 
512
  # convert boxes to original
513
- normalize_bboxes_line = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
514
 
515
  # sort boxes with texts
516
  # we want sorted lists from top to bottom of the image
517
- boxes, texts = sort_data_wo_labels(normalize_bboxes_line, texts)
518
 
519
  count = 0
520
- for box, text in zip(boxes, texts):
521
- tokens = tokenizer.tokenize(text)
522
- num_tokens = len(tokens) # get number of tokens
523
- tokens_list.extend(tokens)
524
-
525
- bboxes_list.extend([box] * num_tokens) # number of boxes must be the same as the number of tokens
526
 
527
  # use of return_overflowing_tokens=True / stride=doc_stride
528
  # to get parts of image with overlap
529
  # source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
530
- encodings = tokenizer(" ".join(texts),
531
  truncation=True,
532
  padding="max_length",
533
  max_length=max_length,
@@ -654,7 +666,7 @@ def predictions_token_level(images, custom_encoded_dataset):
654
  from functools import reduce
655
 
656
  # Get predictions (line level)
657
- def predictions_line_level(dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes):
658
 
659
  ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
660
  bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
@@ -719,7 +731,7 @@ def predictions_line_level(dataset, outputs, images_ids_list, chunk_ids, input_i
719
  input_ids_dict[str(bbox)].append(input_id)
720
  probs_dict[str(bbox)].append(probs)
721
  bbox_prev = bbox
722
-
723
  probs_bbox = dict()
724
  for i,bbox in enumerate(bboxes_list):
725
  probs = probs_dict[str(bbox)]
@@ -832,7 +844,7 @@ def get_encoded_chunk_inference(index_chunk=None):
832
  return image, df, num_tokens, page_no, num_pages
833
 
834
  # display chunk of PDF image and its data
835
- def display_chunk_lines_inference(index_chunk=None):
836
 
837
  # get image and image data
838
  image, df, num_tokens, page_no, num_pages = get_encoded_chunk_inference(index_chunk=index_chunk)
@@ -845,14 +857,14 @@ def display_chunk_lines_inference(index_chunk=None):
845
  print(f'Chunk ({num_tokens} tokens) of the PDF (page: {page_no+1} / {num_pages})\n')
846
 
847
  # display image with bounding boxes
848
- print(">> PDF image with bounding boxes of lines\n")
849
  draw = ImageDraw.Draw(image)
850
 
851
  labels = list()
852
  for box, text in zip(bboxes, texts):
853
  color = "red"
854
  draw.rectangle(box, outline=color)
855
-
856
  # resize image to original
857
  width, height = image.size
858
  image = image.resize((int(0.5*width), int(0.5*height)))
@@ -863,7 +875,7 @@ def display_chunk_lines_inference(index_chunk=None):
863
  cv2.waitKey(0)
864
 
865
  # display image dataframe
866
- print("\n>> Dataframe of annotated lines\n")
867
  cols = ["texts", "bboxes"]
868
  df = df[cols]
869
  display(df)
 
98
  files = ["example.pdf", "blank.pdf", "blank.png", "languages_iso.csv", "languages_tesseract.csv", "wo_content.png"]
99
  for file_name in files:
100
  path_to_file = hf_hub_download(
101
+ repo_id = "pierreguillou/Inference-APP-Document-Understanding-at-paragraphlevel-v2",
102
  filename = "files/" + file_name,
103
  repo_type = "space"
104
  )
 
140
  import torch
141
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
142
 
143
+ from transformers import LayoutLMv2ForTokenClassification # LayoutXLMTokenizerFast,
 
 
 
144
 
145
  model = LayoutLMv2ForTokenClassification.from_pretrained(model_id);
146
  model.to(device);
 
151
 
152
  # tokenizer
153
  from transformers import AutoTokenizer
 
154
  tokenizer = AutoTokenizer.from_pretrained(tokenizer_id)
155
 
156
  # get labels
 
163
  # get text and bounding boxes from an image
164
  # https://stackoverflow.com/questions/61347755/how-can-i-get-line-coordinates-that-readed-by-tesseract
165
  # https://medium.com/geekculture/tesseract-ocr-understanding-the-contents-of-documents-beyond-their-text-a98704b7c655
166
+ def get_data_paragraph(results, factor, conf_min=0):
167
 
168
  data = {}
169
  for i in range(len(results['line_num'])):
 
206
  par_idx += 1
207
 
208
  # get lines of texts, grouped by paragraph
209
+ texts_pars = list()
210
  row_indexes = list()
211
+ texts_lines = list()
212
+ texts_lines_par = list()
213
  row_index = 0
214
  for _,par in par_data.items():
215
  count_lines = 0
216
+ lines_par = list()
217
  for _,line in par.items():
218
  if count_lines == 0: row_indexes.append(row_index)
219
  line_text = ' '.join([item[0] for item in line])
220
+ texts_lines.append(line_text)
221
+ lines_par.append(line_text)
222
  count_lines += 1
223
  row_index += 1
224
  # lines.append("\n")
225
  row_index += 1
226
+ texts_lines_par.append(lines_par)
227
+ texts_pars.append(' '.join(lines_par))
228
  # lines = lines[:-1]
229
 
230
  # get paragraphes boxes (par_boxes)
231
  # get lines boxes (line_boxes)
232
  par_boxes = list()
233
  par_idx = 1
234
+ line_boxes, lines_par_boxes = list(), list()
235
  line_idx = 1
236
  for _, par in par_data.items():
237
  xmins, ymins, xmaxs, ymaxs = list(), list(), list(), list()
238
+ line_boxes_par = list()
239
+ count_line_par = 0
240
  for _, line in par.items():
241
  xmin, ymin = line[0][1], line[0][2]
242
  xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
243
  line_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
244
+ line_boxes_par.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
245
  xmins.append(xmin)
246
  ymins.append(ymin)
247
  xmaxs.append(xmax)
248
  ymaxs.append(ymax)
249
  line_idx += 1
250
+ count_line_par += 1
251
  xmin, ymin, xmax, ymax = min(xmins), min(ymins), max(xmaxs), max(ymaxs)
252
+ par_bbox = [int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)]
253
+ par_boxes.append(par_bbox)
254
+ lines_par_boxes.append(line_boxes_par)
255
  par_idx += 1
256
 
257
+ return texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
258
 
259
  # rescale image to get 300dpi
260
  def set_image_dpi_resize(image):
 
383
  sorted_texts = np.array(texts, dtype=object)[sorted_bboxes_indexes].tolist()
384
 
385
  return sorted_bboxes, sorted_texts
386
+
387
  ## PDF processing
388
 
389
  # get filename and images of PDF pages
 
427
 
428
  # https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
429
  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
430
+ 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()
431
+ 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()
432
 
433
  try:
434
  for i,image in enumerate(images):
 
440
  img = np.array(img, dtype='uint8') # convert PIL to cv2
441
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
442
  ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
443
+
444
  # OCR PyTesseract | get langs of page
445
  txt = pytesseract.image_to_string(img, config=custom_config)
446
  txt = txt.strip().lower()
 
463
  # get image pixels
464
  images_pixels[i] = feature_extractor(images[i], return_tensors="pt").pixel_values
465
 
466
+ 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)
467
+ texts_lines_list.append(texts_lines[i])
468
+ texts_pars_list.append(texts_pars[i])
469
+ texts_lines_par_list.append(texts_lines_par[i])
470
  par_boxes_list.append(par_boxes[i])
471
  line_boxes_list.append(line_boxes[i])
472
+ lines_par_boxes_list.append(lines_par_boxes[i])
473
  images_ids_list.append(i)
474
  images_pixels_list.append(images_pixels[i])
475
  images_list.append(images[i])
476
  page_no_list.append(i)
477
+ num_pages_list.append(num_imgs)
478
 
479
  except:
480
  print(f"There was an error within the extraction of PDF text by the OCR!")
481
  else:
482
  from datasets import Dataset
483
+ 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})
484
 
485
+
486
  # print(f"The text data was successfully extracted by the OCR!")
487
 
488
+ return dataset, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
489
 
490
  ## Inference
491
 
492
+ def prepare_inference_features_paragraph(example, cls_box = cls_box, sep_box = sep_box):
493
 
494
  images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list, images_pixels_list = list(), list(), list(), list(), list(), list()
495
 
496
+ # get batch
497
+ # batch_page_hash = example["page_hash"]
498
  batch_images_ids = example["images_ids"]
499
  batch_images = example["images"]
500
  batch_images_pixels = example["images_pixels"]
501
+ batch_bboxes_par = example["bboxes_par"]
502
+ batch_texts_par = example["texts_par"]
503
  batch_images_size = [image.size for image in batch_images]
504
 
505
  batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
 
509
  batch_images_ids = [batch_images_ids]
510
  batch_images = [batch_images]
511
  batch_images_pixels = [batch_images_pixels]
512
+ batch_bboxes_par = [batch_bboxes_par]
513
+ batch_texts_par = [batch_texts_par]
514
  batch_width, batch_height = [batch_width], [batch_height]
515
 
516
  # process all images of the batch
517
+ 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)):
518
  tokens_list = []
519
  bboxes_list = []
520
 
521
  # add a dimension if only on image
522
+ if not isinstance(texts_par, list):
523
+ texts_par, boxes = [texts_par], [boxes]
524
 
525
  # convert boxes to original
526
+ normalize_bboxes_par = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
527
 
528
  # sort boxes with texts
529
  # we want sorted lists from top to bottom of the image
530
+ boxes, texts_par = sort_data_wo_labels(normalize_bboxes_par, texts_par)
531
 
532
  count = 0
533
+ for box, text_par in zip(boxes, texts_par):
534
+ tokens_par = tokenizer.tokenize(text_par)
535
+ num_tokens_par = len(tokens_par) # get number of tokens
536
+ tokens_list.extend(tokens_par)
537
+ bboxes_list.extend([box] * num_tokens_par) # number of boxes must be the same as the number of tokens
 
538
 
539
  # use of return_overflowing_tokens=True / stride=doc_stride
540
  # to get parts of image with overlap
541
  # source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
542
+ encodings = tokenizer(" ".join(texts_par),
543
  truncation=True,
544
  padding="max_length",
545
  max_length=max_length,
 
666
  from functools import reduce
667
 
668
  # Get predictions (line level)
669
+ def predictions_paragraph_level(dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes):
670
 
671
  ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
672
  bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
 
731
  input_ids_dict[str(bbox)].append(input_id)
732
  probs_dict[str(bbox)].append(probs)
733
  bbox_prev = bbox
734
+
735
  probs_bbox = dict()
736
  for i,bbox in enumerate(bboxes_list):
737
  probs = probs_dict[str(bbox)]
 
844
  return image, df, num_tokens, page_no, num_pages
845
 
846
  # display chunk of PDF image and its data
847
+ def display_chunk_paragraphs_inference(index_chunk=None):
848
 
849
  # get image and image data
850
  image, df, num_tokens, page_no, num_pages = get_encoded_chunk_inference(index_chunk=index_chunk)
 
857
  print(f'Chunk ({num_tokens} tokens) of the PDF (page: {page_no+1} / {num_pages})\n')
858
 
859
  # display image with bounding boxes
860
+ print(">> PDF image with bounding boxes of paragraphs\n")
861
  draw = ImageDraw.Draw(image)
862
 
863
  labels = list()
864
  for box, text in zip(bboxes, texts):
865
  color = "red"
866
  draw.rectangle(box, outline=color)
867
+
868
  # resize image to original
869
  width, height = image.size
870
  image = image.resize((int(0.5*width), int(0.5*height)))
 
875
  cv2.waitKey(0)
876
 
877
  # display image dataframe
878
+ print("\n>> Dataframe of annotated paragraphs\n")
879
  cols = ["texts", "bboxes"]
880
  df = df[cols]
881
  display(df)