DEV Community

Alain Airom
Alain Airom

Posted on

Maximize Your Documents: Exploring the Advantages of Full OCR of PDF files and chat with your documents!

A reflection on benfits of full text OCRization and how it becomes handy with LLM enables applications.

Image description

What is the benefit of a Full Text OCRization of a PDF file?

Full Optical Character Recognition (OCR) of a document like a PDF offers a wide range of benefits, transforming static, image-based files into dynamic, searchable, and editable content.

Here are the key advantages:

  • Searchability: This is arguably the most significant benefit. Without OCR, a scanned PDF is essentially just an image, and you can’t search for specific words or phrases within it. Full OCR converts the image of text into actual, machine-readable text, allowing you to easily search for keywords, names, dates, or any other information. This is incredibly useful for large documents, archives, and research.
  • Editability: Once OCR is applied, the text within the PDF becomes editable. This means you can correct errors, update information, copy and paste content into other applications (like Microsoft Word or Excel), and make changes without having to retype the entire document.
  • Increased Accessibility: OCR makes documents accessible to a wider audience, including those with visual impairments. Screen readers and other assistive technologies can read the recognized text aloud, providing an auditory experience of the document’s content.

Improved Efficiency and Productivity:

  • Automated Data Entry: OCR drastically reduces or eliminates the need for manual data entry, saving countless hours and reducing human errors. This is particularly valuable for processing invoices, forms, and other structured documents.
  • Faster Information Retrieval: With searchable documents, employees can quickly find the information they need, leading to faster response times and improved workflows.
  • Streamlined Document Management: OCR enables better organization and categorization of documents. Extracted text can be used to tag and index files, making it easier to manage large document repositories.
  • Cost Reduction: By automating tasks like data entry and reducing the need for physical storage, OCR can lead to significant cost savings in terms of labor, printing, and storage space.
  • Enhanced Data Accuracy: While not 100% perfect, modern OCR technology (especially with AI and machine learning advancements) offers a high degree of accuracy. It can also include features like built-in validation tools to flag potential inconsistencies.
  • Better Data Security and Disaster Recovery: Digitized documents stored electronically with OCR are less prone to physical damage, loss, or misplacement. They can also be secured with access controls and easily backed up for disaster recovery purposes.
  • Integration with Other Systems: OCR-processed documents can be easily integrated with other business systems, such as CRM, ERP, or accounting software, allowing for seamless data flow and automation of various processes.

In essence, full OCR transforms static, often unwieldy, image-based documents into dynamic, intelligent assets that can be easily managed, processed, and utilized across various applications and workflows.

Combintaion with LLM enabled applications

Full OCR (Optical Character Recognition) is not just beneficial but often essential for LLM (Large Language Model) enabled applications, particularly when dealing with real-world documents that aren’t natively digital or structured. Here’s how:

Bridging the Gap: Image to Text:

  • LLMs are very good with text: The fundamental truth is that LLMs are trained on vast amounts of text data. They can’t “see” or directly interpret images of documents.
  • OCR provides the input: Full OCR’s primary role here is to convert images of text (from scanned PDFs, photos, faxes, etc.) into machine-readable, searchable text. This digitized text is the raw material that an LLM can then process. Without OCR, these documents are invisible to an LLM.
    Enhanced Contextual Understanding:

  • Beyond simple recognition: While traditional OCR focuses on character recognition, modern OCR, especially LLM-powered OCR or systems that integrate LLMs, goes further. They can understand document layouts, identify headings, paragraphs, tables, and even key-value pairs.

  • Richer input for LLMs: This “layout-aware” OCR provides the LLM with not just the text, but also its structural context. An LLM can then leverage this information to:

  • Extract more accurate information: Differentiate between a total amount in a table versus a random number in the body text.

  • Understand relationships: Connect a name to an address or a product to its price within a complex document like an invoice.

  • Reason about the document: An LLM can be prompted to “summarize the key findings from Section 3” or “extract all line items from the invoice,” tasks that require understanding both the text and its organization.
    Improved Accuracy and Error Correction:

  • LLMs as post-OCR correction: Even the best OCR isn’t 100% perfect, especially with poor-quality scans or handwritten text. LLMs, with their strong language understanding, can act as a powerful post-processing layer.

  • Contextual fixing: If OCR misinterprets “10” as “1O,” an LLM, given the surrounding words, can often infer the correct interpretation. This significantly reduces character error rates (CER).

  • Handling variability: LLMs are more robust to variations in fonts, layouts, and even handwriting than traditional, rule-based OCR systems.
    Enabling Advanced Document Intelligence:

  • Summarization: Once a document is fully OCR’d and its text is available, an LLM can quickly generate concise summaries of lengthy contracts, reports, or legal briefs.

  • Question Answering (Q&A): Users can ask natural language questions about the content of a document (e.g., “What is the termination clause in this contract?” or “What was the total amount due on this invoice?”), and the LLM, having processed the OCR’d text, can provide direct answers.

  • Classification and Categorization: LLMs can classify documents based on their content (e.g., “This is an invoice,” “This is a resume,” “This is a legal agreement”) for automated routing and organization.

  • Sentiment Analysis: Analyze the tone of customer feedback forms or emails after they’ve been digitized by OCR.

  • Data Extraction & Structuring: This is a huge area. LLMs, especially when combined with advanced OCR that understands document structure, can extract specific data points (e.g., invoice numbers, dates, names, addresses) and present them in structured formats like JSON, making them ready for databases or other business applications.

  • Compliance and Risk Assessment: For legal or financial documents, an LLM can analyze OCR’d text to identify specific clauses, terms, or risks, automating compliance checks.
    Scalability and Automation:

  • High-volume processing: OCR and LLMs together allow for the automated processing of vast quantities of documents that would otherwise require tedious manual review. This is critical for businesses dealing with archives, customer onboarding, or supply chain management.

  • Integration with workflows: The structured data extracted by OCR and refined by LLMs can be seamlessly fed into CRM, ERP, accounting, or document management systems, enabling end-to-end automation.

In essence, full OCR transforms unstructured, visual data (documents) into structured, linguistic data that LLMs can then “read,” “understand,” and “reason” about. This synergy unlocks a vast array of intelligent applications, from automated data entry and advanced search to sophisticated content analysis and decision-making.

Making benefice of document OCRisation features to enrich users’ knowledge through natural language queries

In a recent project, to assist a customer in building an end-to-end solution using a Retrieval Augmented Generation (RAG) system, specifically leveraging Milvus provided by watsonx.data, and by implementing a chat assistant using watsonx Orchestrate, I developed a local sample application to demonstrate the core concept. The central idea behind this application is to transform source PDF files into ingestible Markdown document formats, embed these Markdown documents into a Milvus vector database, and then enable interactive chat with the content of these documents using the Granite Large Language Model.

In order to do the OCRization, I used (as always ☺️) Docling which is the most performant open-source solution on the internet!

Image description

So to make a recap all tools I used locally;

  • Milvus for RAG,
  • Podman as container engine (for Milvus),
  • Docling for OCR,
  • Ollama for local LLM inferencing,
  • Granite 3.3 8b as the LLM.

The steps to build and test

  • Install and launch Milvus;
# downloads the script to fetch and run the image locally
curl -sfL https://raw.githubusercontent.com/milvus-io/milvus/master/scripts/standalone_embed.sh 

# make these subfloders
mkdir volumes/milvus

# to start your local Milvus DB
bash ./standalone_embed.sh start
Enter fullscreen mode Exit fullscreen mode
  • Prepare your local environment;
python3 -m venv venv
source venv/bin/activate

pip install --upgrade pip

pip install docling
pip install --upgrade pymilvus
pip install sentence-transformers
Enter fullscreen mode Exit fullscreen mode
  • Test your Milvus setup is up and running;
from pymilvus import connections

try:
    connections.connect(host="127.0.0.1", port="19530")
    print("Milvus connection successful!")
    connections.disconnect("default")
except Exception as e:
    print(f"Milvus connection failed: {e}")
Enter fullscreen mode Exit fullscreen mode
  • Using Ollama and Granite, verify that the model is downloaded;
ollama list
#####
NAME                        ID              SIZE      MODIFIED    
tinyllama:latest            2644915ede35    637 MB    2 days ago     
mistral:latest              3944fe81ec14    4.1 GB    12 days ago    
granite3.3:latest           fd429f23b909    4.9 GB    3 weeks ago    
granite3-dense:latest       5c2e6f3112f4    1.6 GB    4 weeks ago    
granite3.2-vision:latest    3be41a661804    2.4 GB    7 weeks ago    
granite3.2:latest   
Enter fullscreen mode Exit fullscreen mode
  • Implement the first application which populates your RAG. The logic is that the code fetches all files in the “/data/input” folder and generates markdown files in the output folder. Then the markdown files are embedded into the Milvus database and are marked as processed so that until they are not modified they won’t be processed again.
