# SPDX-FileCopyrightText: The Docling Contributors # SPDX-License-Identifier: MIT """Backend to parse articles in JATS (Journal Article Tag Suite) XML format. JATS is a standard XML format used by publishers and journal archives including PubMed Central (PMC), bioRxiv, and medRxiv for representing journal articles. Security Note: This module uses lxml.etree.XMLParser with secure configuration to protect against XML External Entity (XXE) attacks and XML bombs. The parser is configured with: - resolve_entities: False (prevents entity resolution attacks) - no_network: True (blocks all network access) - dtd_validation: False (disables DTD validation) - load_dtd: False (prevents loading external DTDs) This configuration ensures safe parsing of JATS XML files while blocking external entity fetching and preventing XXE attacks. """ from __future__ import annotations import logging import traceback import warnings from dataclasses import dataclass, replace from io import BytesIO from pathlib import Path from typing import Final, cast from docling_core.types.doc import ( DocItemLabel, DoclingDocument, DocumentOrigin, GroupItem, GroupLabel, ImageRef, NodeItem, TableCell, TableData, TextItem, ) from docling_core.types.doc.document import Formatting, Script from lxml import etree from pydantic import AnyUrl, ValidationError from typing_extensions import TypedDict, override from docling.backend.abstract_backend import DeclarativeDocumentBackend from docling.backend.html_backend import HTMLDocumentBackend from docling.backend.utils.image_resource_loader import ImageResourceLoader from docling.backend.utils.table_spans import table_width from docling.datamodel.backend_options import JatsBackendOptions from docling.datamodel.base_models import InputFormat from docling.datamodel.document import InputDocument from docling.exceptions import DocumentLoadError _BS4_AVAILABLE: bool = False _BS4_IMPORT_ERROR: ImportError | None = None try: # pragma: no cover - import-time guard from bs4 import BeautifulSoup, NavigableString, Tag from lxml import etree _BS4_AVAILABLE = True except ImportError as e: # pragma: no cover - import-time guard _BS4_IMPORT_ERROR = e _INSTALL_HINT = ( "The 'beautifulsoup4' and 'lxml' packages are required to process JATS files. " "Install them with `pip install 'docling-slim[format-xml-jats]'`." ) _log = logging.getLogger(__name__) JATS_DTD_URL: Final[list[str]] = ["JATS-journalpublishing", "JATS-archive"] DEFAULT_HEADER_ACKNOWLEDGMENTS: Final[str] = "Acknowledgments" DEFAULT_HEADER_ABSTRACT: Final[str] = "Abstract" DEFAULT_HEADER_FOOTNOTES: Final[str] = "Footnotes" DEFAULT_HEADER_REFERENCES: Final[str] = "References" DEFAULT_TEXT_ETAL: Final[str] = "et al." _XLINK_HREF: Final[str] = "{http://www.w3.org/1999/xlink}href" # `list-type` values that number the items, from the JATS 1.3 tag library. _ORDERED_LIST_TYPES: Final[frozenset[str]] = frozenset( {"order", "alpha-lower", "alpha-upper", "roman-lower", "roman-upper"} ) # Elements that hold a whole article inside another one, such as a decision # letter or an author reply, from the JATS 1.3 tag library. _SUB_ARTICLE_TAGS: Final[tuple[str, ...]] = ("sub-article", "response") _NOT_IN_SUB_ARTICLE: Final[str] = "not(ancestor::sub-article or ancestor::response)" _RASTER_IMAGE_SUFFIXES: Final[tuple[str, ...]] = ( ".jpg", ".jpeg", ".png", ".tif", ".tiff", ".gif", ) # Maps JATS formatting tags to docling-core formatting attributes. _JATS_FORMAT_TAG_MAP: Final[dict[str, dict[str, bool | Script]]] = { "bold": {"bold": True}, "italic": {"italic": True}, "underline": {"underline": True}, "strike": {"strikethrough": True}, "sub": {"script": Script.SUB}, "sup": {"script": Script.SUPER}, } @dataclass(slots=True) class InlineSegment: """An ordered inline run of styled text or an inline formula. Attributes: label: Docling item label that classifies this inline run when it is emitted as a text item. text: Literal text carried by the run, or the LaTeX body when the run is a formula. formatting: Emphasis accumulated from the enclosing tags (bold, italic, underline, strike, sub, sup), or ``None`` when the run is unstyled. hyperlink: External link target inherited from an enclosing ``ext-link``, or ``None`` when the run is unlinked. """ label: DocItemLabel text: str formatting: Formatting | None = None hyperlink: AnyUrl | Path | None = None class AbstractSection(TypedDict): """A single titled section inside a structured abstract.""" title: str # Raw

