Skip to content

Commit

Permalink
Add ErrorItem and evaluate page valid status
Browse files Browse the repository at this point in the history
Signed-off-by: Christoph Auer <[email protected]>
  • Loading branch information
cau-git committed Aug 23, 2024
2 parents 21f9775 + 3226b20 commit 1e30de6
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 19 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
## [v1.7.1](https://github.com/DS4SD/docling/releases/tag/v1.7.1) - 2024-08-23

### Fix

* Better raise exception when a page fails to parse ([#46](https://github.com/DS4SD/docling/issues/46)) ([`8808463`](https://github.com/DS4SD/docling/commit/8808463cecd7ff3a92bd99d2e3d65fd248672c9e))
* Upgrade docling-parse to 1.1.1, safety checks for failed parse on pages ([#45](https://github.com/DS4SD/docling/issues/45)) ([`7e84533`](https://github.com/DS4SD/docling/commit/7e845332992ab37386daee087573773051bfd065))

## [v1.7.0](https://github.com/DS4SD/docling/releases/tag/v1.7.0) - 2024-08-22

### Feature
Expand Down
8 changes: 7 additions & 1 deletion docling/backend/docling_parse_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ def __init__(
self.valid = "pages" in parsed_page
if self.valid:
self._dpage = parsed_page["pages"][0]
else:
_log.info(
f"An error occured when loading page {page_no} of document {document_hash}."
)

def is_valid(self) -> bool:
return self.valid
Expand Down Expand Up @@ -198,7 +202,9 @@ def __init__(self, path_or_stream: Union[BytesIO, Path], document_hash: str):
success = self.parser.load_document(document_hash, str(path_or_stream))

if not success:
raise RuntimeError("docling-parse could not load this document.")
raise RuntimeError(
f"docling-parse could not load document {document_hash}."
)

def page_count(self) -> int:
return len(self._pdoc) # To be replaced with docling-parse API
Expand Down
28 changes: 23 additions & 5 deletions docling/backend/pypdfium2_backend.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import random
from io import BytesIO
from pathlib import Path
Expand All @@ -7,16 +8,28 @@
import pypdfium2.raw as pdfium_c
from PIL import Image, ImageDraw
from pypdfium2 import PdfPage
from pypdfium2._helpers.misc import PdfiumError

from docling.backend.abstract_backend import PdfDocumentBackend, PdfPageBackend
from docling.datamodel.base_models import BoundingBox, Cell, CoordOrigin, PageSize

_log = logging.getLogger(__name__)


class PyPdfiumPageBackend(PdfPageBackend):
def __init__(self, pdfium_doc: pdfium.PdfDocument, page_no: int):
self._ppage: pdfium.PdfPage = pdfium_doc[page_no]
def __init__(
self, pdfium_doc: pdfium.PdfDocument, document_hash: str, page_no: int
):
self.valid = True # No better way to tell from pypdfium.
try:
self._ppage: pdfium.PdfPage = pdfium_doc[page_no]
except PdfiumError as e:
_log.info(
f"An exception occured when loading page {page_no} of document {document_hash}.",
exc_info=True,
)
self.valid = False
self.text_page = None
self.valid = True

def is_valid(self) -> bool:
return self.valid
Expand Down Expand Up @@ -220,13 +233,18 @@ def unload(self):
class PyPdfiumDocumentBackend(PdfDocumentBackend):
def __init__(self, path_or_stream: Union[BytesIO, Path], document_hash: str):
super().__init__(path_or_stream, document_hash)
self._pdoc = pdfium.PdfDocument(path_or_stream)
try:
self._pdoc = pdfium.PdfDocument(path_or_stream)
except PdfiumError as e:
raise RuntimeError(
f"pypdfium could not load document {document_hash}"
) from e

def page_count(self) -> int:
return len(self._pdoc)

def load_page(self, page_no: int) -> PyPdfiumPageBackend:
return PyPdfiumPageBackend(self._pdoc, page_no)
return PyPdfiumPageBackend(self._pdoc, self.document_hash, page_no)

def is_valid(self) -> bool:
return self.page_count() > 0
Expand Down
14 changes: 13 additions & 1 deletion docling/datamodel/base_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class ConversionStatus(str, Enum):
STARTED = auto()
FAILURE = auto()
SUCCESS = auto()
SUCCESS_WITH_ERRORS = auto()
PARTIAL_SUCCESS = auto()


class DocInputType(str, Enum):
Expand All @@ -29,6 +29,18 @@ class CoordOrigin(str, Enum):
BOTTOMLEFT = auto()


class DoclingComponentType(str, Enum):
PDF_BACKEND = auto()
MODEL = auto()
DOC_ASSEMBLER = auto()


class ErrorItem(BaseModel):
component_type: DoclingComponentType
module_name: str
error_message: str


class PageSize(BaseModel):
width: float = 0.0
height: float = 0.0
Expand Down
3 changes: 2 additions & 1 deletion docling/datamodel/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
AssembledUnit,
ConversionStatus,
DocumentStream,
ErrorItem,
FigureElement,
Page,
PageElement,
Expand Down Expand Up @@ -118,7 +119,7 @@ class ConvertedDocument(BaseModel):
input: InputDocument

status: ConversionStatus = ConversionStatus.PENDING # failure, success
errors: List[Dict] = [] # structure to keep errors
errors: List[ErrorItem] = [] # structure to keep errors

pages: List[Page] = []
assembled: Optional[AssembledUnit] = None
Expand Down
21 changes: 19 additions & 2 deletions docling/document_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
AssembledUnit,
AssembleOptions,
ConversionStatus,
DoclingComponentType,
ErrorItem,
Page,
PipelineOptions,
)
Expand Down Expand Up @@ -212,12 +214,27 @@ def process_document(self, in_doc: InputDocument) -> ConvertedDocument:
converted_doc.pages = all_assembled_pages
self.assemble_doc(converted_doc)

converted_doc.status = ConversionStatus.SUCCESS
status = ConversionStatus.SUCCESS
for page in converted_doc.pages:
if not page._backend.is_valid():
converted_doc.errors.append(
ErrorItem(
component_type=DoclingComponentType.PDF_BACKEND,
module_name=type(page._backend).__name__,
error_message=f"Page {page.page_no} failed to parse.",
)
)
status = ConversionStatus.PARTIAL_SUCCESS

converted_doc.status = status

except Exception as e:
converted_doc.status = ConversionStatus.FAILURE
trace = "\n".join(traceback.format_exception(e))
_log.info(f"Encountered an error during conversion: {trace}")
_log.info(
f"Encountered an error during conversion of document {in_doc.document_hash}:\n"
f"{trace}"
)

end_doc_time = time.time() - start_doc_time
_log.info(
Expand Down
21 changes: 13 additions & 8 deletions examples/batch_convert.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import json
import logging
import time
from io import BytesIO
from pathlib import Path
from typing import Iterable

from docling.datamodel.base_models import (
ConversionStatus,
DocumentStream,
PipelineOptions,
)
from docling.datamodel.base_models import ConversionStatus, PipelineOptions
from docling.datamodel.document import ConvertedDocument, DocumentConversionInput
from docling.document_converter import DocumentConverter

Expand All @@ -24,6 +19,7 @@ def export_documents(

success_count = 0
failure_count = 0
partial_success_count = 0

for doc in converted_docs:
if doc.status == ConversionStatus.SUCCESS:
Expand All @@ -37,12 +33,21 @@ def export_documents(
# Export Markdown format:
with (output_dir / f"{doc_filename}.md").open("w") as fp:
fp.write(doc.render_as_markdown())
elif doc.status == ConversionStatus.PARTIAL_SUCCESS:
_log.info(
f"Document {doc.input.file} was partially converted with the following errors:"
)
for item in doc.errors:
_log.info(f"\t{item.error_message}")
partial_success_count += 1
else:
_log.info(f"Document {doc.input.file} failed to convert.")
failure_count += 1

_log.info(
f"Processed {success_count + failure_count} docs, of which {failure_count} failed"
f"Processed {success_count + partial_success_count + failure_count} docs, "
f"of which {failure_count} failed "
f"and {partial_success_count} were partially converted."
)


Expand All @@ -61,7 +66,7 @@ def main():
# docs = [DocumentStream(filename="my_doc.pdf", stream=buf)]
# input = DocumentConversionInput.from_streams(docs)

doc_converter = DocumentConverter(pipeline_options=PipelineOptions(do_ocr=False))
doc_converter = DocumentConverter()

input = DocumentConversionInput.from_paths(input_doc_paths)

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "docling"
version = "1.7.0" # DO NOT EDIT, updated automatically
version = "1.7.1" # DO NOT EDIT, updated automatically
description = "Docling PDF conversion package"
authors = ["Christoph Auer <[email protected]>", "Michele Dolfi <[email protected]>", "Maxim Lysak <[email protected]>", "Nikos Livathinos <[email protected]>", "Ahmed Nassar <[email protected]>", "Peter Staar <[email protected]>"]
license = "MIT"
Expand Down

0 comments on commit 1e30de6

Please sign in to comment.