from pathlib import Path
import os
import uuid # For generating unique IDs for Milvus
import json # For saving/loading processed file metadata
import time # For getting file modification times

# --- Docling Library Imports ---
try:
    from docling.datamodel.base_models import InputFormat
    from docling.datamodel.pipeline_options import (
        PdfPipelineOptions,
        TesseractCliOcrOptions,
    )
    from docling.document_converter import DocumentConverter, PdfFormatOption
except ImportError:
    print("Error: 'docling' library not found.")
    print("Please install it using: pip install docling")
    exit()

# --- Milvus Library Imports ---
try:
    from pymilvus import connections, Collection, FieldSchema, CollectionSchema, DataType, utility # Added utility
except ImportError:
    print("Error: 'pymilvus' library not found.")
    print("Please install it using: pip install pymilvus")
    exit()

# --- Sentence Transformer Import for Embeddings ---
try:
    from sentence_transformers import SentenceTransformer
except ImportError:
    print("Error: 'sentence-transformers' library not found.")
    print("Please install it using: pip install sentence-transformers")
    exit()

# --- Configuration for Milvus ---
MILVUS_HOST = "localhost"
MILVUS_PORT = "19530"
COLLECTION_NAME = "ocr_documents"
VECTOR_DIM = 384  # Dimension of the embeddings from 'all-MiniLM-L6-v2' model

# --- Configuration for File Processing ---
# Directory to recursively scan for PDF files
INPUT_DIR = Path(__file__).parent / "data" / "pdf"
# Directory to save processed Markdown files
OUTPUT_MD_DIR = Path(__file__).parent / "output_markdown"
# File to store metadata about processed PDFs
PROCESSED_FILES_DB = Path(__file__).parent / "processed_files.json"

# --- Load Sentence Embedding Model ---
print("Loading sentence embedding model...")
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
print("Sentence embedding model loaded.")

def load_processed_files_db():
    """Loads the database of processed files from a JSON file."""
    if PROCESSED_FILES_DB.exists():
        with open(PROCESSED_FILES_DB, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {}

def save_processed_files_db(db):
    """Saves the database of processed files to a JSON file."""
    with open(PROCESSED_FILES_DB, 'w', encoding='utf-8') as f:
        json.dump(db, f, indent=4)

def create_milvus_collection():
    """
    Connects to Milvus and creates a collection if it doesn't exist.
    """
    print(f"Connecting to Milvus at {MILVUS_HOST}:{MILVUS_PORT}...")
    try:
        connections.connect(host=MILVUS_HOST, port=MILVUS_PORT)
        print("Connected to Milvus.")
    except Exception as e:
        print(f"Failed to connect to Milvus: {e}")
        print("Please ensure your Milvus instance is running.")
        exit()

    # Define the fields for the collection
    fields = [
        FieldSchema(name="pk", dtype=DataType.VARCHAR, is_primary=True, auto_id=False, max_length=100),
        FieldSchema(name="file_name", dtype=DataType.VARCHAR, max_length=256),
        FieldSchema(name="full_path", dtype=DataType.VARCHAR, max_length=512), # Store full path for easier tracking
        FieldSchema(name="last_modified", dtype=DataType.INT64), # Store timestamp for updates
        FieldSchema(name="text_content", dtype=DataType.VARCHAR, max_length=65535), # Max length for VARCHAR
        FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=VECTOR_DIM)
    ]

    # Define the collection schema
    schema = CollectionSchema(fields, "Collection for OCR'd documents and their embeddings")

    # Check if collection exists and get it, otherwise create it
    # CORRECTED: Use utility.has_collection() to check for collection existence
    if utility.has_collection(COLLECTION_NAME):
        print(f"Collection '{COLLECTION_NAME}' already exists.")
        collection = Collection(COLLECTION_NAME)
    else:
        print(f"Creating collection '{COLLECTION_NAME}'...")
        collection = Collection(COLLECTION_NAME, schema)
        print(f"Collection '{COLLECTION_NAME}' created.")

        # Create an index for the vector field for efficient similarity search
        index_params = {
            "metric_type": "L2",  # Euclidean distance
            "index_type": "IVF_FLAT",
            "params": {"nlist": 128}
        }
        print("Creating index for the embedding field...")
        collection.create_index(
            field_name="embedding",
            index_params=index_params
        )
        print("Index created.")

    # Load the collection into memory for search operations
    print(f"Loading collection '{COLLECTION_NAME}' into memory...")
    collection.load()
    print(f"Collection '{COLLECTION_NAME}' loaded.")

    return collection

def process_pdf_document(pdf_path, converter, milvus_collection, processed_db):
    """
    Processes a single PDF document: OCR, Markdown export, embedding, and Milvus insertion.
    """
    relative_pdf_path = str(pdf_path.relative_to(Path(__file__).parent))
    last_modified_timestamp = int(pdf_path.stat().st_mtime)

    # Check if the file has been processed and if it's updated
    if relative_pdf_path in processed_db:
        stored_timestamp = processed_db[relative_pdf_path]['last_modified']
        if last_modified_timestamp <= stored_timestamp:
            print(f"Skipping '{pdf_path.name}': Already processed and not updated.")
            return

    print(f"\nProcessing document: {pdf_path.name}")
    print(f"Full path: {pdf_path}")

    # --- Setup Output Directory for Markdown ---
    # Ensure the output directory for markdown exists
    OUTPUT_MD_DIR.mkdir(parents=True, exist_ok=True)
    output_md_path = OUTPUT_MD_DIR / f"{pdf_path.stem}.md"
    print(f"Output Markdown will be saved to: {output_md_path}")

    md_content = ""
    try:
        print("Converting document and performing OCR/table detection...")
        doc = converter.convert(pdf_path).document
        md_content = doc.export_to_markdown()
        print("Conversion complete.")

        with open(output_md_path, "w", encoding="utf-8") as f:
            f.write(md_content)
        print(f"Successfully saved Markdown output to: {output_md_path}")

    except Exception as e:
        print(f"An error occurred during document processing for '{pdf_path.name}': {e}")
        print("Please ensure 'docling' is correctly configured and Tesseract (if used) is installed.")
        return # Skip Milvus if docling fails

    # --- Milvus Integration ---
    try:
        # Generate embedding for the Markdown content
        print("Generating embedding for the Markdown content...")
        if not md_content.strip():
            print("Warning: Markdown content is empty. Skipping Milvus insertion.")
            return

        embedding = embedding_model.encode(md_content).tolist()
        print("Embedding generated.")

        # Prepare data for insertion
        # Using a unique ID for each document version
        entity_id = f"{pdf_path.stem}_{str(uuid.uuid4())[:8]}"
        data = [
            [entity_id],
            [pdf_path.name],
            [str(pdf_path)], # Store the full absolute path
            [last_modified_timestamp],
            [md_content],
            [embedding]
        ]

        # Insert data into Milvus
        print(f"Inserting data into Milvus collection '{COLLECTION_NAME}'...")
        insert_result = milvus_collection.insert(data)
        print(f"Data inserted successfully. Inserted ID: {insert_result.primary_keys[0]}")

        # Update the processed files database
        processed_db[relative_pdf_path] = {
            'last_modified': last_modified_timestamp,
            'milvus_pk': entity_id
        }
        save_processed_files_db(processed_db)
        print(f"Updated processing status for '{pdf_path.name}'.")

    except Exception as e:
        print(f"An error occurred during Milvus operations for '{pdf_path.name}': {e}")
        print("Please ensure Milvus is running and configured correctly.")


def main():
    # Load the processed files database
    processed_db = load_processed_files_db()
    print(f"Loaded processed files DB: {len(processed_db)} entries.")

    # Initialize Docling converter once
    pipeline_options = PdfPipelineOptions()
    pipeline_options.do_ocr = True
    pipeline_options.do_table_structure = True
    pipeline_options.table_structure_options.do_cell_matching = True
    ocr_options = TesseractCliOcrOptions(force_full_page_ocr=True)
    pipeline_options.ocr_options = ocr_options

    converter = DocumentConverter(
        format_options={
            InputFormat.PDF: PdfFormatOption(
                pipeline_options=pipeline_options,
            )
        }
    )

    # Connect to Milvus and get the collection
    milvus_collection = create_milvus_collection()

    # Ensure the input directory exists
    if not INPUT_DIR.exists():
        print(f"Error: Input directory '{INPUT_DIR}' not found.")
        print("Please create this directory and place your PDF files inside.")
        return

    # Recursively find all PDF files in the input directory
    pdf_files = list(INPUT_DIR.rglob('*.pdf'))

    if not pdf_files:
        print(f"No PDF files found in '{INPUT_DIR}' or its subdirectories.")
        return

    print(f"Found {len(pdf_files)} PDF files to check.")

    for pdf_path in pdf_files:
        process_pdf_document(pdf_path, converter, milvus_collection, processed_db)

    print("\nAll eligible PDF documents processed.")

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Image description

  • The result of this sample app (based on sample provided by Docling is);