nodes are walked at emit time to preserve inline styling. paragraphs: list[etree._Element] class Abstract(TypedDict): label: str paragraphs: list[etree._Element] sections: list[AbstractSection] # structured sub-sections ( children) class Author(TypedDict): name: str affiliation_names: list[str] class Citation(TypedDict): author_names: str title: str source: str year: str volume: str page: str pub_id: str publisher_name: str publisher_loc: str class Table(TypedDict): label: str caption: str content: str class XMLComponents(TypedDict): title: str authors: list[Author] abstract: list[Abstract] class JatsDocumentBackend(DeclarativeDocumentBackend): """Backend to parse articles in XML format tagged according to JATS definition. The Journal Article Tag Suite (JATS) is an definition standard for the representation of journal articles in XML format. Several publishers and journal archives provide content in JATS format, including PubMed Central® (PMC), bioRxiv, medRxiv, or Springer Nature. Refer to https://jats.nlm.nih.gov for more details on JATS. The code from this document backend has been developed by modifying parts of the PubMed Parser library (version 0.5.0, released on 12.08.2024): Achakulvisut et al., (2020). Pubmed Parser: A Python Parser for PubMed Open-Access XML Subset and MEDLINE XML Dataset XML Dataset. Journal of Open Source Software, 5(46), 1979, https://doi.org/10.21105/joss.01979 """ @override def __init__( self, in_doc: InputDocument, path_or_stream: BytesIO | Path, options: JatsBackendOptions | None = None, ) -> None: if not _BS4_AVAILABLE: raise ImportError(_INSTALL_HINT) from _BS4_IMPORT_ERROR if options is None: options = JatsBackendOptions() super().__init__(in_doc, path_or_stream, options) self.options: JatsBackendOptions self.path_or_stream = path_or_stream self.base_path: str | None = ( str(options.source_uri) if options.source_uri is not None else ( str(path_or_stream) if options.enable_local_fetch and isinstance(path_or_stream, Path) else None ) ) self._image_loader = ImageResourceLoader( enable_local_fetch=options.enable_local_fetch, enable_remote_fetch=options.enable_remote_fetch, ) # Initialize the root of the document hierarchy self.root: NodeItem | None = None self.hlevel: int = 0 self.valid: bool = False try: if isinstance(self.path_or_stream, BytesIO): self.path_or_stream.seek(0) parser = etree.XMLParser( resolve_entities=False, load_dtd=False, no_network=True, dtd_validation=False, ) self.tree: etree._ElementTree = etree.parse( self.path_or_stream, parser=parser ) doc_info: etree.DocInfo = self.tree.docinfo if doc_info.system_url and any( kwd in doc_info.system_url for kwd in JATS_DTD_URL ): self.valid = True return for ent in doc_info.internalDTD.iterentities(): if ent.system_url and any( kwd in ent.system_url for kwd in JATS_DTD_URL ): self.valid = True return except Exception as exc: raise DocumentLoadError( f"Could not initialize JATS backend for file with hash {self.document_hash}." ) from exc @override def is_valid(self) -> bool: return self.valid @classmethod @override def supports_pagination(cls) -> bool: return False @override def unload(self): if isinstance(self.path_or_stream, BytesIO): self.path_or_stream.close() self.path_or_stream = None @classmethod @override def supported_formats(cls) -> set[InputFormat]: return {InputFormat.XML_JATS} @override def convert(self) -> DoclingDocument: try: # Create empty document origin = DocumentOrigin( filename=self.file.name or "file", mimetype="application/xml", binary_hash=self.document_hash, ) doc = DoclingDocument(name=self.file.stem or "file", origin=origin) self.hlevel = 0 # Get metadata XML components xml_components: XMLComponents = self._parse_metadata() # Add metadata to the document self._add_metadata(doc, xml_components) # walk over the XML body body = self.tree.xpath(f"//body[{_NOT_IN_SUB_ARTICLE}]") if self.root and len(body) > 0: self._walk_linear(doc, self.root, body[0]) # walk over the XML back matter back = self.tree.xpath(f"//back[{_NOT_IN_SUB_ARTICLE}]") if self.root and len(back) > 0: self._walk_linear(doc, self.root, back[0]) # walk over the sub-articles sub_articles = self.tree.xpath( " | ".join( f"//{tag}[{_NOT_IN_SUB_ARTICLE}]" for tag in _SUB_ARTICLE_TAGS ) ) if self.root: for sub_article in sub_articles: self._add_sub_article(doc, self.root, sub_article) except Exception: _log.error(traceback.format_exc()) return doc @staticmethod def _get_text(node: etree._Element, sep: str | None = None) -> str: skip_tags = ["term", "disp-formula", "inline-formula"] text: str = ( node.text.replace("\n", " ") if (node.tag not in skip_tags and node.text) else "" ) for child in list(node): if child.tag not in skip_tags: # TODO: apply styling according to child.tag when supported by docling-core text += JatsDocumentBackend._get_text(child, sep) if sep: text = text.rstrip(sep) + sep text += child.tail.replace("\n", " ") if child.tail else "" return text @staticmethod def _get_label(node: etree._Element) -> str: """Return the text of the `