marker README

The project's README from github.com/datalab-to/marker. As one markdown file: README.md.

Datalab Logo

Datalab

State of the Art models for Document Intelligence

Code License Model License Discord

Homepage Docs Public Playground


Marker

Marker converts documents to markdown, JSON, chunks, and HTML quickly and accurately.

Try Datalab's Managed Platform

Our managed platform runs a version of our latest open source model, Chandra — higher accuracy than Marker, with zero data retention by default, SOC 2 Type 2, and custom BAAs.

If you have high volume workloads, we offer a batch processing service that has processed 1B+ pages per week — we manage the infrastructure so your workloads finish on time.

Get started with $5 in free credits — sign up.

Performance

We measure marker on olmocr-bench, a third-party benchmark of 1,403 PDFs with tests covering math, tables, multi-column layout, scans, and hard edge cases. Balanced mode scores 76.0% overall — 83.5% on born-digital PDFs — ahead of MinerU and docling and within range of much larger VLMs, while fast mode runs the layout + text-layer path far cheaper (and a no-OCR mode goes faster still). Scores are the olmocr-bench overall (macro-average across the 8 categories).

See below for the full per-category scores, the competitive comparison, and instructions on how to run your own benchmarks.

Hybrid Mode

For the highest accuracy, pass the --use_llm flag to use an LLM alongside marker. This will do things like merge tables across pages, handle inline math, format tables properly, and extract values from forms. It works with Gemini, Claude, OpenAI-compatible, Azure, Vertex, OpenRouter, or Ollama models. By default, it uses gemini-3.5-flash. See below for details.

Examples

PDF File type Markdown JSON
Think Python Textbook View View
Switch Transformers arXiv paper View View
Multi-column CNN arXiv paper View View

Commercial usage

Our code is licensed under Apache 2.0 — free to use, including commercially. Our model weights use a modified AI Pubs Open Rail-M license (free for research, personal use, and startups under $5M funding/revenue). For commercial use of the model weights beyond that, visit our pricing page here.

Community

Discord is where we discuss future development.

Installation

You'll need python 3.10+ and PyTorch.

Install with:

pip install marker-pdf

If you want to use marker on documents other than PDFs, you will need to install additional dependencies with:

pip install marker-pdf[full]

Inference backend prerequisites

Surya auto-spawns the server on first use, and you need vllm (NVIDIA GPU) or llama.cpp (CPU / Apple Silicon):

Usage

First, some configuration:

Interactive App

I've included a streamlit app that lets you interactively try marker with some basic options. Run it with:

pip install -U streamlit streamlit-ace
marker_gui

Convert a single file

marker_single /path/to/file.pdf

You can pass in PDFs or images.

Options:

OCR runs through the surya VLM, which is multilingual - see the surya README for details. If you don't need OCR, marker can work with any language.

Convert multiple files

marker /path/to/input/folder

Batch sizing cheat sheet (e.g. 1000 docs)

Use from python

See the PdfConverter class at marker/converters/pdf.py function for additional arguments that can be passed.

from marker.converters.pdf import PdfConverter
from marker.models import create_model_dict
from marker.output import text_from_rendered

converter = PdfConverter(
    artifact_dict=create_model_dict(),
)
rendered = converter("FILEPATH")
text, _, images = text_from_rendered(rendered)

rendered will be a pydantic basemodel with different properties depending on the output type requested. With markdown output (default), you'll have the properties markdown, metadata, and images. For json output, you'll have children, block_type, and metadata.

Custom configuration

You can pass configuration using the ConfigParser. To see all available options, do marker_single --help.

from marker.converters.pdf import PdfConverter
from marker.models import create_model_dict
from marker.config.parser import ConfigParser

config = {
    "output_format": "json",
    "ADDITIONAL_KEY": "VALUE"
}
config_parser = ConfigParser(config)

converter = PdfConverter(
    config=config_parser.generate_config_dict(),
    artifact_dict=create_model_dict(),
    processor_list=config_parser.get_processors(),
    renderer=config_parser.get_renderer(),
    llm_service=config_parser.get_llm_service()
)
rendered = converter("FILEPATH")

Extract blocks

Each document consists of one or more pages. Pages contain blocks, which can themselves contain other blocks. It's possible to programmatically manipulate these blocks.

Here's an example of extracting all forms from a document:

from marker.converters.pdf import PdfConverter
from marker.models import create_model_dict
from marker.schema import BlockTypes

converter = PdfConverter(
    artifact_dict=create_model_dict(),
)
document = converter.build_document("FILEPATH")
forms = document.contained_blocks((BlockTypes.Form,))

Look at the processors for more examples of extracting and manipulating blocks.

Other converters

You can also use other converters that define different conversion pipelines:

Extract tables

The TableConverter will only convert and extract tables:

from marker.converters.table import TableConverter
from marker.models import create_model_dict
from marker.output import text_from_rendered

converter = TableConverter(
    artifact_dict=create_model_dict(),
)
rendered = converter("FILEPATH")
text, _, images = text_from_rendered(rendered)

This takes all the same configuration as the PdfConverter. You can specify the configuration force_layout_block=Table to avoid layout detection and instead assume every page is a table. Tables are emitted as HTML (<table>) blocks; output_format=json gives you the table blocks with their page bounding boxes.