## DocLayNet: A Large Human-Annotated Dataset for Document-Layout Analysis

Birgit Pfitzmann IBM Research Rueschlikon, Switzerland bpf@zurich.ibm.com

Christoph Auer IBM Research Rueschlikon, Switzerland cau@zurich.ibm.com

Michele Dolfi IBM Research Rueschlikon, Switzerland dol@zurich.ibm.com

Ahmed S. Nassar IBM Research Rueschlikon, Switzerland ahn@zurich.ibm.com

Peter Staar IBM Research Rueschlikon, Switzerland taa@zurich.ibm.com

## ABSTRACT

Accurate document layout analysis is a key requirement for highquality PDF document conversion. With the recent availability of public, large ground-truth datasets such as PubLayNet and DocBank, deep-learning models have proven to be very effective at layout detection and segmentation. While these datasets are of adequate size to train such models, they severely lack in layout variability since they are sourced from scientific article repositories such as PubMed and arXiv only. Consequently, the accuracy of the layout segmentation drops significantly when these models are applied on more challenging and diverse layouts. In this paper, we present DocLayNet, a new, publicly available, document-layout annotation dataset in COCO format. It contains 80863 manually annotated pages from diverse data sources to represent a wide variability in layouts. For each PDF page, the layout annotations provide labelled bounding-boxes with a choice of 11 distinct classes. DocLayNet also provides a subset of doubleand triple-annotated pages to determine the inter-annotator agreement. In multiple experiments, we provide baseline accuracy scores (in mAP) for a set of popular object detection models. We also demonstrate that these models fall approximately 10% behind the inter-annotator agreement. Furthermore, we provide evidence that DocLayNet is of sufficient size. Lastly, we compare models trained on PubLayNet, DocBank and DocLayNet, showing that layout predictions of the DocLayNettrained models are more robust and thus the preferred choice for general-purpose document-layout analysis.

## CCS CONCEPTS

+ Information systems — Document structure; -Applied computing — Document analysis; -Computing methodologies — Machine learning; Computer vision; Object detection;

Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for third-party components of this work must be honored. For all other uses, contact the owner/author(s).

KDD

°22,

August

14-18,

2022,

Washington,

DC,

USA

©

2022

Copyright held

by the

owner/author(s).

ACM

ISBN

978-1-4503-9385-0/22/08.

https://doi.org/10.1145/3534678.3539043

Figure 1: Four examples of complex page layouts across different document categories

<!-- image -->

## KEYWORDS

PDF document conversion, layout segmentation, object-detection, data set, Machine Learning

## ACM Reference Format:

Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar. 2022. DocLayNet: A Large Human-Annotated Dataset for DocumentLayout Analysis. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD '22), August 14-18, 2022, Washington, DC, USA. ACM, New York, NY, USA, 9 pages. https://doi.org/10.1145/ 3534678.3539043

## 1 INTRODUCTION

Despite the substantial improvements achieved with machine-learning (ML) approaches and deep neural networks in recent years, document conversion remains a challenging problem, as demonstrated by the numerous public competitions held on this topic [1-4]. The challenge originates from the huge variability in PDF documents regarding layout, language and formats (scanned, programmatic or a combination of both). Engineering a single ML model that can be applied on all types of documents and provides high-quality layout segmentation remains to this day extremely challenging [5]. To highlight the variability in document layouts, we show a few example documents from the DocLayNet dataset in Figure 1.

A key problem in the process of document conversion is to understand the structure of a single document page, i.e. which segments of text should be grouped together in a unit. To train models for this task, there are currently two large datasets available to the community, PubLayNet [6] and DocBank [7]. They were introduced in 2019 and 2020 respectively and significantly accelerated the implementation of layout detection and segmentation models due to their sizes of 300K and 500K ground-truth pages. These sizes were achieved by leveraging an automation approach. The benefit of automated ground-truth generation is obvious: one can generate large ground-truth datasets at virtually no cost. However, the automation introduces a constraint on the variability in the dataset, because corresponding structured source data must be available. PubLayNet and DocBank were both generated from scientific document repositories (PubMed and arXiv), which provide XML or TEX sources. Those scientific documents present a limited variability in their layouts, because they are typeset in uniform templates provided by the publishers. Obviously, documents such as technical manuals, annual company reports, legal text, government tenders, etc. have very different and partially unique layouts. As a consequence, the layout predictions obtained from models trained on PubLayNet or DocBank is very reasonable when applied on scientific documents. However, for more artistic or free-style layouts, we see sub-par prediction quality from these models, which we demonstrate in Section 5.

In this paper, we present the DocLayNet dataset. It provides pageby-page layout annotation ground-truth using bounding-boxes for 11 distinct class labels on 80863 unique document pages, of which a fraction carry doubleor triple-annotations. DocLayNet is similar in spirit to PubLayNet and DocBank and will likewise be made available to the public! in order to stimulate the document-layout analysis community. It distinguishes itself in the following aspects:

- (1) Human Annotation: In contrast to PubLayNet and DocBank, we relied on human annotation instead of automation approaches to generate the data set.
- (2) Large Layout Variability: We include diverse and complex layouts from a large variety of public sources.
- (3) Detailed Label Set: We define 11 class labels to distinguish layout features in high detail. PubLayNet provides 5 labels; DocBank provides 13, although not a superset of ours.
- (4) Redundant Annotations: A fraction of the pages in the DocLayNet data set carry more than one human annotation.

'https://developer.ibm.com/exchanges/data/all/doclaynet

This enables experimentation with annotation uncertainty and quality control analysis.

- (5) Pre-defined Train-, Test-&amp; Validation-set: Like DocBank, we provide fixed train-, test-&amp; validation-sets to ensure proportional representation of the class-labels. Further, we prevent leakage of unique layouts across sets, which has a large effect on model accuracy scores.

All aspects outlined above are detailed in Section 3. In Section 4, we will elaborate on how we designed and executed this large-scale human annotation campaign. We will also share key insights and lessons learned that might prove helpful for other parties planning to set up annotation campaigns.

In Section 5, we will present baseline accuracy numbers for a variety of object detection methods (Faster R-CNN, Mask R-CNN and YOLOv5) trained on DocLayNet. We further show how the model performance is impacted by varying the DocLayNet dataset size, reducing the label set and modifying the train/test-split. Last but not least, we compare the performance of models trained on PubLayNet, DocBank and DocLayNet and demonstrate that a model trained on DocLayNet provides overall more robust layout recovery.

## 2 RELATED WORK

While early approaches in document-layout analysis used rulebased algorithms and heuristics [8], the problem is lately addressed with deep learning methods. The most common approach is to leverage object detection models [9-15]. In the last decade, the accuracy and speed of these models has increased dramatically. Furthermore, most state-of-the-art object detection methods can be trained and applied with very little work, thanks to a standardisation effort of the ground-truth data format [16] and common deep-learning frameworks [17]. Reference data sets such as PubLayNet [6] and DocBank provide their data in the commonly accepted COCO format [16].

Lately, new types of ML models for document-layout analysis have emerged in the community [18-21]. These models do not approach the problem of layout analysis purely based on an image representation of the page, as computer vision methods do. Instead, they combine the text tokens and image representation of a page in order to obtain a segmentation. While the reported accuracies appear to be promising, a broadly accepted data format which links geometric and textual features has yet to establish.

## 3. THE DOCLAYNET DATASET

DocLayNet contains 80863 PDF pages. Among these, 7059 carry two instances of human annotations, and 1591 carry three. This amounts to 91104 total annotation instances. The annotations provide layout information in the shape of labeled, rectangular boundingboxes. We define 11 distinct labels for layout features, namely Caption, Footnote, Formula, List-item, Page-footer, Page-header, Picture, Section-header, Table, Text, and Title. Our reasoning for picking this particular label set is detailed in Section 4.

In addition to open intellectual property constraints for the source documents, we required that the documents in DocLayNet adhere to a few conditions. Firstly, we kept scanned documents

Figure 2: Distribution of DocLayNet pages across document categories.

