1055 lines
40 KiB
Python
1055 lines
40 KiB
Python
# SPDX-FileCopyrightText: The Docling Contributors
|
|
# SPDX-License-Identifier: MIT
|
|
|
|
import logging
|
|
import sys
|
|
import threading
|
|
import time
|
|
import warnings
|
|
from collections.abc import Iterable, Iterator
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from datetime import datetime
|
|
from functools import partial
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
from typing import Optional, Type, Union
|
|
|
|
from docling_core.types.doc.page import TextCellUnit
|
|
from pydantic import (
|
|
AnyHttpUrl,
|
|
ConfigDict,
|
|
Field,
|
|
TypeAdapter,
|
|
ValidationError,
|
|
model_validator,
|
|
validate_call,
|
|
)
|
|
from typing_extensions import Self
|
|
|
|
from docling.backend.abstract_backend import (
|
|
AbstractDocumentBackend,
|
|
)
|
|
from docling.backend.afp_backend import AfpDocumentBackend
|
|
from docling.backend.asciidoc_backend import AsciiDocBackend
|
|
from docling.backend.boxnote_backend import BoxNoteDocumentBackend
|
|
from docling.backend.csv_backend import CsvDocumentBackend
|
|
from docling.backend.docling_parse_backend import (
|
|
ThreadedDoclingParseDocumentBackend,
|
|
)
|
|
from docling.backend.ebcdic_backend import EbcdicDocumentBackend
|
|
from docling.backend.email_backend import EmailDocumentBackend
|
|
from docling.backend.epub_backend import EpubDocumentBackend
|
|
from docling.backend.html_backend import HTMLDocumentBackend
|
|
from docling.backend.image_backend import ImageDocumentBackend
|
|
from docling.backend.iwork_backend import (
|
|
IWorkKeynoteDocumentBackend,
|
|
IWorkNumbersDocumentBackend,
|
|
IWorkPagesDocumentBackend,
|
|
)
|
|
from docling.backend.json.docling_json_backend import DoclingJSONBackend
|
|
from docling.backend.latex_backend import LatexDocumentBackend
|
|
from docling.backend.md_backend import MarkdownDocumentBackend
|
|
from docling.backend.mets_gbs_backend import MetsGbsDocumentBackend
|
|
from docling.backend.msexcel_backend import MsExcelDocumentBackend
|
|
from docling.backend.mspowerpoint_backend import MsPowerpointDocumentBackend
|
|
from docling.backend.msword_backend import MsWordDocumentBackend
|
|
from docling.backend.noop_backend import NoOpBackend
|
|
from docling.backend.opendocument_backend import (
|
|
OdpDocumentBackend,
|
|
OdsDocumentBackend,
|
|
OdtDocumentBackend,
|
|
)
|
|
from docling.backend.webvtt_backend import WebVTTDocumentBackend
|
|
from docling.backend.xml.doclang_archive_backend import DocLangArchiveBackend
|
|
from docling.backend.xml.doclang_backend import DocLangDocumentBackend
|
|
from docling.backend.xml.jats_backend import JatsDocumentBackend
|
|
from docling.backend.xml.uspto_backend import PatentUsptoDocumentBackend
|
|
from docling.backend.xml.xbrl_backend import XBRLDocumentBackend
|
|
from docling.datamodel.backend_options import (
|
|
AsciiDocBackendOptions,
|
|
BackendOptions,
|
|
CsvBackendOptions,
|
|
DeclarativeBackendOptions,
|
|
EbcdicBackendOptions,
|
|
EmailBackendOptions,
|
|
EpubBackendOptions,
|
|
HTMLBackendOptions,
|
|
IWorkBackendOptions,
|
|
JatsBackendOptions,
|
|
LatexBackendOptions,
|
|
MarkdownBackendOptions,
|
|
MetsGbsBackendOptions,
|
|
MsWordBackendOptions,
|
|
PdfBackendOptions,
|
|
ThreadedDoclingParseBackendOptions,
|
|
XBRLBackendOptions,
|
|
)
|
|
from docling.datamodel.base_models import (
|
|
BaseFormatOption,
|
|
ConversionStatus,
|
|
DoclingComponentType,
|
|
DocumentStream,
|
|
ErrorItem,
|
|
FailureCategory,
|
|
HttpSource,
|
|
InputFormat,
|
|
)
|
|
from docling.datamodel.document import (
|
|
ConversionResult,
|
|
InputDocument,
|
|
_DocumentConversionInput,
|
|
build_invalid_input_errors,
|
|
get_input_rejection_cause,
|
|
)
|
|
from docling.datamodel.pipeline_options import (
|
|
ConvertPipelineOptions,
|
|
NativePdfPipelineOptions,
|
|
PipelineOptions,
|
|
)
|
|
from docling.datamodel.progress import (
|
|
ConversionPhase,
|
|
ProgressCallback,
|
|
ProgressReporter,
|
|
)
|
|
from docling.datamodel.settings import (
|
|
DEFAULT_PAGE_RANGE,
|
|
DocumentLimits,
|
|
PageRange,
|
|
settings,
|
|
)
|
|
from docling.exceptions import ConversionError
|
|
from docling.pipeline.asr_pipeline import AsrPipeline
|
|
from docling.pipeline.base_pipeline import BasePipeline
|
|
from docling.pipeline.native_pdf_pipeline import NativePdfPipeline
|
|
from docling.pipeline.simple_pipeline import SimplePipeline
|
|
from docling.pipeline.standard_pdf_pipeline import StandardPdfPipeline
|
|
from docling.pipeline.video_pipeline import VideoPipeline
|
|
from docling.utils.pipeline_cache import create_pipeline_options_hash
|
|
from docling.utils.progress import ProgressPrinter
|
|
from docling.utils.utils import chunkify
|
|
|
|
_log = logging.getLogger(__name__)
|
|
_PIPELINE_CACHE_LOCK = threading.Lock()
|
|
|
|
|
|
class FormatOption(BaseFormatOption):
|
|
pipeline_cls: Type[BasePipeline]
|
|
backend_options: Optional[BackendOptions] = None
|
|
|
|
def backend_options_for_input(
|
|
self, source: Path | str | DocumentStream
|
|
) -> BackendOptions | None:
|
|
return self.backend_options
|
|
|
|
@model_validator(mode="after")
|
|
def set_optional_field_default(self) -> Self:
|
|
if self.pipeline_options is None:
|
|
self.pipeline_options = self.pipeline_cls.get_default_options()
|
|
|
|
return self
|
|
|
|
|
|
class BoxNoteFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = BoxNoteDocumentBackend
|
|
|
|
|
|
class CsvFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = CsvDocumentBackend
|
|
backend_options: Optional[CsvBackendOptions] = None
|
|
|
|
|
|
class ExcelFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = MsExcelDocumentBackend
|
|
|
|
|
|
class WordFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = MsWordDocumentBackend
|
|
backend_options: Optional[MsWordBackendOptions] = None
|
|
|
|
|
|
class PowerpointFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = MsPowerpointDocumentBackend
|
|
|
|
|
|
class OdtFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = OdtDocumentBackend
|
|
|
|
|
|
class OdsFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = OdsDocumentBackend
|
|
|
|
|
|
class OdpFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = OdpDocumentBackend
|
|
|
|
|
|
class MarkdownFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = MarkdownDocumentBackend
|
|
backend_options: Optional[MarkdownBackendOptions] = None
|
|
|
|
def backend_options_for_input(
|
|
self, source: Path | str | DocumentStream
|
|
) -> MarkdownBackendOptions | None:
|
|
options = self.backend_options
|
|
if (
|
|
options is None
|
|
or options.source_uri is not None
|
|
or isinstance(source, DocumentStream)
|
|
):
|
|
return options
|
|
|
|
return MarkdownBackendOptions.model_validate(
|
|
{**options.model_dump(), "source_uri": source}
|
|
)
|
|
|
|
|
|
class AsciiDocFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = AsciiDocBackend
|
|
backend_options: AsciiDocBackendOptions | None = None
|
|
|
|
def backend_options_for_input(
|
|
self, source: Path | str | DocumentStream
|
|
) -> AsciiDocBackendOptions | None:
|
|
options = self.backend_options
|
|
if (
|
|
options is None
|
|
or options.source_uri is not None
|
|
or isinstance(source, DocumentStream)
|
|
):
|
|
return options
|
|
|
|
return AsciiDocBackendOptions.model_validate(
|
|
{**options.model_dump(), "source_uri": source}
|
|
)
|
|
|
|
|
|
class HTMLFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = HTMLDocumentBackend
|
|
backend_options: Optional[HTMLBackendOptions] = None
|
|
|
|
def backend_options_for_input(
|
|
self, source: Path | str | DocumentStream
|
|
) -> HTMLBackendOptions | None:
|
|
options = self.backend_options
|
|
if (
|
|
options is None
|
|
or options.source_uri is not None
|
|
or isinstance(source, DocumentStream)
|
|
):
|
|
return options
|
|
|
|
return HTMLBackendOptions.model_validate(
|
|
{**options.model_dump(), "source_uri": source}
|
|
)
|
|
|
|
|
|
class PatentUsptoFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[PatentUsptoDocumentBackend] = PatentUsptoDocumentBackend
|
|
|
|
|
|
class XMLJatsFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = JatsDocumentBackend
|
|
backend_options: Optional[JatsBackendOptions] = None
|
|
|
|
|
|
class XMLDocLangFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = DocLangDocumentBackend
|
|
|
|
|
|
class DclxFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = DocLangArchiveBackend
|
|
|
|
|
|
class DoclingJSONFormatOption(FormatOption):
|
|
"""Format option for DoclingDocument JSON input.
|
|
|
|
Image references pointing at local files are dropped from the input unless
|
|
``backend_options.enable_local_fetch`` is set.
|
|
"""
|
|
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = DoclingJSONBackend
|
|
backend_options: DeclarativeBackendOptions | None = None
|
|
|
|
|
|
class XBRLFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = XBRLDocumentBackend
|
|
backend_options: XBRLBackendOptions | None = None
|
|
|
|
|
|
class ImageFormatOption(FormatOption):
|
|
pipeline_cls: Type = StandardPdfPipeline
|
|
backend: Type[AbstractDocumentBackend] = ImageDocumentBackend
|
|
|
|
|
|
class PdfFormatOption(FormatOption):
|
|
pipeline_cls: Type = StandardPdfPipeline
|
|
backend: Type[AbstractDocumentBackend] = ThreadedDoclingParseDocumentBackend
|
|
backend_options: Optional[PdfBackendOptions] = None
|
|
|
|
|
|
class IWorkPagesFormatOption(FormatOption):
|
|
"""Format option for Apple Pages input."""
|
|
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = IWorkPagesDocumentBackend
|
|
backend_options: IWorkBackendOptions | None = None
|
|
|
|
|
|
class IWorkKeynoteFormatOption(FormatOption):
|
|
"""Format option for Apple Keynote input."""
|
|
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = IWorkKeynoteDocumentBackend
|
|
backend_options: IWorkBackendOptions | None = None
|
|
|
|
|
|
class IWorkNumbersFormatOption(FormatOption):
|
|
"""Format option for Apple Numbers input."""
|
|
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = IWorkNumbersDocumentBackend
|
|
backend_options: IWorkBackendOptions | None = None
|
|
|
|
|
|
class NativePdfFormatOption(PdfFormatOption):
|
|
"""PDF format option for the model-free `NativePdfPipeline`.
|
|
|
|
Defaults to the threaded docling-parse backend, configured from the pipeline
|
|
options: it parses with `parser_threads` threads, only decodes the embedded
|
|
bitmaps and only renders page images when the pipeline asks for them.
|
|
"""
|
|
|
|
pipeline_cls: Type = NativePdfPipeline
|
|
backend: Type[AbstractDocumentBackend] = ThreadedDoclingParseDocumentBackend
|
|
|
|
@model_validator(mode="after")
|
|
def configure_backend_options(self) -> Self:
|
|
if not isinstance(self.pipeline_options, NativePdfPipelineOptions):
|
|
return self
|
|
|
|
if self.backend_options is None:
|
|
backend_options = ThreadedDoclingParseBackendOptions(
|
|
parser_threads=self.pipeline_options.parser_threads,
|
|
include_bitmap_images=self.pipeline_options.generate_picture_images,
|
|
render_pages=self.pipeline_options.generate_page_images,
|
|
render_scale=self.pipeline_options.images_scale,
|
|
)
|
|
else:
|
|
backend_options = self.backend_options.model_copy(deep=True)
|
|
|
|
backend_options._materialize_char_cells = (
|
|
self.pipeline_options.text_cell_unit == TextCellUnit.CHAR
|
|
)
|
|
self.backend_options = backend_options
|
|
|
|
return self
|
|
|
|
|
|
class MetsGbsFormatOption(FormatOption):
|
|
pipeline_cls: Type = StandardPdfPipeline
|
|
backend: Type[AbstractDocumentBackend] = MetsGbsDocumentBackend
|
|
backend_options: MetsGbsBackendOptions | None = None
|
|
|
|
|
|
class AudioFormatOption(FormatOption):
|
|
pipeline_cls: Type = AsrPipeline
|
|
backend: Type[AbstractDocumentBackend] = NoOpBackend
|
|
|
|
|
|
class VideoFormatOption(FormatOption):
|
|
"""Format option for video input, processed via VideoPipeline."""
|
|
|
|
pipeline_cls: Type = VideoPipeline
|
|
backend: Type[AbstractDocumentBackend] = NoOpBackend
|
|
|
|
|
|
class LatexFormatOption(FormatOption):
|
|
"""Format options for LaTeX documents."""
|
|
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = LatexDocumentBackend
|
|
backend_options: Optional[LatexBackendOptions] = None
|
|
|
|
def backend_options_for_input(
|
|
self, source: Path | str | DocumentStream
|
|
) -> LatexBackendOptions | None:
|
|
"""Keep the location of a local ``str`` source.
|
|
|
|
A ``str`` source is read into a stream before it reaches the backend,
|
|
which then cannot resolve ``\\input``, ``\\include`` or
|
|
``\\includegraphics`` relative to the document. ``Path`` sources and
|
|
streams are passed on unchanged, and so are http(s) URLs, the same way
|
|
``resolve_source_to_stream`` tells them apart from local paths.
|
|
"""
|
|
options = self.backend_options
|
|
if not isinstance(source, str) or (
|
|
options is not None and options.source_uri is not None
|
|
):
|
|
return options
|
|
try:
|
|
TypeAdapter(AnyHttpUrl).validate_python(source)
|
|
except ValidationError:
|
|
base = options.model_dump() if options is not None else {}
|
|
return LatexBackendOptions.model_validate(
|
|
{**base, "source_uri": Path(source)}
|
|
)
|
|
return options
|
|
|
|
|
|
class EmailFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = EmailDocumentBackend
|
|
backend_options: Optional[EmailBackendOptions] = None
|
|
|
|
|
|
class EpubFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = EpubDocumentBackend
|
|
backend_options: EpubBackendOptions | None = None
|
|
|
|
|
|
class EbcdicFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = EbcdicDocumentBackend
|
|
backend_options: EbcdicBackendOptions | None = None
|
|
|
|
|
|
class AfpFormatOption(FormatOption):
|
|
pipeline_cls: Type = SimplePipeline
|
|
backend: Type[AbstractDocumentBackend] = AfpDocumentBackend
|
|
|
|
|
|
def _get_default_option(format: InputFormat) -> FormatOption:
|
|
format_to_default_options = {
|
|
InputFormat.CSV: CsvFormatOption(),
|
|
InputFormat.BOXNOTE: BoxNoteFormatOption(),
|
|
InputFormat.XLSX: ExcelFormatOption(),
|
|
InputFormat.XLS: ExcelFormatOption(),
|
|
InputFormat.DOCX: WordFormatOption(),
|
|
InputFormat.DOC: WordFormatOption(),
|
|
InputFormat.RTF: WordFormatOption(),
|
|
InputFormat.PPTX: PowerpointFormatOption(),
|
|
InputFormat.PPT: PowerpointFormatOption(),
|
|
InputFormat.ODT: OdtFormatOption(),
|
|
InputFormat.ODS: OdsFormatOption(),
|
|
InputFormat.ODP: OdpFormatOption(),
|
|
InputFormat.MD: MarkdownFormatOption(),
|
|
InputFormat.ASCIIDOC: AsciiDocFormatOption(),
|
|
InputFormat.HTML: HTMLFormatOption(),
|
|
InputFormat.MHTML: HTMLFormatOption(),
|
|
InputFormat.XML_USPTO: PatentUsptoFormatOption(),
|
|
InputFormat.XML_JATS: XMLJatsFormatOption(),
|
|
InputFormat.XML_DOCLANG: XMLDocLangFormatOption(),
|
|
InputFormat.DCLX: DclxFormatOption(),
|
|
InputFormat.XML_XBRL: XBRLFormatOption(),
|
|
InputFormat.METS_GBS: FormatOption(
|
|
pipeline_cls=StandardPdfPipeline, backend=MetsGbsDocumentBackend
|
|
),
|
|
InputFormat.IMAGE: ImageFormatOption(),
|
|
InputFormat.PDF: PdfFormatOption(),
|
|
InputFormat.JSON_DOCLING: DoclingJSONFormatOption(),
|
|
InputFormat.AUDIO: AudioFormatOption(),
|
|
InputFormat.VIDEO: VideoFormatOption(),
|
|
InputFormat.VTT: FormatOption(
|
|
pipeline_cls=SimplePipeline, backend=WebVTTDocumentBackend
|
|
),
|
|
InputFormat.LATEX: LatexFormatOption(),
|
|
InputFormat.EMAIL: EmailFormatOption(),
|
|
InputFormat.EPUB: EpubFormatOption(),
|
|
InputFormat.IWORK_PAGES: IWorkPagesFormatOption(),
|
|
InputFormat.IWORK_KEYNOTE: IWorkKeynoteFormatOption(),
|
|
InputFormat.IWORK_NUMBERS: IWorkNumbersFormatOption(),
|
|
InputFormat.EBCDIC: EbcdicFormatOption(),
|
|
InputFormat.AFP: AfpFormatOption(),
|
|
}
|
|
if (options := format_to_default_options.get(format)) is not None:
|
|
return options
|
|
else:
|
|
raise RuntimeError(f"No default options configured for {format}")
|
|
|
|
|
|
class DocumentConverter:
|
|
"""Convert documents of various input formats to Docling documents.
|
|
|
|
`DocumentConverter` is the main entry point for converting documents in Docling.
|
|
It handles various input formats (PDF, DOCX, PPTX, images, HTML, Markdown, etc.)
|
|
and provides both single-document and batch conversion capabilities.
|
|
|
|
The conversion methods return a `ConversionResult` instance for each document,
|
|
which wraps a `DoclingDocument` object if the conversion was successful, along
|
|
with metadata about the conversion process.
|
|
|
|
Attributes:
|
|
allowed_formats: Allowed input formats.
|
|
format_to_options: Mapping of formats to their options.
|
|
initialized_pipelines: Cache of initialized pipelines keyed by
|
|
(pipeline class, options hash).
|
|
"""
|
|
|
|
_default_download_filename = "file"
|
|
|
|
def __init__(
|
|
self,
|
|
allowed_formats: Optional[list[InputFormat]] = None,
|
|
format_options: Optional[dict[InputFormat, FormatOption]] = None,
|
|
progress_callback: Optional[ProgressCallback] = None,
|
|
show_progress: bool = False,
|
|
) -> None:
|
|
"""Initialize the converter based on format preferences.
|
|
|
|
Args:
|
|
allowed_formats: List of allowed input formats. By default, any
|
|
format supported by Docling is allowed.
|
|
format_options: Dictionary of format-specific options.
|
|
progress_callback: Optional callable that receives progress events
|
|
(see `docling.datamodel.progress`) while documents convert:
|
|
document start and end for every input, pipeline phases, and
|
|
page and enrichment-item counts where they apply. It receives
|
|
the events of every call; `convert` and `convert_all` also take
|
|
a callback for one call. Exceptions it raises are logged and
|
|
ignored. With
|
|
`settings.perf.doc_batch_concurrency > 1` it is called from
|
|
several threads at once and must be thread-safe.
|
|
show_progress: Print progress to stderr with the built-in
|
|
`ProgressPrinter`, without writing a callback. Can be combined
|
|
with `progress_callback`.
|
|
|
|
Examples:
|
|
Create a converter with default settings (all formats allowed):
|
|
|
|
>>> converter = DocumentConverter()
|
|
|
|
Allow only PDF and DOCX formats:
|
|
|
|
>>> from docling.datamodel.base_models import InputFormat
|
|
>>> converter = DocumentConverter(
|
|
... allowed_formats=[InputFormat.PDF, InputFormat.DOCX]
|
|
... )
|
|
|
|
Customize pipeline options for PDF:
|
|
|
|
>>> from docling.datamodel.pipeline_options import PdfPipelineOptions
|
|
>>> converter = DocumentConverter(
|
|
... format_options={
|
|
... InputFormat.PDF: PdfFormatOption(
|
|
... pipeline_options=PdfPipelineOptions()
|
|
... ),
|
|
... }
|
|
... )
|
|
|
|
Print page and enrichment progress to stderr:
|
|
|
|
>>> converter = DocumentConverter(show_progress=True)
|
|
"""
|
|
self.allowed_formats: list[InputFormat] = (
|
|
allowed_formats if allowed_formats is not None else list(InputFormat)
|
|
)
|
|
self.progress_callback: Optional[ProgressCallback] = progress_callback
|
|
self.progress_printer: Optional[ProgressPrinter] = (
|
|
ProgressPrinter() if show_progress else None
|
|
)
|
|
|
|
# Normalize format options: ensure IMAGE format uses ImageDocumentBackend
|
|
# for backward compatibility (old code might use PdfFormatOption or other backends for images)
|
|
normalized_format_options: dict[InputFormat, FormatOption] = {}
|
|
if format_options:
|
|
for format, option in format_options.items():
|
|
if (
|
|
format == InputFormat.IMAGE
|
|
and option.backend is not ImageDocumentBackend
|
|
):
|
|
warnings.warn(
|
|
f"Using {option.backend.__name__} for InputFormat.IMAGE is deprecated. "
|
|
"Images should use ImageDocumentBackend via ImageFormatOption. "
|
|
"Automatically correcting the backend, please update your code to avoid this warning.",
|
|
DeprecationWarning,
|
|
stacklevel=2,
|
|
)
|
|
# Convert to ImageFormatOption while preserving pipeline and backend options
|
|
normalized_format_options[format] = ImageFormatOption(
|
|
pipeline_cls=option.pipeline_cls,
|
|
pipeline_options=option.pipeline_options,
|
|
backend_options=option.backend_options,
|
|
)
|
|
else:
|
|
normalized_format_options[format] = option
|
|
|
|
self.format_to_options: dict[InputFormat, FormatOption] = {
|
|
format: (
|
|
_get_default_option(format=format)
|
|
if (custom_option := normalized_format_options.get(format)) is None
|
|
else custom_option
|
|
)
|
|
for format in self.allowed_formats
|
|
}
|
|
self.initialized_pipelines: dict[
|
|
tuple[Type[BasePipeline], str], BasePipeline
|
|
] = {}
|
|
|
|
def _get_initialized_pipelines(
|
|
self,
|
|
) -> dict[tuple[Type[BasePipeline], str], BasePipeline]:
|
|
return self.initialized_pipelines
|
|
|
|
def initialize_pipeline(self, format: InputFormat):
|
|
"""Initialize the conversion pipeline for the selected format.
|
|
|
|
Args:
|
|
format: The input format for which to initialize the pipeline.
|
|
|
|
Raises:
|
|
ConversionError: If no pipeline could be initialized for the
|
|
given format.
|
|
RuntimeError: If `artifacts_path` is set in
|
|
`docling.datamodel.settings.settings` when required by
|
|
the pipeline, but points to a non-directory file.
|
|
FileNotFoundError: If local model files are not found.
|
|
"""
|
|
pipeline = self._get_pipeline(doc_format=format)
|
|
if pipeline is None:
|
|
raise ConversionError(
|
|
f"No pipeline could be initialized for format {format}"
|
|
)
|
|
|
|
@validate_call(config=ConfigDict(strict=True))
|
|
def convert(
|
|
self,
|
|
source: Union[Path, str, DocumentStream, HttpSource], # TODO review naming
|
|
headers: Optional[dict[str, str]] = None,
|
|
raises_on_error: bool = True,
|
|
max_num_pages: int = sys.maxsize,
|
|
max_file_size: int = sys.maxsize,
|
|
page_range: PageRange = DEFAULT_PAGE_RANGE,
|
|
progress_callback: Optional[ProgressCallback] = None,
|
|
) -> ConversionResult:
|
|
"""Convert one document fetched from a file path, URL, or DocumentStream.
|
|
|
|
Note: If the document content is given as a string (Markdown or HTML
|
|
content), use the `convert_string` method.
|
|
|
|
Args:
|
|
source: Source of input document given as file path, URL,
|
|
DocumentStream, or HttpSource (a URL bundled with its own headers).
|
|
headers: Optional headers given as a dictionary of string key-value pairs,
|
|
in case of URL input source. Ignored for HttpSource inputs, which
|
|
carry their own headers (these override the batch headers per key).
|
|
raises_on_error: Whether to raise an error on the first conversion failure.
|
|
If False, errors are captured in the ConversionResult objects.
|
|
max_num_pages: Maximum number of pages accepted per document.
|
|
Documents exceeding this number will not be converted.
|
|
max_file_size: Maximum file size to convert.
|
|
page_range: Range of pages to convert.
|
|
progress_callback: Optional callable that receives the progress
|
|
events of this call only, on top of the converter-level
|
|
`progress_callback`. Use it when one converter serves several
|
|
callers, e.g. the tasks of a service.
|
|
|
|
Returns:
|
|
The conversion result, which contains a `DoclingDocument` in the `document`
|
|
attribute, and metadata about the conversion process.
|
|
|
|
Raises:
|
|
ConversionError: An error occurred during conversion.
|
|
|
|
Examples:
|
|
Convert a local PDF file:
|
|
|
|
>>> from pathlib import Path
|
|
>>> converter = DocumentConverter()
|
|
>>> result = converter.convert("path/to/document.pdf")
|
|
>>> print(result.document.export_to_markdown())
|
|
|
|
Convert a document from a URL:
|
|
|
|
>>> result = converter.convert("https://example.com/paper.pdf")
|
|
|
|
Convert from an in-memory stream:
|
|
|
|
>>> from io import BytesIO
|
|
>>> from docling.datamodel.base_models import DocumentStream
|
|
>>> buf = BytesIO(b"<html><body>Hello</body></html>")
|
|
>>> stream = DocumentStream(name="page.html", stream=buf)
|
|
>>> result = converter.convert(stream)
|
|
"""
|
|
all_res = self.convert_all(
|
|
source=[source],
|
|
raises_on_error=raises_on_error,
|
|
max_num_pages=max_num_pages,
|
|
max_file_size=max_file_size,
|
|
headers=headers,
|
|
page_range=page_range,
|
|
progress_callback=progress_callback,
|
|
)
|
|
return next(all_res)
|
|
|
|
@validate_call(config=ConfigDict(strict=True))
|
|
def convert_all(
|
|
self,
|
|
source: Iterable[
|
|
Union[Path, str, DocumentStream, HttpSource]
|
|
], # TODO review naming
|
|
headers: Optional[dict[str, str]] = None,
|
|
raises_on_error: bool = True,
|
|
max_num_pages: int = sys.maxsize,
|
|
max_file_size: int = sys.maxsize,
|
|
page_range: PageRange = DEFAULT_PAGE_RANGE,
|
|
progress_callback: Optional[ProgressCallback] = None,
|
|
) -> Iterator[ConversionResult]:
|
|
"""Convert multiple documents from file paths, URLs, or DocumentStreams.
|
|
|
|
Args:
|
|
source: Source of input documents given as an iterable of file paths, URLs,
|
|
DocumentStreams, or HttpSources (a URL bundled with its own headers).
|
|
headers: Optional headers given as a (single) dictionary of string
|
|
key-value pairs, in case of URL input source. Per-source HttpSource
|
|
headers override these (merged per key) for that source only.
|
|
raises_on_error: Whether to raise an error on the first conversion failure.
|
|
max_num_pages: Maximum number of pages accepted per document.
|
|
Documents exceeding this number will not be converted.
|
|
max_file_size: Maximum file size in bytes. Documents exceeding this
|
|
limit will be skipped.
|
|
page_range: Range of pages to convert in each document.
|
|
progress_callback: Optional callable that receives the progress
|
|
events of this call only, on top of the converter-level
|
|
`progress_callback`. Use it when one converter serves several
|
|
callers, e.g. the tasks of a service.
|
|
|
|
Yields:
|
|
The conversion results, each containing a `DoclingDocument` in the
|
|
`document` attribute and metadata about the conversion process.
|
|
|
|
Raises:
|
|
ConversionError: An error occurred during conversion.
|
|
|
|
Examples:
|
|
Convert a batch of local files:
|
|
|
|
>>> from pathlib import Path
|
|
>>> converter = DocumentConverter()
|
|
>>> paths = list(Path("docs/").glob("*.pdf"))
|
|
>>> for result in converter.convert_all(paths):
|
|
... print(result.document.export_to_markdown()[:100])
|
|
|
|
Convert with a file size limit of 20 MB:
|
|
|
|
>>> results = converter.convert_all(
|
|
... paths, max_file_size=20 * 1024 * 1024
|
|
... )
|
|
"""
|
|
limits = DocumentLimits(
|
|
max_num_pages=max_num_pages,
|
|
max_file_size=max_file_size,
|
|
page_range=page_range,
|
|
)
|
|
conv_input = _DocumentConversionInput(
|
|
path_or_stream_iterator=source, limits=limits, headers=headers
|
|
)
|
|
conv_res_iter = self._convert(
|
|
conv_input,
|
|
raises_on_error=raises_on_error,
|
|
progress_callback=progress_callback,
|
|
)
|
|
|
|
had_result = False
|
|
for conv_res in conv_res_iter:
|
|
had_result = True
|
|
if raises_on_error and conv_res.status not in {
|
|
ConversionStatus.SUCCESS,
|
|
ConversionStatus.PARTIAL_SUCCESS,
|
|
}:
|
|
error_details = ""
|
|
if conv_res.errors:
|
|
error_messages = [err.error_message for err in conv_res.errors]
|
|
error_details = f" Errors: {'; '.join(error_messages)}"
|
|
# Chain the underlying exception (when one was captured during
|
|
# input construction) so callers can classify failures via
|
|
# ``__cause__`` — e.g. an encrypted PDF surfaces the original
|
|
# ``PdfiumError``. See issue #1920.
|
|
raise ConversionError(
|
|
f"Conversion failed for: {conv_res.input.file} with status: "
|
|
f"{conv_res.status.value}.{error_details}"
|
|
) from get_input_rejection_cause(conv_res.input)
|
|
else:
|
|
yield conv_res
|
|
|
|
if not had_result and raises_on_error:
|
|
raise ConversionError(
|
|
"Conversion failed because the provided file has no recognizable "
|
|
"format or it wasn't in the list of allowed formats."
|
|
)
|
|
|
|
@validate_call(config=ConfigDict(strict=True))
|
|
def convert_string(
|
|
self,
|
|
content: str,
|
|
format: InputFormat,
|
|
name: Optional[str] = None,
|
|
progress_callback: Optional[ProgressCallback] = None,
|
|
) -> ConversionResult:
|
|
"""Convert a document given as a string using the specified format.
|
|
|
|
Only Markdown (`InputFormat.MD`), HTML (`InputFormat.HTML`), and DocLang
|
|
(`InputFormat.XML_DOCLANG`) formats are supported. The content is wrapped
|
|
in a `DocumentStream` and passed to the main conversion pipeline.
|
|
|
|
Args:
|
|
content: The document content as a string.
|
|
format: The format of the input content.
|
|
name: The filename to associate with the document. If not provided, a
|
|
timestamp-based name is generated. The appropriate file extension is
|
|
appended if missing.
|
|
progress_callback: Optional callable that receives the progress
|
|
events of this call only, on top of the converter-level
|
|
`progress_callback`. Use it when one converter serves several
|
|
callers, e.g. the tasks of a service.
|
|
|
|
Returns:
|
|
The conversion result, which contains a `DoclingDocument` in the `document`
|
|
attribute, and metadata about the conversion process.
|
|
|
|
Raises:
|
|
ValueError: If format is not supported by `convert_string`.
|
|
ConversionError: An error occurred during conversion.
|
|
|
|
Examples:
|
|
Convert a Markdown string:
|
|
|
|
>>> from docling.datamodel.base_models import InputFormat
|
|
>>> converter = DocumentConverter()
|
|
>>> result = converter.convert_string(
|
|
... "# Title\nSome text.", format=InputFormat.MD
|
|
... )
|
|
>>> print(result.document.export_to_markdown())
|
|
|
|
Convert an HTML string:
|
|
|
|
>>> result = converter.convert_string(
|
|
... "<h1>Title</h1><p>Some text.</p>",
|
|
... format=InputFormat.HTML,
|
|
... name="my_page",
|
|
... )
|
|
"""
|
|
name = name or datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
|
|
if format == InputFormat.MD:
|
|
if not name.endswith(".md"):
|
|
name += ".md"
|
|
|
|
buff = BytesIO(content.encode("utf-8"))
|
|
doc_stream = DocumentStream(name=name, stream=buff)
|
|
|
|
return self.convert(doc_stream, progress_callback=progress_callback)
|
|
elif format == InputFormat.HTML:
|
|
if not name.endswith(".html"):
|
|
name += ".html"
|
|
|
|
buff = BytesIO(content.encode("utf-8"))
|
|
doc_stream = DocumentStream(name=name, stream=buff)
|
|
|
|
return self.convert(doc_stream, progress_callback=progress_callback)
|
|
elif format == InputFormat.XML_DOCLANG:
|
|
if not name.endswith((".dclg", ".dclg.xml")):
|
|
name += ".dclg.xml"
|
|
|
|
buff = BytesIO(content.encode("utf-8"))
|
|
doc_stream = DocumentStream(name=name, stream=buff)
|
|
|
|
return self.convert(doc_stream, progress_callback=progress_callback)
|
|
else:
|
|
raise ValueError(f"format {format} is not supported in `convert_string`")
|
|
|
|
def _convert(
|
|
self,
|
|
conv_input: _DocumentConversionInput,
|
|
raises_on_error: bool,
|
|
progress_callback: Optional[ProgressCallback] = None,
|
|
) -> Iterator[ConversionResult]:
|
|
start_time = time.monotonic()
|
|
|
|
for input_batch in chunkify(
|
|
enumerate(conv_input.docs(self.format_to_options), start=1),
|
|
settings.perf.doc_batch_size, # pass format_options
|
|
):
|
|
_log.info("Going to convert document batch...")
|
|
process_func = partial(
|
|
self._process_indexed_document,
|
|
raises_on_error=raises_on_error,
|
|
progress_callback=progress_callback,
|
|
)
|
|
|
|
if (
|
|
settings.perf.doc_batch_concurrency > 1
|
|
and settings.perf.doc_batch_size > 1
|
|
):
|
|
with ThreadPoolExecutor(
|
|
max_workers=settings.perf.doc_batch_concurrency
|
|
) as pool:
|
|
for item in pool.map(
|
|
process_func,
|
|
input_batch,
|
|
):
|
|
yield item
|
|
else:
|
|
for item in map(
|
|
process_func,
|
|
input_batch,
|
|
):
|
|
elapsed = time.monotonic() - start_time
|
|
start_time = time.monotonic()
|
|
_log.info(
|
|
f"Finished converting document {item.input.file.name} in {elapsed:.2f} sec."
|
|
)
|
|
yield item
|
|
|
|
def _get_pipeline(self, doc_format: InputFormat) -> Optional[BasePipeline]:
|
|
"""Retrieve or initialize a pipeline, reusing instances based on class and options."""
|
|
fopt = self.format_to_options.get(doc_format)
|
|
|
|
if fopt is None or fopt.pipeline_options is None:
|
|
return None
|
|
|
|
pipeline_class = fopt.pipeline_cls
|
|
pipeline_options = fopt.pipeline_options
|
|
options_hash = create_pipeline_options_hash(pipeline_options)
|
|
|
|
# Use a composite key to cache pipelines
|
|
cache_key = (pipeline_class, options_hash)
|
|
|
|
with _PIPELINE_CACHE_LOCK:
|
|
if cache_key not in self.initialized_pipelines:
|
|
_log.info(
|
|
f"Initializing pipeline for {pipeline_class.__name__} with options hash {options_hash}"
|
|
)
|
|
self.initialized_pipelines[cache_key] = pipeline_class(
|
|
pipeline_options=pipeline_options
|
|
)
|
|
else:
|
|
_log.debug(
|
|
f"Reusing cached pipeline for {pipeline_class.__name__} with options hash {options_hash}"
|
|
)
|
|
|
|
return self.initialized_pipelines[cache_key]
|
|
|
|
def _process_indexed_document(
|
|
self,
|
|
indexed_doc: tuple[int, InputDocument],
|
|
raises_on_error: bool,
|
|
progress_callback: Optional[ProgressCallback] = None,
|
|
) -> ConversionResult:
|
|
document_index, in_doc = indexed_doc
|
|
callbacks = [
|
|
callback
|
|
for callback in (
|
|
self.progress_callback,
|
|
self.progress_printer,
|
|
progress_callback,
|
|
)
|
|
if callback is not None
|
|
]
|
|
progress = ProgressReporter(callbacks, in_doc.file.name, document_index)
|
|
progress.document_started()
|
|
status = ConversionStatus.FAILURE
|
|
try:
|
|
conv_res = self._process_document(
|
|
in_doc, raises_on_error=raises_on_error, progress=progress
|
|
)
|
|
status = conv_res.status
|
|
finally:
|
|
progress.document_completed(status)
|
|
return conv_res
|
|
|
|
def _process_document(
|
|
self,
|
|
in_doc: InputDocument,
|
|
raises_on_error: bool,
|
|
progress: Optional[ProgressReporter] = None,
|
|
) -> ConversionResult:
|
|
valid = (
|
|
self.allowed_formats is not None and in_doc.format in self.allowed_formats
|
|
)
|
|
if valid:
|
|
conv_res = self._execute_pipeline(
|
|
in_doc, raises_on_error=raises_on_error, progress=progress
|
|
)
|
|
else:
|
|
error_message = f"File format not allowed: {in_doc.file}"
|
|
error_item = ErrorItem(
|
|
component_type=DoclingComponentType.USER_INPUT,
|
|
module_name="",
|
|
error_message=error_message,
|
|
category=FailureCategory.POLICY,
|
|
)
|
|
conv_res = ConversionResult(
|
|
input=in_doc, status=ConversionStatus.SKIPPED, errors=[error_item]
|
|
)
|
|
|
|
return conv_res
|
|
|
|
def _unload_input_document(self, in_doc: InputDocument) -> None:
|
|
backend = getattr(in_doc, "_backend", None)
|
|
if backend is not None:
|
|
backend.unload()
|
|
|
|
def _execute_pipeline(
|
|
self,
|
|
in_doc: InputDocument,
|
|
raises_on_error: bool,
|
|
progress: Optional[ProgressReporter] = None,
|
|
) -> ConversionResult:
|
|
if in_doc.valid:
|
|
pipeline_started = False
|
|
try:
|
|
if progress is not None:
|
|
progress.phase_started(ConversionPhase.INITIALIZE)
|
|
pipeline = self._get_pipeline(in_doc.format)
|
|
if pipeline is not None:
|
|
pipeline_started = True
|
|
conv_res = pipeline.execute(
|
|
in_doc, raises_on_error=raises_on_error, progress=progress
|
|
)
|
|
else:
|
|
if raises_on_error:
|
|
raise ConversionError(
|
|
f"No pipeline could be initialized for {in_doc.file}."
|
|
)
|
|
else:
|
|
_log.warning(
|
|
"No pipeline could be initialized for %s.", in_doc.file
|
|
)
|
|
conv_res = ConversionResult(
|
|
input=in_doc,
|
|
status=ConversionStatus.FAILURE,
|
|
)
|
|
finally:
|
|
if not pipeline_started:
|
|
self._unload_input_document(in_doc)
|
|
else:
|
|
try:
|
|
_log.warning("Input document %s is not valid.", in_doc.file)
|
|
conv_res = ConversionResult(
|
|
input=in_doc,
|
|
status=ConversionStatus.FAILURE,
|
|
errors=build_invalid_input_errors(in_doc),
|
|
)
|
|
finally:
|
|
self._unload_input_document(in_doc)
|
|
|
|
return conv_res
|