pierreguillou commited on
Commit
2afcefd
·
1 Parent(s): c144ca3

Update files/functions.py

Browse files
Files changed (1) hide show
  1. files/functions.py +58 -74
files/functions.py CHANGED
@@ -75,8 +75,8 @@ sep_box_lilt = cls_box
75
  sep_box_layoutxlm = [1000, 1000, 1000, 1000]
76
 
77
  # models
78
- model_id_lilt = "pierreguillou/lilt-xlm-roberta-base-finetuned-with-DocLayNet-base-at-linelevel-ml384"
79
- model_id_layoutxlm = "pierreguillou/layout-xlm-base-finetuned-with-DocLayNet-base-at-linelevel-ml384"
80
 
81
  # tokenizer for LayoutXLM
82
  tokenizer_id_layoutxlm = "xlm-roberta-base"
@@ -109,7 +109,7 @@ from huggingface_hub import hf_hub_download
109
  files = ["example.pdf", "blank.pdf", "blank.png", "languages_iso.csv", "languages_tesseract.csv", "wo_content.png"]
110
  for file_name in files:
111
  path_to_file = hf_hub_download(
112
- repo_id = "pierreguillou/Inference-APP-Document-Understanding-at-linelevel-LiLT-base-LayoutXLM-base-v1",
113
  filename = "files/" + file_name,
114
  repo_type = "space"
115
  )
@@ -146,47 +146,13 @@ for lang_t, langcode_t in zip(langs_t,langscode_t):
146
 
147
  langdetect2Tesseract = {v:k for k,v in Tesseract2langdetect.items()}
148
 
149
- ## model / feature extractor / tokenizer
150
 
151
- # get device
152
- import torch
153
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
154
-
155
- ## model LiLT
156
- import transformers
157
- from transformers import AutoTokenizer, AutoModelForTokenClassification
158
- tokenizer_lilt = AutoTokenizer.from_pretrained(model_id_lilt)
159
- model_lilt = AutoModelForTokenClassification.from_pretrained(model_id_lilt);
160
- model_lilt.to(device);
161
-
162
- ## model LayoutXLM
163
- from transformers import LayoutLMv2ForTokenClassification # LayoutXLMTokenizerFast,
164
- model_layoutxlm = LayoutLMv2ForTokenClassification.from_pretrained(model_id_layoutxlm);
165
- model_layoutxlm.to(device);
166
-
167
- # feature extractor
168
- from transformers import LayoutLMv2FeatureExtractor
169
- feature_extractor = LayoutLMv2FeatureExtractor(apply_ocr=False)
170
-
171
- # tokenizer
172
- from transformers import AutoTokenizer
173
- tokenizer_layoutxlm = AutoTokenizer.from_pretrained(tokenizer_id_layoutxlm)
174
-
175
- # get labels
176
- id2label_lilt = model_lilt.config.id2label
177
- label2id_lilt = model_lilt.config.label2id
178
- num_labels_lilt = len(id2label_lilt)
179
-
180
- id2label_layoutxlm = model_layoutxlm.config.id2label
181
- label2id_layoutxlm = model_layoutxlm.config.label2id
182
- num_labels_layoutxlm = len(id2label_layoutxlm)
183
-
184
- ## General
185
 
186
  # get text and bounding boxes from an image
187
  # https://stackoverflow.com/questions/61347755/how-can-i-get-line-coordinates-that-readed-by-tesseract
188
  # https://medium.com/geekculture/tesseract-ocr-understanding-the-contents-of-documents-beyond-their-text-a98704b7c655
189
- def get_data(results, factor, conf_min=0):
190
 
191
  data = {}
192
  for i in range(len(results['line_num'])):
@@ -229,43 +195,55 @@ def get_data(results, factor, conf_min=0):
229
  par_idx += 1
230
 
231
  # get lines of texts, grouped by paragraph
232
- lines = list()
233
  row_indexes = list()
 
 