<!-- image -->

to a minimum, since they introduce difficulties in annotation (see Section 4). As a second condition, we focussed on medium to large documents (&gt; 10 pages) with technical content, dense in complex tables, figures, plots and captions. Such documents carry a lot of information value, but are often hard to analyse with high accuracy due to their challenging layouts. Counterexamples of documents not included in the dataset are receipts, invoices, hand-written documents or photographs showing "text in the wild".

The pages in DocLayNet can be grouped into six distinct categories, namely Financial Reports, Manuals, Scientific Articles, Laws &amp; Regulations, Patents and Government Tenders. Each document category was sourced from various repositories. For example, Financial Reports contain both free-style format annual reports? which expose company-specific, artistic layouts as well as the more formal SEC filings. The two largest categories (Financial Reports and Manuals) contain a large amount of free-style layouts in order to obtain maximum variability. In the other four categories, we boosted the variability by mixing documents from independent providers, such as different government websites or publishers. In Figure 2, we show the document categories contained in DocLayNet with their respective sizes.

We did not control the document selection with regard to language. The vast majority of documents contained in DocLayNet (close to 95%) are published in English language. However, DocLayNet also contains a number of documents in other languages such as German (2.5%), French (1.0%) and Japanese (1.0%). While the document language has negligible impact on the performance of computer vision methods such as object detection and segmentation models, it might prove challenging for layout analysis methods which exploit textual features.

To ensure that future benchmarks in the document-layout analysis community can be easily compared, we have split up DocLayNet into pre-defined train-, testand validation-sets. In this way, we can avoid spurious variations in the evaluation scores due to random splitting in train-, testand validation-sets. We also ensured that less frequent labels are represented in train and test sets in equal proportions.

2e¢. AAPL from https://www.annualreports.com/

Table 1 shows the overall frequency and distribution of the labels among the different sets. Importantly, we ensure that subsets are only split on full-document boundaries. This avoids that pages of the same document are spread over train, test and validation set, which can give an undesired evaluation advantage to models and lead to overestimation of their prediction accuracy. We will show the impact of this decision in Section 5.

In order to accommodate the different types of models currently in use by the community, we provide DocLayNet in an augmented COCO format [16]. This entails the standard COCO ground-truth file (in JSON format) with the associated page images (in PNG format, 1025x1025 pixels). Furthermore, custom fields have been added to each COCO record to specify document category, original document filename and page number. In addition, we also provide the original PDF pages, as well as sidecar files containing parsed PDF text and text-cell coordinates (in JSON). All additional files are linked to the primary page images by their matching filenames.

Despite being cost-intense and far less scalable than automation, human annotation has several benefits over automated groundtruth generation. The first and most obvious reason to leverage human annotations is the freedom to annotate any type of document without requiring a programmatic source. For most PDF documents, the original source document is not available. The latter is not a hard constraint with human annotation, but it is for automated methods. A second reason to use human annotations is that the latter usually provide a more natural interpretation of the page layout. The human-interpreted layout can significantly deviate from the programmatic layout used in typesetting. For example, "invisible" tables might be used solely for aligning text paragraphs on columns. Such typesetting tricks might be interpreted by automated methods incorrectly as an actual table, while the human annotation will interpret it correctly as Text or other styles. The same applies to multi-line text elements, when authors decided to space them as "invisible" list elements without bullet symbols. A third reason to gather ground-truth through human annotation is to estimate a "natural" upper bound on the segmentation accuracy. As we will show in Section 4, certain documents featuring complex layouts can have different but equally acceptable layout interpretations. This natural upper bound for segmentation accuracy can be found by annotating the same pages multiple times by different people and evaluating the inter-annotator agreement. Such a baseline consistency evaluation is very useful to define expectations for a good target accuracy in trained deep neural network models and avoid overfitting (see Table 1). On the flip side, achieving high annotation consistency proved to be a key challenge in human annotation, as we outline in Section 4.

## 4 ANNOTATION CAMPAIGN

The annotation campaign was carried out in four phases. In phase one, we identified and prepared the data sources for annotation. In phase two, we determined the class labels and how annotations should be done on the documents in order to obtain maximum consistency. The latter was guided by a detailed requirement analysis and exhaustive experiments. In phase three, we trained the annotation staff and performed exams for quality assurance. In phase four,

Table 1: DocLayNet dataset overview. Along with the frequency of each class label, we present the relative occurrence (as % of row "Total") in the train, test and validation sets. The inter-annotator agreement is computed as the mAP@0.5-0.95 metric between pairwise annotations from the triple-annotated pages, from which we obtain accuracy ranges.

|                |         | % of Total   | % of Total   | % of Total   | triple inter-annotator mAP @0.5-0.95 (%)   | triple inter-annotator mAP @0.5-0.95 (%)   | triple inter-annotator mAP @0.5-0.95 (%)   | triple inter-annotator mAP @0.5-0.95 (%)   | triple inter-annotator mAP @0.5-0.95 (%)   | triple inter-annotator mAP @0.5-0.95 (%)   | triple inter-annotator mAP @0.5-0.95 (%)   |
|----------------|---------|--------------|--------------|--------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|
| class label    | Count   | Train        | Test         | Val          | All                                        | Fin                                        | Man                                        | Sci                                        | Law                                        | Pat                                        | Ten                                        |
| Caption        | 22524   | 2.04         | 1.77         | 2.32         | 84-89                                      | 40-61                                      | 86-92                                      | 94-99                                      | 95-99                                      | 69-78                                      | n/a                                        |
| Footnote       | 6318    | 0.60         | 0.31         | 0.58         | 83-91                                      | n/a                                        | 100                                        | 62-88                                      | 85-94                                      | n/a                                        | 82-97                                      |
| Formula        | 25027   | 2.25         | 1.90         | 2.96         | 83-85                                      | n/a                                        | n/a                                        | 84-87                                      | 86-96                                      | n/a                                        | n/a                                        |
| List-item      | 185660  | 17.19        | 13.34        | 15.82        | 87-88                                      | 74-83                                      | 90-92                                      | 97-97                                      | 81-85                                      | 75-88                                      | 93-95                                      |
| Page-footer    | 70878   | 6.51         | 5.58         | 6.00         | 93-94                                      | 88-90                                      | 95-96                                      | 100                                        | 92-97                                      | 100                                        | 96-98                                      |
| Page-header    | 58022   | 5.10         | 6.70         | 5.06         | 85-89                                      | 66-76                                      | 90-94                                      | 98-100                                     | 91-92                                      | 97-99                                      | 81-86                                      |
| Picture        | 45976   | 4.21         | 2.78         | 5.31         | 69-71                                      | 56-59                                      | 82-86                                      | 69-82                                      | 80-95                                      | 66-71                                      | 59-76                                      |
| Section-header | 142884  | 12.60        | 15.77        | 12.85        | 83-84                                      | 76-81                                      | 90-92                                      | 94-95                                      | 87-94                                      | 69-73                                      | 78-86                                      |
| Table          | 34733   | 3.20         | 2.27         | 3.60         | 77-81                                      | 75-80                                      | 83-86                                      | 98-99                                      | 58-80                                      | 79-84                                      | 70-85                                      |
| Text           | 510377  | 45.82        | 49.28        | 45.00        | 84-86                                      | 81-86                                      | 88-93                                      | 89-93                                      | 87-92                                      | 71-79                                      | 87-95                                      |
| Title          | 5071    | 0.47         | 0.30         | 0.50         | 60-72                                      | 24-63                                      | 50-63                                      | 94-100                                     | 82-96                                      | 68-79                                      | 24-56                                      |
| Total          | 1107470 | 941123       | 99816        | 66531        | 82-83                                      | 71-74                                      | 79-81                                      | 89-94                                      | 86-91                                      | 71-76                                      | 68-85                                      |

Figure 3: Corpus Conversion Service annotation user interface. The PDF page is shown in the background, with overlaid text-cells (in darker shades). The annotation boxes can be drawn by dragging a rectangle over each segment with the respective label from the palette on the right.

<!-- image -->

we distributed the annotation workload and performed continuous quality controls. Phase one and two required a small team of experts only. For phases three and four, a group of 40 dedicated annotators were assembled and supervised.

Phase 1: Data selection and preparation. Our inclusion criteria for documents were described in Section 3. A large effort went into ensuring that all documents are free to use. The data sources include publication repositories such as arXiv', government offices, company websites as well as data directory services for financial reports and patents. Scanned documents were excluded wherever possible because they can be rotated or skewed. This would not allow us to perform annotation with rectangular bounding-boxes and therefore complicate the annotation process.

