# yuliang-liu/monkeyocr architecture

> Architecture diagram of the GitHub repository yuliang-liu/monkeyocr, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-06-13). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/yuliang-liu/monkeyocr
- Repository: https://github.com/yuliang-liu/monkeyocr

## Overview

##### Project Type and Purpose
- MonkeyOCR is a modular document parsing tool (Python library + CLI + demo) that implements a Structure-Recognition-Relation paradigm for extracting text, formulas, tables, and relationships from PDF/image inputs.
- It provides both a command-line interface (`parse.py`) and a Gradio-based demo (`demo/demo_gradio.py`) for interactive use.

##### High-Level Architecture Overview
- The system is organized into five primary layers:
1. **Presentation Layer**
- CLI entrypoint (`parse.py`)
- Gradio web UI (`demo/demo_gradio.py`)
2. **Configuration & Orchestration**
- `model_configs.yaml`, `magic_pdf/config/*`, `setup.py`
- Tools for model download and patching (`tools/download_model.py`, `tools/lmdeploy_patcher.py`)
3. **Data I/O Layer**
- Local file / HTTP / S3 readers & writers (`magic_pdf/data/io/*`, `magic_pdf/data/data_reader_writer/*`)
4. **Processing Pipeline**
a. **Pre-processing** (`magic_pdf/pre_proc/*`): image cropping, OCR‐bbox detection, page dict construction
b. **Filtering** (`magic_pdf/filter/*`): classify PDF block types, metadata scanning
c. **Model Inference** (`magic_pdf/model/*`, `magic_pdf/operators/*`):
- Structure detection submodule (DocLayoutYOLO or custom layout_zh)
- Content recognition (LLM / Transformers backend via LMDeploy or HuggingFace)
- Relation prediction triplets
d. **Post-processing** (`magic_pdf/post_proc/*`): paragraph splitting, merge OCR spans, remove overlaps
5. **Output Generation**
- Markdown conversion (`magic_pdf/dict2md/ocr_mkcontent.py`)
- Final PDFs with layout overlays, JSON block dumps (`.json`, `.md`, `_layout.pdf`)

##### Main Components & Interactions
- Input Layer:
- PDF/image → Data I/O → PIL/NumPy buffers
- Pre-processing → produces block candidates
- Filtering → prunes and annotates blocks
- Model Layer:
- Recognition Engine → text/formula/table content
- Relation Predictor → upstream/downstream links
- Post-processing → refines order & splits
- Output Layer → Markdown, overlay PDF, JSON