You can also run this via the CLI with

marker_single FILENAME --use_llm --force_layout_block Table --converter_cls marker.converters.table.TableConverter --output_format json

OCR Only

If you only want to run OCR, you can also do that through the OCRConverter. Set --keep_chars to keep individual characters and bounding boxes (digital PDFs only - pages that go through the VLM return block-level HTML without character boxes).

from marker.converters.ocr import OCRConverter
from marker.models import create_model_dict

converter = OCRConverter(
    artifact_dict=create_model_dict(),
)
rendered = converter("FILEPATH")

This takes all the same configuration as the PdfConverter.

You can also run this via the CLI with

marker_single FILENAME --converter_cls marker.converters.ocr.OCRConverter

Output Formats

Markdown

Markdown output will include:

HTML

HTML output is similar to markdown output:

JSON

JSON output will be organized in a tree-like structure, with the leaf nodes being blocks. Examples of leaf nodes are a single list item, a paragraph of text, or an image.

The output will be a list, with each list item representing a page. Each page is considered a block in the internal marker schema. There are different types of blocks to represent different elements.

Pages have the keys:

The child blocks have two additional keys:

Note that child blocks of pages can have their own children as well (a tree structure).

{
      "id": "/page/10/Page/366",
      "block_type": "Page",
      "html": "<content-ref src='/page/10/SectionHeader/0'></content-ref><content-ref src='/page/10/SectionHeader/1'></content-ref><content-ref src='/page/10/Text/2'></content-ref><content-ref src='/page/10/Text/3'></content-ref><content-ref src='/page/10/Figure/4'></content-ref><content-ref src='/page/10/SectionHeader/5'></content-ref><content-ref src='/page/10/SectionHeader/6'></content-ref><content-ref src='/page/10/TextInlineMath/7'></content-ref><content-ref src='/page/10/TextInlineMath/8'></content-ref><content-ref src='/page/10/Table/9'></content-ref><content-ref src='/page/10/SectionHeader/10'></content-ref><content-ref src='/page/10/Text/11'></content-ref>",
      "polygon": [[0.0, 0.0], [612.0, 0.0], [612.0, 792.0], [0.0, 792.0]],
      "children": [
        {
          "id": "/page/10/SectionHeader/0",
          "block_type": "SectionHea

marker (datalab-to/marker)

Searching Database…

40.5K ·GitHub
Что это такое?Marker — это инструмент для конвертации документов, который быстро и точно превращает PDF (и другие типы документов) в Markdown, JSON, HTML или вывод, разбитый на фрагменты (chunks), попутно извлекая таблицы, формулы, формы и изображения.
Это библиотека Python, консольный инструмент или и то, и другое?Оба варианта: это библиотека на Python с классами-конвертерами PdfConverter и TableConverter, а также команды marker_single и marker и демонстрационное приложение на Streamlit для интерактивной проверки.
Как его установить и запустить?Установите через pip после настройки Python 3.10+ и PyTorch, затем запустите marker_single для одного файла или marker для папки — так выполняется пакетная конвертация. Для форматов, отличных от PDF, например DOCX или PPTX, нужно дополнительно установить зависимости.
В чём компромисс между быстрым и сбалансированным режимом?Сбалансированный режим (по умолчанию на GPU) использует модель surya VLM для разметки макета и заново распознаёт через OCR любую страницу, текст которой выглядит плохо, — так достигается максимальное качество. Быстрый режим (по умолчанию на CPU/MPS) использует более лёгкий детектор макета и минимизирует обращения к VLM; взамен он немного теряет в точности на сканированных или искажённых страницах, зато работает быстрее.
Могу ли я бесплатно использовать веса модели в коммерческих целях?Код распространяется по лицензии Apache 2.0 и доступен для любого использования, включая коммерческое. А веса модели лицензированы по изменённой лицензии AI Pubs Open Rail-M, которая бесплатна только для исследований, личного использования и стартапов с объёмом финансирования или выручки менее 5 млн долларов. При более высоких показателях нужна платная лицензия.
Какие провайдеры LLM могут повысить точность?Флаг --usellm позволяет marker обращаться к моделям Gemini, Claude, эндпоинтам, совместимым с OpenAI, а также к Azure, Vertex, OpenRouter или Ollama. Это помогает объединять таблицы на разных страницах, исправлять встроенные формулы и извлекать значения из форм.
Какие форматы, кроме PDF, можно конвертировать?Кроме PDF, он также работает с изображениями, PPTX, DOCX, XLSX, HTML и EPUB. Но для форматов, отличных от PDF, нужно дополнительно установить зависимости.
Насколько точен Marker по сравнению с другими инструментами для PDF?В тесте olmocr-bench из 1403 файлов PDF сбалансированный режим набирает 76,0% в целом и 83,5% на документах, изначально созданных в цифровом виде. Это выше результатов MinerU и docling и сопоставимо с гораздо более крупными vision-language моделями.
Можно ли извлечь из документа только таблицы?Да, конвейер TableConverter только находит и конвертирует таблицы, выводя их в виде блоков HTML (или JSON с координатами рамок на страницах) через CLI или Python API.
Creator
datalab-to
Size
20.5 MB
Stars
40.5K
Age
2y
Commits · 90 Days