Preparation work included uploading and parsing the sourced PDF documents in the Corpus Conversion Service (CCS) [22], a cloud-native platform which provides a visual annotation interface and allows for dataset inspection and analysis. The annotation interface of CCS is shown in Figure 3. The desired balance of pages between the different document categories was achieved by selective subsampling of pages with certain desired properties. For example, we made sure to include the title page of each document and bias the remaining page selection to those with figures or tables. The latter was achieved by leveraging pre-trained object detection models from PubLayNet, which helped us estimate how many figures and tables a given page contains.

Phase 2: Label selection and guideline. We reviewed the collected documents and identified the most common structural features they exhibit. This was achieved by identifying recurrent layout elements and lead us to the definition of 11 distinct class labels. These 11 class labels are Caption, Footnote, Formula, List-item, Pagefooter, Page-header, Picture, Section-header, Table, Text, and Title. Critical factors that were considered for the choice of these class labels were (1) the overall occurrence of the label, (2) the specificity of the label, (3) recognisability on a single page (i.e. no need for context from previous or next page) and (4) overall coverage of the page. Specificity ensures that the choice of label is not ambiguous, while coverage ensures that all meaningful items on a page can be annotated. We refrained from class labels that are very specific to a document category, such as Abstract in the Scientific Articles category. We also avoided class labels that are tightly linked to the semantics of the text. Labels such as Author and Affiliation, as seen in DocBank, are often only distinguishable by discriminating on

$https://arxiv.org/

the textual content of an element, which goes beyond visual layout recognition, in particular outside the Scientific Articles category.

At first sight, the task of visual document-layout interpretation appears intuitive enough to obtain plausible annotations in most cases. However, during early trial-runs in the core team, we observed many cases in which annotators use different annotation styles, especially for documents with challenging layouts. For example, if a figure is presented with subfigures, one annotator might draw a single figure bounding-box, while another might annotate each subfigure separately. The same applies for lists, where one might annotate all list items in one block or each list item separately. In essence, we observed that challenging layouts would be annotated in different but plausible ways. To illustrate this, we show in Figure 4 multiple examples of plausible but inconsistent annotations on the same pages.

Obviously, this inconsistency in annotations is not desirable for datasets which are intended to be used for model training. To minimise these inconsistencies, we created a detailed annotation guideline. While perfect consistency across 40 annotation staff members is clearly not possible to achieve, we saw a huge improvement in annotation consistency after the introduction of our annotation guideline. A few selected, non-trivial highlights of the guideline are:

- (1) Every list-item is an individual object instance with class label List-item. This definition is different from PubLayNet and DocBank, where all list-items are grouped together into one List object.
- (2) A List-item is a paragraph with hanging indentation. Singleline elements can qualify as List-item if the neighbour elements expose hanging indentation. Bullet or enumeration symbols are not a requirement.
- (3) For every Caption, there must be exactly one corresponding Picture or Table.
- (4) Connected sub-pictures are grouped together in one Picture object.
- (5) Formula numbers are included in a Formula object.
- (6) Emphasised text (e.g. in italic or bold) at the beginning of a paragraph is not considered a Section-header, unless it appears exclusively on its own line.

The complete annotation guideline is over 100 pages long and a detailed description is obviously out of scope for this paper. Nevertheless, it will be made publicly available alongside with DocLayNet for future reference.

Phase 3: Training. After a first trial with a small group of people, we realised that providing the annotation guideline and a set of random practice pages did not yield the desired quality level for layout annotation. Therefore we prepared a subset of pages with two different complexity levels, each with a practice and an exam part. 974 pages were reference-annotated by one proficient core team member. Annotation staff were then given the task to annotate the same subsets (blinded from the reference). By comparing the annotations of each staff member with the reference annotations, we could quantify how closely their annotations matched the reference. Only after passing two exam levels with high annotation quality, staff were admitted into the production phase. Practice iterations

Figure 4: Examples of plausible annotation alternatives for the same page. Criteria in our annotation guideline can resolve cases A to C, while the case D remains ambiguous.

<!-- image -->

were carried out over a timeframe of 12 weeks, after which 8 of the 40 initially allocated annotators did not pass the bar.

Phase 4: Production annotation. The previously selected 80K pages were annotated with the defined 11 class labels by 32 annotators. This production phase took around three months to complete. All annotations were created online through CCS, which visualises the programmatic PDF text-cells as an overlay on the page. The page annotation are obtained by drawing rectangular bounding-boxes, as shown in Figure 3. With regard to the annotation practices, we implemented a few constraints and capabilities on the tooling level. First, we only allow non-overlapping, vertically oriented, rectangular boxes. For the large majority of documents, this constraint was sufficient and it speeds up the annotation considerably in comparison with arbitrary segmentation shapes. Second, annotator staff were not able to see each other's annotations. This was enforced by design to avoid any bias in the annotation, which could skew the numbers of the inter-annotator agreement (see Table 1). We wanted

Table 2: Prediction performance (mAP@0.5-0.95) of object detection networks on DocLayNet test set. The MRCNN (Mask R-CNN) and FRCNN (Faster R-CNN) models with ResNet-50 or ResNet-101 backbone were trained based on the network architectures from the detectron2 model zoo (Mask R-CNN R50, R101-FPN 3x, Faster R-CNN R101-FPN 3x), with default configurations. The YOLO implementation utilized was YOLOv5x6 [13]. All models were initialised using pre-trained weights from the COCO 2017 dataset.

|                | human   | MRCNN   | MRCNN   | FRCNN   | YOLO   |
|----------------|---------|---------|---------|---------|--------|
|                |         | R50     | R101    | R101    | v5x6   |
| Caption        | 84-89   | 68.4    | 71.5    | 70.1    | 77.7   |
| Footnote       | 83-91   | 70.9    | 71.8    | 73.7    | 77.2   |
| Formula        | 83-85   | 60.1    | 63.4    | 63.5    | 66.2   |
| List-item      | 87-88   | 81.2    | 80.8    | 81.0    | 86.2   |
| Page-footer    | 93-94   | 61.6    | 59.3    | 58.9    | 61.1   |
| Page-header    | 85-89   | 71.9    | 70.0    | 72.0    | 67.9   |
| Picture        | 69-71   | 71.7    | 72.7    | 72.0    | 77.1   |
| Section-header | 83-84   | 67.6    | 69.3    | 68.4    | 74.6   |
| Table          | 77-81   | 82.2    | 82.9    | 82.2    | 86.3   |
| Text           | 84-86   | 84.6    | 85.8    | 85.4    | 88.1   |
| Title          | 60-72   | 76.7    | 80.4    | 79.9    | 82.7   |
| All            | 82-83   | 72.4    | 73.5    | 73.4    | 76.8   |

to avoid this at any cost in order to have clear, unbiased baseline numbers for human document-layout annotation. Third, we introduced the feature of snapping boxes around text segments to obtain a pixel-accurate annotation and again reduce time and effort. The CCS annotation tool automatically shrinks every user-drawn box to the minimum bounding-box around the enclosed text-cells for all purely text-based segments, which excludes only Table and Picture. For the latter, we instructed annotation staff to minimise inclusion of surrounding whitespace while including all graphical lines. A downside of snapping boxes to enclosed text cells is that some wrongly parsed PDF pages cannot be annotated correctly and need to be skipped. Fourth, we established a way to flag pages as rejected for cases where no valid annotation according to the label guidelines could be achieved. Example cases for this would be PDF pages that render incorrectly or contain layouts that are impossible to capture with non-overlapping rectangles. Such rejected pages are not contained in the final dataset. With all these measures in place, experienced annotation staff managed to annotate a single page in a typical timeframe of 20s to 60s, depending on its complexity.

## 5 EXPERIMENTS

The primary goal of DocLayNet is to obtain high-quality ML models capable of accurate document-layout analysis on a wide variety of challenging layouts. As discussed in Section 2, object detection models are currently the easiest to use, due to the standardisation of ground-truth data in COCO format [16] and the availability of general frameworks such as detectron2 [17]. Furthermore, baseline numbers in PubLayNet and DocBank were obtained using standard object detection models such as Mask R-CNN and Faster R-CNN. As such, we will relate to these object detection methods in this

Figure 5: Prediction performance (mAP@0.5-0.95) of a Mask R-CNN network with ResNet50 backbone trained on increasing fractions of the DocLayNet dataset. The learning curve flattens around the 80% mark, indicating that increasing the size of the DocLayNet dataset with similar data will not yield significantly better predictions.

<!-- image -->

paper and leave the detailed evaluation of more recent methods mentioned in Section 2 for future work.

