import os import gradio as gr import re import string from operator import itemgetter import collections import pypdf from pypdf import PdfReader from pypdf.errors import PdfReadError import pypdfium2 as pdfium import langdetect from langdetect import detect_langs import pandas as pd import numpy as np import random import tempfile import itertools from matplotlib import font_manager from PIL import Image, ImageDraw, ImageFont import cv2 ## files import sys sys.path.insert(0, 'files/') import functions from functions import * # update pip os.system('python -m pip install --upgrade pip') # model from transformers import AutoTokenizer, AutoModelForTokenClassification import torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model_id = "pierreguillou/lilt-xlm-roberta-base-finetuned-with-DocLayNet-base-at-paragraphlevel-ml512" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForTokenClassification.from_pretrained(model_id); model.to(device); # APP outputs def app_outputs(uploaded_pdf): filename, msg, images = pdf_to_images(uploaded_pdf) num_images = len(images) if not msg.startswith("Error with the PDF"): # Extraction of image data (text and bounding boxes) dataset, texts_lines, texts_pars, texts_lines_par, row_indexes, par_boxes, line_boxes, lines_par_boxes = extraction_data_from_image(images) print(dataset) # prepare our data in the format of the model encoded_dataset = dataset.map(prepare_inference_features_paragraph, batched=True, batch_size=64, remove_columns=dataset.column_names) custom_encoded_dataset = CustomDataset(encoded_dataset, tokenizer) # Get predictions (token level) outputs, images_ids_list, chunk_ids, input_ids, bboxes = predictions_token_level(images, custom_encoded_dataset) # Get predictions (line level) probs_bbox, bboxes_list_dict, input_ids_dict_dict, probs_dict_dict, df = predictions_paragraph_level_gradio(dataset, outputs, images_ids_list, chunk_ids, input_ids, bboxes) # Get labeled images with lines bounding boxes labeled_images = get_labeled_images_gradio(dataset, images_ids_list, bboxes_list_dict, probs_dict_dict) img_files = list() # get image of PDF with bounding boxes for i in range(num_images): if filename != "files/blank.png": img_file = f"img_{i}_" + filename.replace(".pdf", ".png") else: img_file = filename.replace(".pdf", ".png") img_file = img_file.replace("/", "_") labeled_images[i].save(img_file) img_files.append(img_file) if num_images < max_imgboxes: num_true_images = num_images img_files += [image_blank]*(max_imgboxes - num_images) labeled_images += [Image.open(image_blank)]*(max_imgboxes - num_images) for count in range(max_imgboxes - num_images): df[num_images + count] = pd.DataFrame() else: num_true_images = max_imgboxes img_files = img_files[:max_imgboxes] labeled_images = labeled_images[:max_imgboxes] df = dict(itertools.islice(df.items(), max_imgboxes)) for num_page in range(num_true_images): example = dataset[num_page] df_num_page = df[num_page] width, height = example["images"].size # apply same transformations bboxes_par_list = [denormalize_box(normalize_box(upperleft_to_lowerright(bbox), width, height), width, height) for bbox in example['bboxes_par']] texts_list = list() for bbox_par, label in zip(df_num_page["bboxes"].tolist(), df_num_page["labels"]): index_par = bboxes_par_list.index(bbox_par) bboxes_lines_par_list = dataset[num_page]["bboxes_lines_par"][index_par] texts_lines_par_list = dataset[num_page]["texts_lines_par"][index_par] boxes, texts = sort_data_wo_labels(bboxes_lines_par_list, texts_lines_par_list) # apply text startegy in function of label if label == "Text" or label == "Caption" or label == "Footnote": texts = ' '.join(texts) else: texts = '\n'.join(texts) texts_list.append(texts) df[num_page]["Paragraph text"] = texts_list cols = ["bboxes", "Paragraph text", "labels"] df[num_page] = df[num_page][cols] # save csv_files = list() for i in range(max_imgboxes): csv_file = f"csv_{i}_" + filename.replace(".pdf", ".csv") csv_file = csv_file.replace("/", "_") csv_files.append(gr.File.update(value=csv_file, visible=True)) df[i].to_csv(csv_file, encoding="utf-8", index=False) else: img_files, labeled_images, csv_files = [""]*max_imgboxes, [""]*max_imgboxes, [""]*max_imgboxes img_files[0], img_files[1] = image_blank, image_blank labeled_images[0], labeled_images[1] = Image.open(image_blank), Image.open(image_blank) csv_file = "csv_wo_content.csv" csv_files[0], csv_files[1] = gr.File.update(value=csv_file, visible=True), gr.File.update(value=csv_file, visible=True) df, df_empty = dict(), pd.DataFrame() df[0], df[1] = df_empty.to_csv(csv_file, encoding="utf-8", index=False), df_empty.to_csv(csv_file, encoding="utf-8", index=False) return msg, img_files[0], img_files[1], labeled_images[0], labeled_images[1], csv_files[0], csv_files[1], df[0], df[1] # gradio APP with gr.Blocks(title="Inference APP for Document Understanding at paragraph level (v1 - LiLT base)", css=".gradio-container") as demo: gr.HTML("""
(02/16/2023) This Inference APP uses the model LiLT base combined with XLM-RoBERTa base and finetuned on the dataset DocLayNet base at paragraph level (chunk size of 512 tokens).
LiLT (Language-Independent Layout Transformer) is a Document Understanding model that uses both layout and text in order to detect labels of bounding boxes. Combined with the model XML-RoBERTa base, this finetuned model has the capacity to understand any language. Finetuned on the dataset DocLayNet base, it can classifly any bounding box (and its OCR text) to 11 labels (Caption, Footnote, Formula, List-item, Page-footer, Page-header, Picture, Section-header, Table, Text, Title).
It relies on an external OCR engine to get words and bounding boxes from the document image. Thus, let's run in this APP an OCR engine (PyTesseract) to get the bounding boxes, then run LiLT (already fine-tuned on the dataset DocLayNet base at paragraph level) on the individual tokens and then, visualize the result at paragraph level!
It allows to get all pages of any PDF (of any language) with bounding boxes labeled at paragraph level and the associated dataframes with labeled data (bounding boxes, texts, labels) :-)
However, the inference time per page can be high when running the model on CPU due to the number of paragraph predictions to be made. Therefore, to avoid running this APP for too long, only the first 2 pages are processed by this APP. If you want to increase this limit, you can either clone this APP in Hugging Face Space (or run its notebook on your own plateform) and change the value of the parameter max_imgboxes
, or run the inference notebook "Document AI | Inference at paragraph level with a Document Understanding model (LiLT fine-tuned on DocLayNet dataset)" on your own platform as it does not have this limit.
Links to Document Understanding APPs:
More information about the DocLayNet datasets, the finetuning of the model and this APP in the following blog posts: