Core Types & Exceptions

This page documents the core data types, enumerations, and exceptions that form the foundation of doc2mark. Every call to doc2mark.load() or load() returns a ProcessedDocument whose fields are described here. The enumerations control which input formats are recognised and which output representations are available, while the exception hierarchy lets callers handle errors at the right level of granularity.

Enumerations

DocumentFormat

An enumeration of every file format that doc2mark can ingest. Each member value is the lowercase file extension (without a leading dot).

Category

Members

Extension values

Office

DOCX, XLSX, PPTX

"docx", "xlsx", "pptx"

Legacy Office

DOC, XLS, PPT, RTF, PPS

"doc", "xls", "ppt", "rtf", "pps"

PDF

PDF

"pdf"

Text / Data

TXT, CSV, TSV, JSON, JSONL

"txt", "csv", "tsv", "json", "jsonl"

Markup

HTML, XML, MARKDOWN

"html", "xml", "md"

Email

EML

"eml"

Image

PNG, JPG, JPEG, WEBP, TIFF, TIF, BMP, GIF, HEIC, HEIF, AVIF

"png", "jpg", "jpeg", "webp", "tiff", "tif", "bmp", "gif", "heic", "heif", "avif"

from doc2mark import DocumentFormat

fmt = DocumentFormat.PDF
print(fmt.value)  # "pdf"
class doc2mark.DocumentFormat(*values)[source]

Bases: Enum

Supported document formats.

AVIF = 'avif'
BMP = 'bmp'
CSV = 'csv'
DOC = 'doc'
DOCX = 'docx'
EML = 'eml'
GIF = 'gif'
HEIC = 'heic'
HEIF = 'heif'
HTML = 'html'
JPEG = 'jpeg'
JPG = 'jpg'
JSON = 'json'
JSONL = 'jsonl'
MARKDOWN = 'md'
PDF = 'pdf'
PNG = 'png'
PPS = 'pps'
PPT = 'ppt'
PPTX = 'pptx'
RTF = 'rtf'
TIF = 'tif'
TIFF = 'tiff'
TSV = 'tsv'
TXT = 'txt'
WEBP = 'webp'
XLS = 'xls'
XLSX = 'xlsx'
XML = 'xml'

OutputFormat

Controls the representation produced by the loader.

MARKDOWN

Produce a Markdown string (value "markdown"). This is the default.

JSON

Produce a JSON-structured representation (value "json").

TEXT

Produce plain text with formatting stripped (value "text").

from doc2mark import OutputFormat

fmt = OutputFormat.MARKDOWN
print(fmt.value)  # "markdown"
class doc2mark.OutputFormat(*values)[source]

Bases: Enum

Supported output formats.

JSON = 'json'
MARKDOWN = 'markdown'
TEXT = 'text'

TableStyle

Selects how complex tables (those with merged cells) are rendered in the output. Defined in doc2mark.core.table.

MINIMAL_HTML

Bare <table> markup without inline styles (value "minimal_html"). This is the default, returned by TableStyle.default().

MARKDOWN_GRID

A Markdown pipe table annotated with merge markers and an HTML comment listing spanned regions (value "markdown_grid").

STYLED_HTML

A fully styled <table> with borders, padding, and background colours on header cells (value "styled_html").

from doc2mark import TableStyle

style = TableStyle.default()       # TableStyle.MINIMAL_HTML
print(style.value)                  # "minimal_html"
class doc2mark.TableStyle(*values)[source]

Bases: Enum

Table output style options for complex tables with merged cells.

MARKDOWN_GRID = 'markdown_grid'
MINIMAL_HTML = 'minimal_html'
STYLED_HTML = 'styled_html'
classmethod default()[source]

Result Objects

ProcessedDocument

The primary return value from any document-loading call. It is a dataclass() with the following fields:

contentstr

The converted document body (Markdown by default).

metadataDocumentMetadata

Structured metadata about the source file.

imagesOptional[List[Dict[str, Any]]]

Extracted images, each represented as a dictionary. None when image extraction is not requested.

tablesOptional[List[Dict[str, Any]]]

Extracted table data. None when no tables are present.

sectionsOptional[List[Dict[str, Any]]]

Document sections, when the format supports them. None otherwise.

json_contentOptional[List[Dict[str, Any]]]

A structured JSON representation of the document used for chunking (compatible with the UnifiedMarkdownLoader pipeline). None when the output format does not produce it.

Convenience properties and methods:

markdownstr (property)

Alias for content.

textstr (property)

Returns content with common Markdown formatting stripped.

to_dict() -> Dict[str, Any]

Returns a fully JSON-serializable dictionary of the document (enum values are converted to strings, bytes are base64-encoded).

get_chunks(config=None)

Split the document into section-aware chunks for RAG pipelines. Accepts an optional ChunkingConfig; uses defaults when None.

from doc2mark import load

result = load("report.pdf")

# Markdown body
print(result.content[:200])

# Metadata
print(result.metadata.filename)
print(result.metadata.page_count)

# Plain-text view (Markdown formatting removed)
plain = result.text

# JSON-safe dict for serialisation
data = result.to_dict()

# Section-aware chunks for RAG
chunks = result.get_chunks()
class doc2mark.ProcessedDocument(content, metadata, images=None, tables=None, sections=None, json_content=None)[source]

Bases: object

Container for processed document data.

Parameters:
  • content (str)

  • metadata (DocumentMetadata)

  • images (List[Dict[str, Any]] | None)

  • tables (List[Dict[str, Any]] | None)

  • sections (List[Dict[str, Any]] | None)

  • json_content (List[Dict[str, Any]] | None)

get_chunks(config=None)[source]