In this section, we will present several aspects related to the performance of object detection models on DocLayNet. Similarly as in PubLayNet, we will evaluate the quality of their predictions using mean average precision (mAP) with 10 overlaps that range from 0.5 to 0.95 in steps of 0.05 (mAP@0.5-0.95). These scores are computed by leveraging the evaluation code provided by the COCO API [16].

## Baselines for Object Detection

In Table 2, we present baseline experiments (given in mAP) on Mask R-CNN [12], Faster R-CNN [11], and YOLOv5 [13]. Both training and evaluation were performed on RGB images with dimensions of 1025 x 1025 pixels. For training, we only used one annotation in case of redundantly annotated pages. As one can observe, the variation in mAP between the models is rather low, but overall between 6 and 10% lower than the mAP computed from the pairwise human annotations on triple-annotated pages. This gives a good indication that the DocLayNet dataset poses a worthwhile challenge for the research community to close the gap between human recognition and ML approaches. It is interesting to see that Mask R-CNN and Faster R-CNN produce very comparable mAP scores, indicating that pixel-based image segmentation derived from bounding-boxes does not help to obtain better predictions. On the other hand, the more recent Yolov5x model does very well and even out-performs humans on selected labels such as Text, Table and Picture. This is not entirely surprising, as Text, Table and Picture are abundant and the most visually distinctive in a document.

Table 3: Performance of a Mask R-CNN R50 network in mAP@0.5-0.95 scores trained on DocLayNet with different class label sets. The reduced label sets were obtained by either down-mapping or dropping labels.

| Class-count    |   11 | 6       | 5       | 4       |
|----------------|------|---------|---------|---------|
| Caption        |   68 | Text    | Text    | Text    |
| Footnote       |   71 | Text    | Text    | Text    |
| Formula        |   60 | Text    | Text    | Text    |
| List-item      |   81 | Text    | 82      | Text    |
| Page-footer    |   62 | 62      | -       | -       |
| Page-header    |   72 | 68      | -       | -       |
| Picture        |   72 | 72      | 72      | 72      |
| Section-header |   68 | 67      | 69      | 68      |
| Table          |   82 | 83      | 82      | 82      |
| Text           |   85 | 84      | 84      | 84      |
| Title          |   77 | Sec.-h. | Sec.-h. | Sec.-h. |
| Overall        |   72 | 73      | 78      | 77      |

## Learning Curve

One of the fundamental questions related to any dataset is if it is "large enough". To answer this question for DocLayNet, we performed a data ablation study in which we evaluated a Mask R-CNN model trained on increasing fractions of the DocLayNet dataset. As can be seen in Figure 5, the mAP score rises sharply in the beginning and eventually levels out. To estimate the error-bar on the metrics, we ran the training five times on the entire data-set. This resulted in a 1% error-bar, depicted by the shaded area in Figure 5. In the inset of Figure 5, we show the exact same data-points, but with a logarithmic scale on the x-axis. As is expected, the mAP score increases linearly as a function of the data-size in the inset. The curve ultimately flattens out between the 80% and 100% mark, with the 80% mark falling within the error-bars of the 100% mark. This provides a good indication that the model would not improve significantly by yet increasing the data size. Rather, it would probably benefit more from improved data consistency (as discussed in Section 3), data augmentation methods [23], or the addition of more document categories and styles.

## Impact of Class Labels

The choice and number of labels can have a significant effect on the overall model performance. Since PubLayNet, DocBank and DocLayNet all have different label sets, it is of particular interest to understand and quantify this influence of the label set on the model performance. We investigate this by either down-mapping labels into more common ones (e.g. Caption— Text) or excluding them from the annotations entirely. Furthermore, it must be stressed that all mappings and exclusions were performed on the data before model training. In Table 3, we present the mAP scores for a Mask R-CNN R50 network on different label sets. Where a label is down-mapped, we show its corresponding label, otherwise it was excluded. We present three different label sets, with 6, 5 and 4 different labels respectively. The set of 5 labels contains the same labels as PubLayNet. However, due to the different definition of

Table 4: Performance of a Mask R-CNN R50 network with document-wise and page-wise split for different label sets. Naive page-wise split will result in ~10% point improvement.

| Class-count    | 11   | 11   | 5   | 5    |
|----------------|------|------|-----|------|
| Split          | Doc  | Page | Doc | Page |
| Caption        | 68   | 83   |     |      |
| Footnote       | 71   | 84   |     |      |
| Formula        | 60   | 66   |     |      |
| List-item      | 81   | 88   | 82  | 88   |
| Page-footer    | 62   | 89   |     |      |
| Page-header    | 72   | 90   |     |      |
| Picture        | 72   | 82   | 72  | 82   |
| Section-header | 68   | 83   | 69  | 83   |
| Table          | 82   | 89   | 82  | 90   |
| Text           | 85   | 91   | 84  | 90   |
| Title          | 77   | 81   |     |      |
| All            | 72   | 84   | 78  | 87   |

lists in PubLayNet (grouped list-items) versus DocLayNet (separate list-items), the label set of size 4 is the closest to PubLayNet, in the assumption that the List is down-mapped to Text in PubLayNet. The results in Table 3 show that the prediction accuracy on the remaining class labels does not change significantly when other classes are merged into them. The overall macro-average improves by around 5%, in particular when Page-footer and Page-header are excluded.

## Impact of Document Split in Train and Test Set

Many documents in DocLayNet have a unique styling. In order to avoid overfitting on a particular style, we have split the train-, testand validation-sets of DocLayNet on document boundaries, i.e. every document contributes pages to only one set. To the best of our knowledge, this was not considered in PubLayNet or DocBank. To quantify how this affects model performance, we trained and evaluated a Mask R-CNN R50 model on a modified dataset version. Here, the train-, testand validation-sets were obtained by a randomised draw over the individual pages. As can be seen in Table 4, the difference in model performance is surprisingly large: pagewise splitting gains 10% in mAP over the document-wise splitting. Thus, random page-wise splitting of DocLayNet can easily lead to accidental overestimation of model performance and should be avoided.

## Dataset Comparison

Throughout this paper, we claim that DocLayNet's wider variety of document layouts leads to more robust layout detection models. In Table 5, we provide evidence for that. We trained models on each of the available datasets (PubLayNet, DocBank and DocLayNet) and evaluated them on the test sets of the other datasets. Due to the different label sets and annotation styles, a direct comparison is not possible. Hence, we focussed on the common labels among the datasets. Between PubLayNet and DocLayNet, these are Picture,

Table 5: Prediction Performance (mAP@0.5-0.95) of a Mask R-CNN R50 network across the PubLayNet, DocBank &amp; DocLayNet data-sets. By evaluating on common label classes of each dataset, we observe that the DocLayNet-trained model has much less pronounced variations in performance across all datasets.

|                 |            | Testing on   | Testing on   | Testing on   |
|-----------------|------------|--------------|--------------|--------------|
| Training on     | labels     | PLN          | DB           | DLN          |
| PubLayNet (PLN) | Figure     | 96           | 43           | 23           |
| PubLayNet (PLN) | Sec-header | 87           | -            | 32           |
|                 | Table      | 95           | 24           | 49           |
|                 | Text       | 96           | -            | 42           |
|                 | total      | 93           | 34           | 30           |
| DocBank (DB)    | Figure     | 77           | 71           | 31           |
| DocBank (DB)    | Table      | 19           | 65           | 22           |
| DocBank (DB)    | total      | 48           | 68           | 27           |
| DocLayNet (DLN) | Figure     | 67           | 51           | 72           |
| DocLayNet (DLN) | Sec-header | 53           | -            | 68           |
|                 | Table      | 87           | 43           | 82           |
|                 | Text       | 77           | -            | 84           |
|                 | total      | 59           | 47           | 78           |

Section-header, Table and Text. Before training, we either mapped or excluded DocLayNet's other labels as specified in table 3, and also PubLayNet's List to Text. Note that the different clustering of lists (by list-element vs. whole list objects) naturally decreases the mAP score for Text.

For comparison of DocBank with DocLayNet, we trained only on Picture and Table clusters of each dataset. We had to exclude Text because successive paragraphs are often grouped together into a single object in DocBank. This paragraph grouping is incompatible with the individual paragraphs of DocLayNet. As can be seen in Table 5, DocLayNet trained models yield better performance compared to the previous datasets. It is noteworthy that the models trained on PubLayNet and DocBank perform very well on their own test set, but have a much lower performance on the foreign datasets. While this also applies to DocLayNet, the difference is far less pronounced. Thus we conclude that DocLayNet trained models are overall more robust and will produce better results for challenging, unseen layouts.

## Example Predictions

