docling-project/docling · error · DocumentLoadError

Could not initialize USPTO backend for file with hash {self.

Error message

Could not initialize USPTO backend for file with hash {self.document_hash}.

What it means

The USPTO backend constructor failed while slurping the patent file line by line (reading BytesIO or Path, decoding UTF-8, sniffing the DOCTYPE/PATN header) and wraps any exception in DocumentLoadError. The whole read loop is inside one try/except Exception, so any IO or decode error becomes this message.

Source

Thrown at docling/backend/xml/uspto_backend.py:133

        super().__init__(in_doc, path_or_stream)

        self.patent_content: str = ""
        self.parser: PatentUspto | None = None

        try:
            if isinstance(self.path_or_stream, BytesIO):
                while line := self.path_or_stream.readline().decode("utf-8"):
                    if line.startswith("<!DOCTYPE") or line == "PATN\n":
                        self._set_parser(line)
                    self.patent_content += line
            elif isinstance(self.path_or_stream, Path):
                with open(self.path_or_stream, encoding="utf-8") as file_obj:
                    while line := file_obj.readline():
                        if line.startswith("<!DOCTYPE") or line == "PATN\n":
                            self._set_parser(line)
                        self.patent_content += line
        except Exception as exc:
            raise DocumentLoadError(
                f"Could not initialize USPTO backend for file with hash {self.document_hash}."
            ) from exc

    def _set_parser(self, doctype: str) -> None:
        doctype_line = doctype.lower()
        if doctype == "PATN\n":
            self.parser = PatentUsptoGrantAps()
        elif "us-patent-application-v4" in doctype_line:
            self.parser = PatentUsptoIce()
        elif "us-patent-grant-v4" in doctype_line:
            self.parser = PatentUsptoIce()
        elif "us-grant-025" in doctype_line:
            self.parser = PatentUsptoGrantV2()
        elif all(
            item in doctype_line
            for item in ("patent-application-publication", "pap-v1")
        ):
            self.parser = PatentUsptoAppV1()

View on GitHub (pinned to 61d76f1ff3)

Solutions

  1. Check __cause__ for the real error (UnicodeDecodeError vs OSError).
  2. Re-encode the file to UTF-8 before converting (iconv or Python transcode).
  3. Verify readability and integrity of the file; re-download if truncated.
  4. Catch DocumentLoadError in batch patent pipelines and log/skip the offending file.

Example fix

# before
result = converter.convert(Path("p9999999.txt"))  # Latin-1 APS file -> DocumentLoadError

# after
raw = Path("p9999999.txt").read_bytes().decode("latin-1").encode("utf-8")
from io import BytesIO
result = converter.convert(BytesIO(raw))
Defensive patterns

Strategy: try-catch

Validate before calling

from pathlib import Path

def patent_file_utf8_readable(path: Path) -> bool:
    try:
        with open(path, encoding="utf-8") as f:
            f.readline()
        return True
    except (UnicodeDecodeError, OSError):
        return False

Try / catch

from docling.datamodel.base_docs import DocumentLoadError

try:
    result = converter.convert(patent_path)
except DocumentLoadError as e:
    logger.error("USPTO load failed for %s: cause=%r", patent_path, e.__cause__)

Prevention

When it happens

Trigger: Constructing PatentUsptoDocumentBackend on a file that cannot be opened/read, or whose lines are not valid UTF-8 — e.g. legacy patents in Latin-1/CP1252, binary garbage, or an unreadable path.

Common situations: Old APS-era patent files in non-UTF-8 encodings; partially downloaded patents from bulk USPTO datasets; permission-restricted mounts in containers.

Related errors


AI-assisted analysis of docling-project/docling@61d76f1ff3 (2026-08-14). Data as JSON: /api/errors/40bccc85b7a3fa31. Report an issue: GitHub.