Rapid Layout Document Layout Analysis

repository·main·Indexed 42 days ago

https://github.com/rapidai/rapidlayout

A document layout analysis tool for detecting and locating elements such as titles, paragraphs, tables, and images in research papers and reports. It supports Python API and CLI usage, integrates models like PP-DocLayoutV2/V3, YOLOv8, and DocLayout-YOLO, and provides acceleration options via ONNX Runtime for GPU (CUDA) and NPU (CANN).

Tokens
12.8K
Snippets
37
Records
50
Agent score
53%

What's inside Rapid Layout

  1. Overview of Rapid Layout capabilities

    main

    Rapid Layout is a document layout analysis tool that identifies the category and position of layout elements such as titles, paragraphs, tables, and images in document-type images (e.g., paper screenshots, research reports).

    Supported Scenarios:

    • Tables
    • Chinese text
    • English text
    • Academic papers
    • Research reports
    • General layouts

    The project integrates various open-source models including the PP series, YOLOv8 series, and DocLayout-YOLO. Because different scenarios have significant layout variations, it is recommended to fine-tune with a custom dataset if the built-in models do not meet your specific business requirements.

  2. Use OpenVINO for Inference

    main

    To use the OpenVINO engine, first install the required packages: pip install rapid-layout onnxruntime openvino. You can then initialize RapidLayout directly by setting engine_type=EngineType.OPENVINO. Configuration for OpenVINO devices and threads can be managed via the openvino section in the engine configuration.

    pip install rapid-layout onnxruntime openvino
    from rapid_layout import EngineType, ModelType, RapidLayout
    
    layout_engine = RapidLayout(
        model_type=ModelType.PP_LAYOUT_CDLA,
        engine_type=EngineType.OPENVINO,
    )
    img_path = "https://raw.githubusercontent.com/RapidAI/RapidLayout/718b60e927ab893c2fad67c98f753b2105a6f421/tests/test_files/layout.jpg"
    results = layout_engine(img_path)
    print(results)
    results.vis("layout_res.png")
  3. Set up the Rapid Layout development environment

    main

    To develop on Rapid Layout, clone the repository and set up a virtual environment to avoid system conflicts. It is recommended to perform an editable installation (pip install -e .) so that local changes take effect immediately.

    Prerequisites:

    • Python >= 3.6 (3.8+ recommended)
    • Git
    • GitHub account

    Setup Steps:

    1. Clone the repository:
      git clone https://github.com/RapidAI/RapidLayout.git
      cd RapidLayout
    2. Create and activate a virtual environment (using venv or conda):
      # Using venv
      python -m venv .venv
      source .venv/bin/activate   # Linux/macOS
      # .venv\Scripts\activate  # Windows
      
      # Or using conda
      conda create -n rapidlayout python=3.10
      conda activate rapidlayout
    3. Install dependencies and the package in editable mode:
      pip install -r requirements.txt
      pip install pytest
      pip install -e .
    git clone https://github.com/RapidAI/RapidLayout.git
    cd RapidLayout
    python -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    pip install pytest
    pip install -e .
  4. Run unit tests with pytest

    main

    Tests are located in the tests/ directory. Use pytest from the repository root to verify your changes.

    • Run all tests: pytest tests/ -v
    • Run a specific test file: pytest tests/test_main.py -v
    • Check test coverage: pytest tests/ -v --cov=rapid_layout (requires pytest-cov installed)
    # Run all tests
    pytest tests/ -v
    
    # Run specific file
    pytest tests/test_main.py -v
    
    # Check coverage
    pytest tests/ -v --cov=rapid_layout
  5. Install rapid-layout and inference engines

    main

    Install the core library and the default onnxruntime engine using pip:

    pip install rapid-layout onnxruntime

    If you want to use the openvino engine, you must also install OpenVINO:

    pip install openvino
  6. Convert PP-DocLayout models to ONNX

    main

    Use the paddle2onnx command to convert the model directory and files to an .onnx file. Ensure you provide the correct paths to the model directory, the JSON file, and the parameter file.

    paddle2onnx  --model_dir=models/PP-DocLayoutV2  --model_filename inference.json --params_filename inference.pdiparams  --save_file=./models/PP-DocLayoutV2/inference.onnx  --enable_onnx_checker=True
  7. Write and structure new unit tests

    main

    When adding new features or fixing bugs, you must include corresponding unit tests.

    Guidelines:

    • Place test files in tests/ with the naming convention test_*.py.
    • Use pytest for writing test cases.
    • Place test resources (like images) in tests/test_files/.
    • Ensure tests are stable and do not depend on undocumented external services (use mocks where necessary).

    Example test structure:

    # tests/test_xxx.py
    import pytest
    from pathlib import Path
    
    cur_dir = Path(__file__).resolve().parent
    root_dir = cur_dir.parent
    test_dir = cur_dir / "test_files"
    
    def get_engine():
        from rapid_layout import RapidLayout
        return RapidLayout()
    
    def test_your_new_feature():
        engine = get_engine()
        img_path = test_dir / "layout.jpg"
        result = engine(img_path)
        assert result is not None
        # Add more assertions...
  8. Select a layout analysis model based on document type

    main

    RapidLayout supports various models optimized for different document scenarios. Because layout differences vary significantly across use cases, you should choose a model that matches your specific document type (e.g., English documents, Chinese documents, papers, or tables). If existing models do not meet your requirements, it is recommended to build a custom training set for fine-tuning.

    Available Model Types and Categories

    model_typeDocument TypeSupported Categories
    pp_doc_layoutv3 (requires rapid_layout>=1.2.0)Document['abstract', 'algorithm', 'aside_text', 'chart', 'content', 'display_formula', 'doc_title', 'figure_title', 'footer', 'footer_image', 'footnote', 'formula_number', 'header', 'header_image', 'image', 'inline_formula', 'number', 'paragraph_title', 'reference', 'reference_content', 'seal', 'table', 'text', 'vertical_text', 'vision_footnote']
    pp_doc_layoutv2 (requires rapid_layout>=1.1.0)Document['abstract', 'algorithm', 'aside_text', 'chart', 'content', 'display_formula', 'doc_title', 'figure_title', 'footer', 'footer_image', 'footnote', 'formula_number', 'header', 'header_image', 'image', 'inline_formula', 'number', 'paragraph_title', 'reference', 'reference_content', 'seal', 'table', 'text', 'vertical_text', 'vision_footnote']
    pp_layout_tableTable['table']
    pp_layout_publaynetEnglish['text', 'title', 'list', 'table', 'figure']
    pp_layout_cdlaChinese['text', 'title', 'figure', 'figure_caption', 'table', 'table_caption', 'header', 'footer', 'reference', 'equation']
    yolov8n_layout_paperPaper['Text', 'Title', 'Header', 'Footer', 'Figure', 'Table', 'Toc', 'Figure caption', 'Table caption']
    yolov8n_layout_reportResearch Report['Text', 'Title', 'Header', 'Footer', 'Figure', 'Table', 'Toc', 'Figure caption', 'Table caption']
    yolov8n_layout_publaynetEnglish['Text', 'Title', 'List', 'Table', 'Figure']
    yolov8n_layout_general6General['Text', 'Title', 'Figure', 'Table', 'Caption', 'Equation']
    doclayout_docstructbenchGeneral['title', 'plain text', 'abandon', 'figure', 'figure_caption', 'table', 'table_caption', 'table_footnote', 'isolate_formula', 'formula_caption']
    doclayout_d4laGeneral['DocTitle', 'ParaTitle', 'ParaText', 'ListText', 'RegionTitle', 'Date', 'LetterHead', 'LetterDear', 'LetterSign', 'Question', 'OtherText', 'RegionKV', 'RegionList', 'Abstract', 'Author', 'TableName', 'Table', 'Figure', 'FigureName', 'Equation', 'Reference', 'Footer', 'PageHeader', 'PageFooter', 'Number', 'Catalog', 'PageNumber']
    doclayout_docsynthGeneral['Caption', 'Footnote', 'Formula', 'List-item', 'Page-footer', 'Page-header', 'Picture', 'Section-header', 'Table', 'Text', 'Title']
  9. Run layout analysis with RapidLayout

    main

    You can use RapidLayout via a Python script or the CLI. By default, it uses the pp_layout_cdla model and the onnxruntime engine.

    Python Usage

    Default configuration:

    from rapid_layout import RapidLayout
    
    layout_engine = RapidLayout()
    img_path = "path/to/your/image.jpg"
    results = layout_engine(img_path)
    print(results)
    # Visualize the results
    results.vis("layout_res.png")

    Custom configuration (using keyword arguments):

    from rapid_layout import EngineType, ModelType, RapidLayout
    
    layout_engine = RapidLayout(
        model_type=ModelType.PP_LAYOUT_CDLA,
        engine_type=EngineType.ONNXRUNTIME,
        conf_thresh=0.5,
    )
    img_path = "path/to/your/image.jpg"
    results = layout_engine(img_path)
    results.vis("layout_res.png")

    Custom configuration (using RapidLayoutInput object):

    from rapid_layout import EngineType, ModelType, RapidLayout, RapidLayoutInput
    
    cfg = RapidLayoutInput(
        model_type=ModelType.PP_LAYOUT_CDLA,
        engine_type=EngineType.ONNXRUNTIME,
    )
    layout_engine = RapidLayout(cfg=cfg)
    img_path = "path/to/your/image.jpg"
    results = layout_engine(img_path)
    results.vis("layout_res.png")

    CLI Usage

    Run analysis directly from the terminal:

    # Basic usage
    rapid_layout test_images/layout.png
    
    # Usage with specific model and confidence threshold
    rapid_layout test_images/layout.png -m pp_layout_cdla --conf_thresh 0.5
    from rapid_layout import RapidLayout
    
    layout_engine = RapidLayout()
    img_path = "https://raw.githubusercontent.com/RapidAI/RapidLayout/718b60e927ab893c2fad67c98f753b2105a6f421/tests/test_files/layout.jpg"
    results = layout_engine(img_path)
    print(results)
    results.vis("layout_res.png")