To conclude this section, we illustrate the quality of layout predictions one can expect from DocLayNet-trained models by providing a selection of examples without any further post-processing applied. Figure 6 shows selected layout predictions on pages from the test-set of DocLayNet. Results look decent in general across document categories, however one can also observe mistakes such as overlapping clusters of different classes, or entirely missing boxes due to low confidence.

## 6 CONCLUSION

In this paper, we presented the DocLayNet dataset. It provides the document conversion and layout analysis research community a new and challenging dataset to improve and fine-tune novel ML methods on. In contrast to many other datasets, DocLayNet was created by human annotation in order to obtain reliable layout ground-truth on a wide variety of publicationand typesettingstyles. Including a large proportion of documents outside the scientific publishing domain adds significant value in this respect.

From the dataset, we have derived on the one hand reference metrics for human performance on document-layout annotation (through double and triple annotations) and on the other hand evaluated the baseline performance of commonly used object detection methods. We also illustrated the impact of various dataset-related aspects on model performance through data-ablation experiments, both from a size and class-label perspective. Last but not least, we compared the accuracy of models trained on other public datasets and showed that DocLayNet trained models are more robust.

To date, there is still a significant gap between human and ML accuracy on the layout interpretation task, and we hope that this work will inspire the research community to close that gap.

## REFERENCES

- 1] Max Gobel, Tamir Hassan, Ermelinda Oro, and Giorgio Orsi. Icdar 2013 table competition. In 2013 12th International Conference on Document Analysis and Recognition, pages 1449-1453, 2013.
- 2] Christian Clausner, Apostolos Antonacopoulos, and Stefan Pletschacher. Icdar2017 competition on recognition of documents with complex layouts -rdcl2017. In 2017 14th IAPR International Conference on Document Analysis and Recognition (ICDAR), volume 01, pages 1404-1410, 2017.
- 3] Hervé Déjean, Jean-Luc Meunier, Liangcai Gao, Yilun Huang, Yu Fang, Florian Kleber, and Eva-Maria Lang. ICDAR 2019 Competition on Table Detection and Recognition (cTDaR), April 2019. http://sac.founderit.com/.
- 4] Antonio Jimeno Yepes, Peter Zhong, and Douglas Burdick. Competition on scientific literature parsing. In Proceedings of the International Conference on Document Analysis and Recognition, ICDAR, pages 605-617. LNCS 12824, SpringerVerlag, sep 2021.
- 5] Logan Markewich, Hao Zhang, Yubin Xing, Navid Lambert-Shirzad, Jiang Zhexin, Roy Lee, Zhi Li, and Seok-Bum Ko. Segmentation for document layout analysis: not dead yet. International Journal on Document Analysis and Recognition (IJDAR), pages 1-11, 01 2022.
- 6] Xu Zhong, Jianbin Tang, and Antonio Jimeno-Yepes. Publaynet: Largest dataset ever for document layout analysis. In Proceedings of the International Conference on Document Analysis and Recognition, ICDAR, pages 1015-1022, sep 2019.
- 7] Minghao Li, Yiheng Xu, Lei Cui, Shaohan Huang, Furu Wei, Zhoujun Li, and Ming Zhou. Docbank: A benchmark dataset for document layout analysis. In Proceedings of the 28th International Conference on Computational Linguistics, COLING, pages 949-960. International Committee on Computational Linguistics, dec 2020.
- 8] Riaz Ahmad, Muhammad Tanvir Afzal, and M. Qadir. Information extraction from pdf sources based on rule-based system using integrated formats. In Sem WebEval@ESWC, 2016.
- 9] Ross B. Girshick, Jeff Donahue, Trevor Darrell, and Jitendra Malik. Rich feature hierarchies for accurate object detection and semantic segmentation. In IEEE Conference on Computer Vision and Pattern Recognition, CVPR, pages 580-587. IEEE Computer Society, jun 2014.
- [10] Ross B. Girshick. Fast R-CNN. In 2015 IEEE International Conference on Computer Vision, ICCV, pages 1440-1448. IEEE Computer Society, dec 2015.
- [11] Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun. Faster r-cnn: Towards real-time object detection with region proposal networks. IEEE Transactions on Pattern Analysis and Machine Intelligence, 39(6):1137-1149, 2017.
- [12] Kaiming He, Georgia Gkioxari, Piotr Dollar, and Ross B. Girshick. Mask R-CNN. In IEEE International Conference on Computer Vision, ICCV, pages 2980-2988. IEEE Computer Society, Oct 2017.
- [13] Glenn Jocher, Alex Stoken, Ayush Chaurasia, Jirka Borovec, NanoCode012, TaoXie, Yonghye Kwon, Kalen Michael, Liu Changyu, Jiacong Fang, Abhiram V, Laughing, tkianai, yxNONG, Piotr Skalski, Adam Hogan, Jebastin Nadar, imyhxy, Lorenzo Mammana, Alex Wang, Cristi Fati, Diego Montes, Jan Hajek, Laurentiu

OText OCaption Olistttem OFormula OTable OPicture @Section-Header QPage-Header OPage-Footer OTitle

<!-- image -->

Figure 6: Example layout predictions on selected pages from the DocLayNet test-set. (A, D) exhibit favourable results on coloured backgrounds. (B, C) show accurate list-item and paragraph differentiation despite densely-spaced lines. (E) demonstrates good table and figure distinction. (F) shows predictions on a Chinese patent with multiple overlaps, label confusion and missing boxes.

Diaconu, Mai Thanh Minh, Marc, albinxavi, fatih, oleg, and wanghao yang. ultralytics/yolovs: v6.0 -yolovSn nano models, roboflow integration, tensorflow export, opencv dnn support, October 2021.

- [20] Shoubin Li, Xuyan Ma, Shuaiqun Pan, Jun Hu, Lin Shi, and Qing Wang. Vtlayout: Fusion of visual and text features for document layout analysis, 2021.
- 14 Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to-end object detection with transformers. CORR, abs/2005.12872, 2020.
- 15. Mingxing Tan, Ruoming Pang, and Quoc V. Le. Efficientdet: Scalable and efficient object detection. CoRR, abs/1911.09070, 2019.
- 16 Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdey, Ross B. Girshick, James Hays, Pietro Perona, Deva Ramanan, Piotr Dollar, and C. Lawrence Zitnick. Microsoft COCO: common objects in context, 2014.
- 17 Yuxin Wu, Alexander Kirillov, Francisco Massa, Wan-Yen Lo, and Ross Girshick. Detectron2, 2019.
- 18 Nikolaos Livathinos, Cesar Berrospi, Maksym Lysak, Viktor Kuropiatnyk, Ahmed Nassar, Andre Carvalho, Michele Dolfi, Christoph Auer, Kasper Dinkla, and Peter W. J. Staar. Robust pdf document conversion using recurrent neural networks. In Proceedings of the 35th Conference on Artificial Intelligence, AAAI, pages 1513715145, feb 2021.
- 19 Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, and Ming Zhou. Layoutlm: Pre-training of text and layout for document image understanding. In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, KDD, pages 1192-1200, New York, USA, 2020. Association for Computing Machinery.
- [21] Peng Zhang, Can Li, Liang Qiao, Zhanzhan Cheng, Shiliang Pu, Yi Niu, and Fei Wu. Vsr: A unified framework for document layout analysis combining vision, semantics and relations, 2021.
- [22] Peter W J Staar, Michele Dolfi, Christoph Auer, and Costas Bekas. Corpus conversion service: A machine learning platform to ingest documents at scale. In Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, KDD, pages 774-782. ACM, 2018.
- [23] Connor Shorten and Taghi M. Khoshgoftaar. A survey on image data augmentation for deep learning. Journal of Big Data, 6(1):60, 2019.
Enter fullscreen mode Exit fullscreen mode
  • Also the document(s) are flagged as processed as mentioned previously;
{
    "data/pdf/2206.01062.pdf": {
        "last_modified": 1751716138,
        "milvus_pk": "2206.01062_3817379d"
    }
}
Enter fullscreen mode Exit fullscreen mode
  • The second application will chat with the RAG database;
import os
import sys
from pathlib import Path

# --- Milvus Library Imports ---
try:
    from pymilvus import connections, Collection, DataType, utility
except ImportError:
    print("Error: 'pymilvus' library not found.")
    print("Please install it using: pip install pymilvus")
    sys.exit(1)

# --- Sentence Transformer Import for Embeddings ---
try:
    from sentence_transformers import SentenceTransformer
except ImportError:
    print("Error: 'sentence-transformers' library not found.")
    print("Please install it using: pip install sentence-transformers")
    sys.exit(1)

# --- Ollama Library Import ---
try:
    import ollama