Split document into section-aware chunks for RAG.

Parameters:

config – Optional ChunkingConfig. Uses defaults when None.

Returns:

List of Chunk objects.

property markdown: str

Get content as markdown.

property text: str

Get content as plain text.

to_dict()[source]

Return a JSON-serializable representation of the processed document.

Return type:

Dict[str, Any]

DocumentMetadata

A dataclass() that carries information about the source file. Only the first three fields are always populated; the rest are None unless the format provides them.

Always present:

filenamestr

Original file name.

formatDocumentFormat

Detected input format.

size_bytesint

File size in bytes.

Common optional fields:

page_countOptional[int]

Number of pages (PDF, DOCX, PPTX).

word_countOptional[int]

Approximate word count.

languageOptional[str]

Detected language code.

creation_dateOptional[str]

Creation timestamp from file metadata.

modification_dateOptional[str]

Last-modification timestamp from file metadata.

authorOptional[str]

Author name from file metadata.

titleOptional[str]

Document title from file metadata.

Format-specific optional fields:

sheet_namesOptional[List[str]]

Sheet names (XLSX).

slide_countOptional[int]

Number of slides (PPTX).

line_countOptional[int]

Number of lines (text files).

header_countOptional[int]

Number of headings (Markdown).

link_countOptional[int]

Number of hyperlinks (HTML, Markdown).

image_countOptional[int]

Number of images found in the document.

total_cellsOptional[int]

Total cell count (XLSX).

encodingOptional[str]

Detected character encoding (text files).

delimiterOptional[str]

Field delimiter (CSV, TSV).

record_countOptional[int]

Number of records (JSONL).

row_countOptional[int]

Number of rows (CSV).

column_countOptional[int]

Number of columns (CSV).

element_countOptional[int]

Number of XML elements (XML).

root_tagOptional[str]

Root element tag name (XML).

frontmatterOptional[Dict[str, Any]]

Parsed YAML front-matter (Markdown).

data_typeOptional[str]

Top-level JSON type descriptor (JSON).

item_countOptional[int]

Number of top-level items (JSON).

extraDict[str, Any]

Catch-all dictionary for additional metadata not covered by the fields above. Defaults to an empty dict.

from doc2mark import load

result = load("spreadsheet.xlsx")
meta = result.metadata

print(meta.filename)       # "spreadsheet.xlsx"
print(meta.format)         # DocumentFormat.XLSX
print(meta.size_bytes)     # 14832
print(meta.sheet_names)    # ["Sheet1", "Summary"]
class doc2mark.DocumentMetadata(filename, format, size_bytes, page_count=None, word_count=None, language=None, creation_date=None, modification_date=None, author=None, title=None, sheet_names=None, slide_count=None, line_count=None, header_count=None, link_count=None, image_count=None, total_cells=None, encoding=None, delimiter=None, record_count=None, row_count=None, column_count=None, element_count=None, root_tag=None, frontmatter=None, data_type=None, item_count=None, extra=<factory>)[source]

Bases: object

Metadata for a processed document.

Parameters:
  • filename (str)

  • format (DocumentFormat)

  • size_bytes (int)

  • page_count (int | None)

  • word_count (int | None)

  • language (str | None)

  • creation_date (str | None)

  • modification_date (str | None)

  • author (str | None)

  • title (str | None)

  • sheet_names (List[str] | None)

  • slide_count (int | None)

  • line_count (int | None)

  • header_count (int | None)

  • link_count (int | None)

  • image_count (int | None)

  • total_cells (int | None)

  • encoding (str | None)

  • delimiter (str | None)

  • record_count (int | None)

  • row_count (int | None)

  • column_count (int | None)

  • element_count (int | None)

  • root_tag (str | None)

  • frontmatter (Dict[str, Any] | None)

  • data_type (str | None)

  • item_count (int | None)

  • extra (Dict[str, Any])

Exceptions

All exceptions raised by doc2mark inherit from ProcessingError, so a single except ProcessingError clause catches every library-specific failure.

Exception
 +-- ProcessingError
      +-- UnsupportedFormatError
      +-- OCRError
      +-- ConversionError

ProcessingError

Base exception for all document-processing errors. Catch this when you want a single handler for any doc2mark failure.

from doc2mark import load, ProcessingError

try:
    result = load("data.bin")
except ProcessingError as exc:
    print(f"Could not process file: {exc}")
exception doc2mark.ProcessingError[source]

Bases: Exception

Base exception for document processing errors.

UnsupportedFormatError

Raised when the file extension is not recognised or no processor is registered for the detected DocumentFormat.

from doc2mark import load, UnsupportedFormatError

try:
    result = load("archive.7z")
except UnsupportedFormatError:
    print("This file type is not supported.")
exception doc2mark.UnsupportedFormatError[source]

Bases: ProcessingError

Raised when attempting to process an unsupported format.

OCRError

Raised when an OCR backend (e.g. OCRProvider OPENAI or VERTEX_AI) fails – for example due to an invalid API key, a network timeout, or an unsupported image.

from doc2mark import load, OCRError

try:
    result = load("scan.pdf", extract_images=True, ocr_images=True)
except OCRError:
    print("OCR processing failed.")
exception doc2mark.OCRError[source]

Bases: ProcessingError

Raised when OCR processing fails.

ConversionError

Raised when format conversion fails internally – for instance when a legacy .doc file cannot be converted to .docx before processing.

from doc2mark import load, ConversionError

try:
    result = load("legacy.doc")
except ConversionError:
    print("Document conversion failed.")
exception doc2mark.ConversionError[source]

Bases: ProcessingError

Raised when document conversion fails.