234
  row_index = 0
235
  for _,par in par_data.items():
236
  count_lines = 0
 
237
  for _,line in par.items():
238
  if count_lines == 0: row_indexes.append(row_index)
239
  line_text = ' '.join([item[0] for item in line])
240
- lines.append(line_text)
 
241
  count_lines += 1
242
  row_index += 1
243
  # lines.append("\n")
244
  row_index += 1
 
 
245
  # lines = lines[:-1]
246
 
247
  # get paragraphes boxes (par_boxes)
248
  # get lines boxes (line_boxes)
249
  par_boxes = list()
250
  par_idx = 1
251
- line_boxes = list()
252
  line_idx = 1
253
  for _, par in par_data.items():
254
  xmins, ymins, xmaxs, ymaxs = list(), list(), list(), list()
 
 
255
  for _, line in par.items():
256
  xmin, ymin = line[0][1], line[0][2]
257
  xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
258
  line_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
 
259
  xmins.append(xmin)
260
  ymins.append(ymin)
261
  xmaxs.append(xmax)
262
  ymaxs.append(ymax)
263
  line_idx += 1
 
264
  xmin, ymin, xmax, ymax = min(xmins), min(ymins), max(xmaxs), max(ymaxs)
265
- par_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
 
 
266
  par_idx += 1
267
 
268
- return lines, row_indexes, par_boxes, line_boxes #data, par_data #
269
 
270
  # rescale image to get 300dpi
271
  def set_image_dpi_resize(image):
@@ -395,7 +373,8 @@ def sort_data_wo_labels(bboxes, texts):
395
 
396
  return sorted_bboxes, sorted_texts
397
 
398
- ## PDF processing
 
399
 
400
  # get filename and images of PDF pages
401
  def pdf_to_images(uploaded_pdf):
@@ -438,8 +417,8 @@ def extraction_data_from_image(images):
438
 
439
  # https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
440
  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
441
- results, lines, row_indexes, par_boxes, line_boxes, images_pixels = dict(), dict(), dict(), dict(), dict(), dict()
442
- 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()
443
 
444
  try:
445
  for i,image in enumerate(images):
@@ -451,7 +430,7 @@ def extraction_data_from_image(images):
451
  img = np.array(img, dtype='uint8') # convert PIL to cv2
452
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
453
  ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
454
-
455
  # OCR PyTesseract | get langs of page
456
  txt = pytesseract.image_to_string(img, config=custom_config)
457
  txt = txt.strip().lower()
@@ -474,38 +453,44 @@ def extraction_data_from_image(images):
474
  # get image pixels
475
  images_pixels[i] = feature_extractor(images[i], return_tensors="pt").pixel_values
476
 
477
- lines[i], row_indexes[i], par_boxes[i], line_boxes[i] = get_data(results[i], factor, conf_min=0)
478
- lines_list.append(lines[i])
 
 
479
  par_boxes_list.append(par_boxes[i])
480
  line_boxes_list.append(line_boxes[i])
 
481
  images_ids_list.append(i)
482
  images_pixels_list.append(images_pixels[i])
483
  images_list.append(images[i])
484
  page_no_list.append(i)
485
- num_pages_list.append(num_imgs)
486
 
487
  except:
488
  print(f"There was an error within the extraction of PDF text by the OCR!")
489
  else:
490
  from datasets import Dataset
491
- 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})
492
 
 
493
  # print(f"The text data was successfully extracted by the OCR!")
494
 
495
- return dataset, lines, row_indexes, par_boxes, line_boxes
496
 
497
- ## Inference
 
498
 
499
- def prepare_inference_features(example, tokenizer, max_length, cls_box, sep_box):
500
 
501
  images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list, images_pixels_list = list(), list(), list(), list(), list(), list()
502
 
503
- # get batch
 
504
  batch_images_ids = example["images_ids"]
505
  batch_images = example["images"]