except ImportError:
    print("Error: 'ollama' library not found.")
    print("Please install it using: pip install ollama")
    sys.exit(1)

# --- Configuration for Milvus ---
MILVUS_HOST = "localhost"
MILVUS_PORT = "19530"
COLLECTION_NAME = "ocr_documents"
VECTOR_DIM = 384  # Dimension of the embeddings from 'all-MiniLM-L6-v2' model

# --- Configuration for Ollama ---
OLLAMA_MODEL = "granite3.3:latest"
OLLAMA_API_BASE_URL = "http://localhost:11434" # Default Ollama API URL

# --- Load Sentence Embedding Model ---
print("Loading sentence embedding model for queries and retrieval...")
try:
    embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
    print("Sentence embedding model loaded.")
except Exception as e:
    print(f"Error loading sentence embedding model: {e}")
    print("Please ensure you have an internet connection to download the model or it's cached locally.")
    sys.exit(1)

def connect_to_milvus():
    """
    Connects to Milvus and returns the collection object.
    """
    print(f"Connecting to Milvus at {MILVUS_HOST}:{MILVUS_PORT}...")
    try:
        connections.connect(host=MILVUS_HOST, port=MILVUS_PORT)
        print("Connected to Milvus.")
    except Exception as e:
        print(f"Failed to connect to Milvus: {e}")
        print("Please ensure your Milvus instance is running.")
        sys.exit(1)

    if not utility.has_collection(COLLECTION_NAME):
        print(f"Error: Collection '{COLLECTION_NAME}' not found in Milvus.")
        print("Please run the 'ocr-to-milvus-app' first to populate the database.")
        sys.exit(1)

    collection = Collection(COLLECTION_NAME)
    print(f"Loading collection '{COLLECTION_NAME}' into memory for search...")
    collection.load()
    print(f"Collection '{COLLECTION_NAME}' loaded.")
    return collection

def retrieve_context_from_milvus(query_embedding, milvus_collection, top_k=3):
    """
    Performs a similarity search in Milvus to retrieve relevant document chunks.
    """
    search_params = {
        "metric_type": "L2",
        "params": {"nprobe": 10},
    }
    try:
        results = milvus_collection.search(
            data=[query_embedding],
            anns_field="embedding",
            param=search_params,
            limit=top_k,
            output_fields=["text_content", "file_name"]
        )
        return results[0] # Return the first (and only) query's results
    except Exception as e:
        print(f"Error during Milvus search: {e}")
        return []

def get_ollama_response(prompt_with_context):
    """
    Sends a prompt to the local Ollama LLM and returns the response.
    """
    try:
        response = ollama.chat(
            model=OLLAMA_MODEL,
            messages=[{'role': 'user', 'content': prompt_with_context}],
            options={'base_url': OLLAMA_API_BASE_URL} # Specify Ollama API URL
        )
        return response['message']['content']
    except ollama.ResponseError as e:
        print(f"Error communicating with Ollama: {e}")
        print(f"Please ensure Ollama is running and '{OLLAMA_MODEL}' model is available.")
        return "Sorry, I couldn't get a response from the LLM. Please check Ollama."
    except Exception as e:
        print(f"An unexpected error occurred with Ollama: {e}")
        return "An unexpected error occurred while generating the response."

def main():
    milvus_collection = connect_to_milvus()

    print("\n--- Interactive Milvus-Ollama Chat ---")
    print(f"Using Ollama model: {OLLAMA_MODEL}")
    print("Type your query and press Enter. Type 'exit' to quit.")

    while True:
        user_query = input("\nYou: ").strip()
        if user_query.lower() == 'exit':
            print("Exiting chat. Goodbye!")
            break
        if not user_query:
            continue

        # 1. Generate embedding for the user's query
        query_embedding = embedding_model.encode(user_query).tolist()

        # 2. Retrieve relevant context from Milvus
        print("Searching Milvus for relevant context...")
        milvus_results = retrieve_context_from_milvus(query_embedding, milvus_collection)

        context_texts = []
        source_files = set()
        if milvus_results:
            for hit in milvus_results:
                context_texts.append(hit.entity.get('text_content', ''))
                source_files.add(hit.entity.get('file_name', 'Unknown File'))
            print(f"Found relevant context from: {', '.join(source_files)}")
        else:
            print("No relevant context found in Milvus.")

        # 3. Construct prompt for Ollama with retrieved context
        if context_texts:
            context_str = "\n\n".join(context_texts)
            prompt_for_llm = (
                "You are an AI assistant that answers questions based on the provided document context.\n"
                "If the answer is not available in the context, state that you don't know.\n\n"
                "Context:\n"
                f"{context_str}\n\n"
                f"Question: {user_query}\n"
                "Answer:"
            )
        else:
            prompt_for_llm = (
                "You are an AI assistant. No specific document context was found for this query.\n"
                "Answer the question to the best of your general knowledge, or state if you cannot.\n\n"
                f"Question: {user_query}\n"
                "Answer:"
            )

        # 4. Get response from Ollama
        print("Generating response with Ollama...")
        llm_response = get_ollama_response(prompt_for_llm)

        # 5. Display the response
        print(f"\nAI: {llm_response}")
        if source_files:
            print(f"Sources: {', '.join(source_files)}")

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode
  • Now let’s try a sample chat;
python milvus_rag_granite_chatt.py
#####
Loading sentence embedding model for queries and retrieval...
Sentence embedding model loaded.
Connecting to Milvus at localhost:19530...
Connected to Milvus.
Loading collection 'ocr_documents' into memory for search...
Collection 'ocr_documents' loaded.

--- Interactive Milvus-Ollama Chat ---
Using Ollama model: granite3.3:latest
Type your query and press Enter. Type 'exit' to quit.

You: what does this paper talk about                 
Searching Milvus for relevant context...
Found relevant context from: 2206.01062.pdf
Generating response with Ollama...

AI: This paper discusses a dataset called DocLayNet, which is one of the largest and most comprehensive datasets available for document layout analysis. The authors compare DocLayNet to two existing datasets, PubLayNet and DocBank, highlighting its advantages such as a broader range of document types, higher-quality annotations, and more realistic scenarios. They also provide insights into the challenges faced during the creation of the dataset and present quantitative and qualitative evaluations to demonstrate its utility for research in document layout analysis and information extraction. The paper references various other works related to object detection, transformer models, and PDF document conversion using recurrent neural networks.

References:
- [6] Xu Zhong, Jianbin Tang, and Antonio Jimeno-Yepes. Publaynet: Largest dataset ever for document layout analysis. In Proceedings of the International Conference on Document Analysis and Recognition, ICDAR, pages 1015-1022, sep 2019.
- [7] Minghao Li, Yiheng Xu, Lei Cui, Shaohan Huang, Furu Wei, Zhoujun Li, and Ming Zhou. Docbank: A benchmark dataset for document layout analysis. In Proceedings of the 28th International Conference on Computational Linguistics, COLING, pages 949-960. International Committee on Computational Linguistics, dec 2020.
- [18] Nikolaos Livathinos, Cesar Berrospi, Maksym Lysak, Viktor Kuropiatnyk, Ahmed Nassar, Andre Carvalho, Michele Dolfi, Christoph Auer, Kasper Dinkla, and Peter W. J. Staar. Robust pdf document conversion using recurrent neural networks. In Proceedings of the 35th Conference on Artificial Intelligence, AAAI, pages 15137-15145, feb 2021.
- [22] Peter W J Staar, Michele Dolfi, Christoph Auer, and Costas Bekas. Corpus conversion service: A machine learning platform to ingest documents at scale. In Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, KDD, pages 774-782. ACM, 2018.
- [23] Connor Shorten and Taghi M. Khoshgoftaar. A survey on image data augmentation for deep learning. Journal of Big Data, 6(1):60, 2019.
Sources: 2206.01062.pdf
Enter fullscreen mode Exit fullscreen mode

That’s all!

Conclusion

Through this project, we’ve established a robust pipeline that transforms static, often inaccessible, business and knowledge documents into dynamic, interactive assets. The journey begins with OCRization, where scanned PDF files are meticulously converted into structured Markdown formats, extracting not just text but also crucial elements like table structures. These digitized documents are then embedded into a Milvus vector database, turning raw content into searchable, contextually rich data points. Finally, an LLM-powered chat interface leverages this embedded knowledge, allowing end-users to query documents in natural language. This comprehensive approach ensures that valuable information, previously locked away in image-based files, becomes instantly accessible, enabling efficient information retrieval, informed decision-making, and a truly intelligent interaction with an organization’s knowledge base.

Thanks for reading 🤗

Links

Top comments (0)