{"record":{"id":"40bccc85b7a3fa31","repo":"docling-project/docling","slug":"could-not-initialize-uspto-backend-for-file-with-h","errorCode":null,"errorMessage":"Could not initialize USPTO backend for file with hash {self.document_hash}.","messagePattern":"Could not initialize USPTO backend for file with hash (.+?)\\.","errorType":"exception","errorClass":"DocumentLoadError","httpStatus":null,"severity":"error","filePath":"docling/backend/xml/uspto_backend.py","lineNumber":133,"sourceCode":"        super().__init__(in_doc, path_or_stream)\n\n        self.patent_content: str = \"\"\n        self.parser: PatentUspto | None = None\n\n        try:\n            if isinstance(self.path_or_stream, BytesIO):\n                while line := self.path_or_stream.readline().decode(\"utf-8\"):\n                    if line.startswith(\"<!DOCTYPE\") or line == \"PATN\\n\":\n                        self._set_parser(line)\n                    self.patent_content += line\n            elif isinstance(self.path_or_stream, Path):\n                with open(self.path_or_stream, encoding=\"utf-8\") as file_obj:\n                    while line := file_obj.readline():\n                        if line.startswith(\"<!DOCTYPE\") or line == \"PATN\\n\":\n                            self._set_parser(line)\n                        self.patent_content += line\n        except Exception as exc:\n            raise DocumentLoadError(\n                f\"Could not initialize USPTO backend for file with hash {self.document_hash}.\"\n            ) from exc\n\n    def _set_parser(self, doctype: str) -> None:\n        doctype_line = doctype.lower()\n        if doctype == \"PATN\\n\":\n            self.parser = PatentUsptoGrantAps()\n        elif \"us-patent-application-v4\" in doctype_line:\n            self.parser = PatentUsptoIce()\n        elif \"us-patent-grant-v4\" in doctype_line:\n            self.parser = PatentUsptoIce()\n        elif \"us-grant-025\" in doctype_line:\n            self.parser = PatentUsptoGrantV2()\n        elif all(\n            item in doctype_line\n            for item in (\"patent-application-publication\", \"pap-v1\")\n        ):\n            self.parser = PatentUsptoAppV1()","sourceCodeStart":115,"sourceCodeEnd":151,"githubUrl":"https://github.com/docling-project/docling/blob/61d76f1ff3f8428065465889f7b4577da7df704c/docling/backend/xml/uspto_backend.py#L115-L151","documentation":"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.","triggerScenarios":"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.","commonSituations":"Old APS-era patent files in non-UTF-8 encodings; partially downloaded patents from bulk USPTO datasets; permission-restricted mounts in containers.","solutions":["Check __cause__ for the real error (UnicodeDecodeError vs OSError).","Re-encode the file to UTF-8 before converting (iconv or Python transcode).","Verify readability and integrity of the file; re-download if truncated.","Catch DocumentLoadError in batch patent pipelines and log/skip the offending file."],"exampleFix":"# before\nresult = converter.convert(Path(\"p9999999.txt\"))  # Latin-1 APS file -> DocumentLoadError\n\n# after\nraw = Path(\"p9999999.txt\").read_bytes().decode(\"latin-1\").encode(\"utf-8\")\nfrom io import BytesIO\nresult = converter.convert(BytesIO(raw))","handlingStrategy":"try-catch","validationCode":"from pathlib import Path\n\ndef patent_file_utf8_readable(path: Path) -> bool:\n    try:\n        with open(path, encoding=\"utf-8\") as f:\n            f.readline()\n        return True\n    except (UnicodeDecodeError, OSError):\n        return False","typeGuard":null,"tryCatchPattern":"from docling.datamodel.base_docs import DocumentLoadError\n\ntry:\n    result = converter.convert(patent_path)\nexcept DocumentLoadError as e:\n    logger.error(\"USPTO load failed for %s: cause=%r\", patent_path, e.__cause__)","preventionTips":["Transcode legacy patent files to UTF-8 during ingestion.","Verify bulk-download integrity (size/checksum) before conversion.","Log __cause__ to distinguish decode vs permission failures."],"tags":["uspto","patents","encoding","document-load","utf-8"],"backgroundTag":null,"analyzedSha":"61d76f1ff3f8428065465889f7b4577da7df704c","analyzedAt":"2026-08-14T23:53:18.727Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}