506
  batch_images_pixels = example["images_pixels"]
507
- batch_bboxes_line = example["bboxes_line"]
508
- batch_texts = example["texts"]
509
  batch_images_size = [image.size for image in batch_images]
510
 
511
  batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
@@ -515,38 +500,37 @@ def prepare_inference_features(example, tokenizer, max_length, cls_box, sep_box)
515
  batch_images_ids = [batch_images_ids]
516
  batch_images = [batch_images]
517
  batch_images_pixels = [batch_images_pixels]
518
- batch_bboxes_line = [batch_bboxes_line]
519
- batch_texts = [batch_texts]
520
  batch_width, batch_height = [batch_width], [batch_height]
521
 
522
  # process all images of the batch
523
- 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)):
524
  tokens_list = []
525
  bboxes_list = []
526
 
527
  # add a dimension if only on image
528
- if not isinstance(texts, list):
529
- texts, boxes = [texts], [boxes]
530
 
531
  # convert boxes to original
532
- normalize_bboxes_line = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
533
 
534
  # sort boxes with texts
535
  # we want sorted lists from top to bottom of the image
536
- boxes, texts = sort_data_wo_labels(normalize_bboxes_line, texts)
537
 
538
  count = 0
539
- for box, text in zip(boxes, texts):
540
- tokens = tokenizer.tokenize(text)
541
- num_tokens = len(tokens) # get number of tokens
542
- tokens_list.extend(tokens)
543
-
544
- bboxes_list.extend([box] * num_tokens) # number of boxes must be the same as the number of tokens
545
 
546
  # use of return_overflowing_tokens=True / stride=doc_stride
547
  # to get parts of image with overlap
548
  # source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