##### Architectural Patterns & Principles
- **Layered Modular Design**: clearly separated I/O, processing stages, and output generation
- **Adapter Pattern**: pluggable I/O backends (HTTP, S3, local file) and model backends (LMDeploy, Transformers)
- **Pipeline Pattern**: sequential pre-proc → filter → inference → post-proc
- **Configuration-Driven**: behavior controlled via YAML and constants

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Presentation Layer
    subgraph "Presentation Layer"
        CLI["CLI Entrypoint\nparse.py"]:::presentation
        Gradio["Gradio Web UI\ndemo/demo_gradio.py"]:::presentation
    end

    %% Configuration & Orchestration
    subgraph "Configuration & Orchestration"
        ConfigYAML["model_configs.yaml"]:::config
        Constants["constants.py"]:::config
        Enums["enums.py"]:::config
        Exceptions["exceptions.py"]:::config
        ModelBlock["model_block_type.py"]:::config
        OCRContent["ocr_content_type.py"]:::config
        ContentConfig["make_content_config.py"]:::config
        SetupScript["setup.py"]:::config
        DownloadTool["download_model.py"]:::config
        Patcher["lmdeploy_patcher.py"]:::config
    end

    %% Data I/O Layer
    subgraph "Data I/O Layer"
        BaseIO["base.py"]:::io
        HTTPIO["http.py"]:::io
        S3IO["s3.py"]:::io
        BaseRW["base.py"]:::io
        FileRW["filebase.py"]:::io
        MultiBucketRW["multi_bucket_s3.py"]:::io
        S3RW["s3.py"]:::io
    end

    %% Processing Pipeline
    subgraph "Pre-processing" 
        ConstructPage["construct_page_dict.py"]:::preproc
        CutImage["cut_image.py"]:::preproc
        DetectBBoxes["ocr_detect_all_bboxes.py"]:::preproc
        MergeDicts["ocr_dict_merge.py"]:::preproc
        ModifySpan["ocr_span_list_modify.py"]:::preproc
        RemoveOverlap["remove_bbox_overlap.py"]:::preproc
    end

    subgraph "Filtering"
        Classify["pdf_classify_by_type.py"]:::filter
        MetaScan["pdf_meta_scan.py"]:::filter
    end

    subgraph "Model Inference"
        ModelList["model_list.py"]:::model
        ModelInit["model_init.py"]:::model
        CustomModel["custom_model.py"]:::model
        MagicModel["magic_model.py"]:::model
        BatchLLM["batch_analyze_llm.py"]:::model
        DocCustomLLM["doc_analyze_by_custom_model_llm.py"]:::model
        LLMPipes["pipes_llm.py"]:::model
        LLMModels["models_llm.py"]:::model
        CoreParse["pdf_parse_union_core_v2_llm.py"]:::model
        DocLayoutYOLO["DocLayoutYOLO.py"]:::model
        XYCut["xycut.py"]:::model
        HelperXY["helpers.py"]:::model
    end

    subgraph "Post-processing"
        ParaSplit["para_split_v3.py"]:::postproc
    end

    %% Output Generation
    subgraph "Output Generation"
        OCR2MD["ocr_mkcontent.py"]:::output
        DrawBBox["draw_bbox.py"]:::output
        JSONCompress["json_compressor.py"]:::output
    end

    %% Utilities & Shared Libraries
    subgraph "Utilities & Shared Libs"
        Commons["commons.py"]:::util
        ConfigReader["config_reader.py"]:::util
        CoordTransform["coordinate_transform.py"]:::util
        BoxBase["boxbase.py"]:::util
        PathUtils["path_utils.py"]:::util
        SafeFilename["safe_filename.py"]:::util
        PDFImageTools["pdf_image_tools.py"]:::util
        PDFCheck["pdf_check.py"]:::util
        MarkdownUtils["markdown_utils.py"]:::util
        LocalMath["local_math.py"]:::util
        Version["version.py"]:::util
        HashUtils["hash_utils.py"]:::util
        CleanMemory["clean_memory.py"]:::util
        LanguageDetect["language.py"]:::util
    end

    %% External Resources
    HF["HuggingFace / ModelScope"]:::external
    LangModel["lid.176.ftz"]:::external
    HTTPIn["HTTP Endpoint"]:::external
    S3Bucket["S3 Bucket"]:::external

    %% Data Flow
    CLI -->|uses| ConfigYAML
    CLI -->|reads/writes| BaseIO
    Gradio -->|uses| ConfigYAML
    Gradio -->|reads/writes| BaseIO

    ConfigYAML -->|configures| BaseIO
    ConfigYAML -->|configures| ModelList

    BaseIO --> ConstructPage
    ConstructPage --> CutImage --> DetectBBoxes --> MergeDicts --> ModifySpan --> RemoveOverlap
    RemoveOverlap --> Classify --> MetaScan
    MetaScan --> ModelInit --> ModelList --> CustomModel --> MagicModel
    MagicModel --> BatchLLM --> DocCustomLLM --> CoreParse
    CoreParse --> DocLayoutYOLO --> XYCut --> HelperXY
    HelperXY --> ParaSplit
    ParaSplit --> OCR2MD --> DrawBBox --> JSONCompress

    HF -->|provides weights| DownloadTool -->|populates| ConfigYAML
    LangModel -->|used by| LanguageDetect
    HTTPIn --> HTTPIO --> BaseIO
    S3Bucket --> S3IO --> BaseIO

    %% Click Events
    click CLI "https://github.com/yuliang-liu/monkeyocr/blob/main/parse.py"
    click Gradio "https://github.com/yuliang-liu/monkeyocr/blob/main/demo/demo_gradio.py"
    click ConfigYAML "https://github.com/yuliang-liu/monkeyocr/blob/main/model_configs.yaml"
    click Constants "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/config/constants.py"
    click Enums "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/config/enums.py"
    click Exceptions "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/config/exceptions.py"
    click ModelBlock "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/config/model_block_type.py"
    click OCRContent "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/config/ocr_content_type.py"
    click ContentConfig "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/config/make_content_config.py"
    click SetupScript "https://github.com/yuliang-liu/monkeyocr/blob/main/setup.py"
    click DownloadTool "https://github.com/yuliang-liu/monkeyocr/blob/main/tools/download_model.py"
    click Patcher "https://github.com/yuliang-liu/monkeyocr/blob/main/tools/lmdeploy_patcher.py"
    click BaseIO "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/io/base.py"
    click HTTPIO "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/io/http.py"
    click S3IO "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/io/s3.py"
    click BaseRW "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/data_reader_writer/base.py"
    click FileRW "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/data_reader_writer/filebase.py"
    click MultiBucketRW "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/data_reader_writer/multi_bucket_s3.py"
    click S3RW "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/data/data_reader_writer/s3.py"
    click ConstructPage "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pre_proc/construct_page_dict.py"
    click CutImage "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pre_proc/cut_image.py"
    click DetectBBoxes "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pre_proc/ocr_detect_all_bboxes.py"
    click MergeDicts "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pre_proc/ocr_dict_merge.py"
    click ModifySpan "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pre_proc/ocr_span_list_modify.py"
    click RemoveOverlap "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pre_proc/remove_bbox_overlap.py"
    click Classify "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/filter/pdf_classify_by_type.py"
    click MetaScan "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/filter/pdf_meta_scan.py"
    click ModelList "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/model_list.py"
    click ModelInit "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/sub_modules/model_init.py"
    click CustomModel "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/custom_model.py"
    click MagicModel "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/magic_model.py"
    click BatchLLM "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/batch_analyze_llm.py"
    click DocCustomLLM "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/doc_analyze_by_custom_model_llm.py"
    click LLMPipes "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/operators/pipes_llm.py"
    click LLMModels "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/operators/models_llm.py"
    click CoreParse "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/pdf_parse_union_core_v2_llm.py"
    click DocLayoutYOLO "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/sub_modules/layout/doclayout_yolo/DocLayoutYOLO.py"
    click XYCut "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/sub_modules/reading_oreder/layoutreader/xycut.py"
    click HelperXY "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/model/sub_modules/reading_oreder/layoutreader/helpers.py"
    click ParaSplit "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/post_proc/para_split_v3.py"
    click OCR2MD "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/dict2md/ocr_mkcontent.py"
    click DrawBBox "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/libs/draw_bbox.py"
    click JSONCompress "https://github.com/yuliang-liu/monkeyocr/blob/main/magic_pdf/libs/json_compressor.py"

    %% Styles
    classDef presentation fill:#FFE599,stroke:#DDBE84,stroke-width:1px
    classDef config fill:#D5A6BD,stroke:#B07AA1,stroke-width:1px
    classDef io fill:#C9DAF8,stroke:#6D9EEB,stroke-width:1px
    classDef preproc fill:#B6D7A8,stroke:#93C47D,stroke-width:1px
    classDef filter fill:#FFD966,stroke:#E69138,stroke-width:1px
    classDef model fill:#F4CCCC,stroke:#D9534F,stroke-width:1px
    classDef postproc fill:#A4C2F4,stroke:#6D9EEB,stroke-width:1px
    classDef output fill:#EAD1DC,stroke:#C27BA0,stroke-width:1px
    classDef util fill:#D9D2E9,stroke:#8E7CC3,stroke-width:1px
    classDef external fill:#F9CB9C,stroke:#B45F06,stroke-width:1px
```