549
- encodings = tokenizer(" ".join(texts),
550
  truncation=True,
551
  padding="max_length",
552
  max_length=max_length,
@@ -681,7 +665,7 @@ def predictions_token_level(images, custom_encoded_dataset, model_id, model):
681
  from functools import reduce
682
 
683
  # Get predictions (line level)
684
- def predictions_line_level(max_length, tokenizer, id2label, dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes, cls_box, sep_box):
685
 
686
  ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
687
  bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
@@ -746,7 +730,7 @@ def predictions_line_level(max_length, tokenizer, id2label, dataset, outputs, im
746
  input_ids_dict[str(bbox)].append(input_id)
747
  probs_dict[str(bbox)].append(probs)
748
  bbox_prev = bbox
749
-
750
  probs_bbox = dict()
751
  for i,bbox in enumerate(bboxes_list):
752
  probs = probs_dict[str(bbox)]
 
75
  sep_box_layoutxlm = [1000, 1000, 1000, 1000]
76
 
77
  # models
78
+ model_id_lilt = "pierreguillou/lilt-xlm-roberta-base-finetuned-with-DocLayNet-base-at-paragraphlevel-ml512"
79
+ model_id_layoutxlm = "pierreguillou/layout-xlm-base-finetuned-with-DocLayNet-base-at-paragraphlevel-ml512"
80
 
81
  # tokenizer for LayoutXLM
82
  tokenizer_id_layoutxlm = "xlm-roberta-base"
 
109
  files = ["example.pdf", "blank.pdf", "blank.png", "languages_iso.csv", "languages_tesseract.csv", "wo_content.png"]
110
  for file_name in files:
111
  path_to_file = hf_hub_download(
112
+ repo_id = "pierreguillou/Inference-APP-Document-Understanding-at-paragraphlevel-LiLT-base-LayoutXLM-base-v1",
113
  filename = "files/" + file_name,
114
  repo_type = "space"
115
  )
 
146
 
147
  langdetect2Tesseract = {v:k for k,v in Tesseract2langdetect.items()}
148
 
 
149
 
150
+ # General
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  # get text and bounding boxes from an image
153
  # https://stackoverflow.com/questions/61347755/how-can-i-get-line-coordinates-that-readed-by-tesseract
154
  # https://medium.com/geekculture/tesseract-ocr-understanding-the-contents-of-documents-beyond-their-text-a98704b7c655
155
+ def get_data_paragraph(results, factor, conf_min=0):
156
 
157
  data = {}
158
  for i in range(len(results['line_num'])):
 
195
  par_idx += 1
196
 
197
  # get lines of texts, grouped by paragraph
198
+ texts_pars = list()
199
  row_indexes = list()
200
+ texts_lines = list()
201
+ texts_lines_par = list()
202
  row_index = 0
203
  for _,par in par_data.items():
204
  count_lines = 0
205
+ lines_par = list()
206
  for _,line in par.items():
207
  if count_lines == 0: row_indexes.append(row_index)
208
  line_text = ' '.join([item[0] for item in line])
209
+ texts_lines.append(line_text)
210
+ lines_par.append(line_text)
211
  count_lines += 1
212
  row_index += 1
213
  # lines.append("\n")
214
  row_index += 1
215
+ texts_lines_par.append(lines_par)
216
+ texts_pars.append(' '.join(lines_par))
217
  # lines = lines[:-1]
218
 
219
  # get paragraphes boxes (par_boxes)
220
  # get lines boxes (line_boxes)
221
  par_boxes = list()
222
  par_idx = 1
223
+ line_boxes, lines_par_boxes = list(), list()
224
  line_idx = 1
225
  for _, par in par_data.items():
226
  xmins, ymins, xmaxs, ymaxs = list(), list(), list(), list()
227
+ line_boxes_par = list()
228
+ count_line_par = 0
229
  for _, line in par.items():
230
  xmin, ymin = line[0][1], line[0][2]
231
  xmax, ymax = (line[-1][1] + line[-1][3]), (line[-1][2] + line[-1][4])
232
  line_boxes.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
233
+ line_boxes_par.append([int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)])
234
  xmins.append(xmin)
235
  ymins.append(ymin)
236
  xmaxs.append(xmax)
237
  ymaxs.append(ymax)
238
  line_idx += 1
239
+ count_line_par += 1
240
  xmin, ymin, xmax, ymax = min(xmins), min(ymins), max(xmaxs), max(ymaxs)
241
+ par_bbox = [int(xmin/factor), int(ymin/factor), int(xmax/factor), int(ymax/factor)]
242
+ par_boxes.append(par_bbox)
243
+ lines_par_boxes.append(line_boxes_par)
244
  par_idx += 1
245
 
246
+ return texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
247
 
248
  # rescale image to get 300dpi
249
  def set_image_dpi_resize(image):
 
373
 
374
  return sorted_bboxes, sorted_texts
375
 
376
+
377
+ # PDF processing
378
 
379
  # get filename and images of PDF pages
380
  def pdf_to_images(uploaded_pdf):
 
417
 
418
  # https://pyimagesearch.com/2021/11/15/tesseract-page-segmentation-modes-psms-explained-how-to-improve-your-ocr-accuracy/
419
  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
420
+ 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()
421
+ 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()
422
 
423
  try:
424
  for i,image in enumerate(images):
 
430
  img = np.array(img, dtype='uint8') # convert PIL to cv2
431
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray scale image
432
  ret,img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
433
+
434
  # OCR PyTesseract | get langs of page
435
  txt = pytesseract.image_to_string(img, config=custom_config)
436
  txt = txt.strip().lower()
 
453
  # get image pixels
454
  images_pixels[i] = feature_extractor(images[i], return_tensors="pt").pixel_values
455
 
456
+ 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)
457
+ texts_lines_list.append(texts_lines[i])
458
+ texts_pars_list.append(texts_pars[i])
459
+ texts_lines_par_list.append(texts_lines_par[i])
460
  par_boxes_list.append(par_boxes[i])
461
  line_boxes_list.append(line_boxes[i])
462
+ lines_par_boxes_list.append(lines_par_boxes[i])
463
  images_ids_list.append(i)
464
  images_pixels_list.append(images_pixels[i])
465
  images_list.append(images[i])
466
  page_no_list.append(i)
467
+ num_pages_list.append(num_imgs)
468
 
469
  except:
470
  print(f"There was an error within the extraction of PDF text by the OCR!")
471
  else:
472
  from datasets import Dataset
473
+ 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})
474
 
475
+
476
  # print(f"The text data was successfully extracted by the OCR!")
477
 
478
+ return dataset, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes
479
 
480
+
481
+ # Inference
482
 
483
+ def prepare_inference_features_paragraph(example, tokenizer, max_length, cls_box, sep_box):
484
 
485
  images_ids_list, chunks_ids_list, input_ids_list, attention_mask_list, bb_list, images_pixels_list = list(), list(), list(), list(), list(), list()
486
 
487
+ # get batch
488
+ # batch_page_hash = example["page_hash"]
489
  batch_images_ids = example["images_ids"]
490
  batch_images = example["images"]
491
  batch_images_pixels = example["images_pixels"]
492
+ batch_bboxes_par = example["bboxes_par"]
493
+ batch_texts_par = example["texts_par"]
494
  batch_images_size = [image.size for image in batch_images]
495
 
496
  batch_width, batch_height = [image_size[0] for image_size in batch_images_size], [image_size[1] for image_size in batch_images_size]
 
500
  batch_images_ids = [batch_images_ids]
501
  batch_images = [batch_images]
502
  batch_images_pixels = [batch_images_pixels]
503
+ batch_bboxes_par = [batch_bboxes_par]
504
+ batch_texts_par = [batch_texts_par]
505
  batch_width, batch_height = [batch_width], [batch_height]
506
 
507
  # process all images of the batch
508
+ 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)):
509
  tokens_list = []
510
  bboxes_list = []
511
 
512
  # add a dimension if only on image
513
+ if not isinstance(texts_par, list):
514
+ texts_par, boxes = [texts_par], [boxes]
515
 
516
  # convert boxes to original
517
+ normalize_bboxes_par = [normalize_box(upperleft_to_lowerright(box), width, height) for box in boxes]
518
 
519
  # sort boxes with texts
520
  # we want sorted lists from top to bottom of the image
521
+ boxes, texts_par = sort_data_wo_labels(normalize_bboxes_par, texts_par)
522
 
523
  count = 0
524
+ for box, text_par in zip(boxes, texts_par):
525
+ tokens_par = tokenizer.tokenize(text_par)
526
+ num_tokens_par = len(tokens_par) # get number of tokens
527
+ tokens_list.extend(tokens_par)
528
+ bboxes_list.extend([box] * num_tokens_par) # number of boxes must be the same as the number of tokens
 
529
 
530
  # use of return_overflowing_tokens=True / stride=doc_stride
531
  # to get parts of image with overlap
532
  # source: https://huggingface.co/course/chapter6/3b?fw=tf#handling-long-contexts
533
+ encodings = tokenizer(" ".join(texts_par),
534
  truncation=True,
535
  padding="max_length",
536
  max_length=max_length,
 
665
  from functools import reduce
666
 
667
  # Get predictions (line level)
668
+ def predictions_paragraph_level(max_length, tokenizer, id2label, dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes, cls_box, sep_box):
669
 
670
  ten_probs_dict, ten_input_ids_dict, ten_bboxes_dict = dict(), dict(), dict()
671
  bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = dict(), dict(), dict(), dict()
 
730
  input_ids_dict[str(bbox)].append(input_id)
731
  probs_dict[str(bbox)].append(probs)
732
  bbox_prev = bbox
733
+
734
  probs_bbox = dict()
735
  for i,bbox in enumerate(bboxes_list):
736
  probs = probs_dict[str(bbox)]