feat: allow computing page images on-demand and cache them

Signed-off-by: Michele Dolfi <dol@zurich.ibm.com>
This commit is contained in:
Michele Dolfi 2024-08-20 09:33:57 +02:00
parent 778e51ef18
commit 35e90b66d7
7 changed files with 37 additions and 22 deletions

View File

@ -80,7 +80,9 @@ class DoclingParsePageBackend(PdfPageBackend):
cell_counter += 1 cell_counter += 1
def draw_clusters_and_cells(): def draw_clusters_and_cells():
image = self.get_page_image() image = (
self.get_page_image()
) # make new image to avoid drawing on the saved ones
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
for c in cells: for c in cells:
x0, y0, x1, y1 = c.bbox.as_tuple() x0, y0, x1, y1 = c.bbox.as_tuple()

View File

@ -134,7 +134,9 @@ class PyPdfiumPageBackend(PdfPageBackend):
return merged_cells return merged_cells
def draw_clusters_and_cells(): def draw_clusters_and_cells():
image = self.get_page_image() image = (
self.get_page_image()
) # make new image to avoid drawing on the saved ones
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
for c in cells: for c in cells:
x0, y0, x1, y1 = c.bbox.as_tuple() x0, y0, x1, y1 = c.bbox.as_tuple()

View File

@ -234,14 +234,29 @@ class Page(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True) model_config = ConfigDict(arbitrary_types_allowed=True)
page_no: int page_no: int
page_hash: str = None page_hash: Optional[str] = None
size: PageSize = None size: Optional[PageSize] = None
image: Image = None
cells: List[Cell] = None cells: List[Cell] = None
predictions: PagePredictions = PagePredictions() predictions: PagePredictions = PagePredictions()
assembled: AssembledUnit = None assembled: Optional[AssembledUnit] = None
_backend: PdfPageBackend = None # Internal PDF backend _backend: Optional[PdfPageBackend] = (
None # Internal PDF backend. By default it is cleared during assembling.
)
_image_cache: Dict[float, Image] = (
{}
) # Cache of images in different scales. By default it is cleared during assembling.
def get_image(self, scale: float = 1.0) -> Optional[Image]:
if self._backend is None:
return self._image_cache.get(scale, None)
if not scale in self._image_cache:
self._image_cache[scale] = self._backend.get_page_image(scale=scale)
return self._image_cache[scale]
@property
def image(self) -> Optional[Image]:
return self.get_image()
class DocumentStream(BaseModel): class DocumentStream(BaseModel):

View File

@ -189,9 +189,7 @@ class DocumentConverter:
# Remove page images (can be disabled) # Remove page images (can be disabled)
if not self.assemble_options.keep_page_images: if not self.assemble_options.keep_page_images:
assembled_page.image = ( assembled_page._image_cache = {}
None # Comment this if you want to visualize page images
)
# Unload backend # Unload backend
assembled_page._backend.unload() assembled_page._backend.unload()
@ -231,7 +229,7 @@ class DocumentConverter:
# Generate the page image and store it in the page object # Generate the page image and store it in the page object
def populate_page_images(self, doc: InputDocument, page: Page) -> Page: def populate_page_images(self, doc: InputDocument, page: Page) -> Page:
page.image = page._backend.get_page_image() page.get_image() # this will trigger storing the image in the internal cache
return page return page
@ -247,7 +245,7 @@ class DocumentConverter:
draw.rectangle([(x0, y0), (x1, y1)], outline="red") draw.rectangle([(x0, y0), (x1, y1)], outline="red")
image.show() image.show()
# draw_text_boxes(page.image, cells) # draw_text_boxes(page.get_image(scale=1.0), cells)
return page return page

View File

@ -30,7 +30,7 @@ class EasyOcrModel:
for page in page_batch: for page in page_batch:
# rects = page._fpage. # rects = page._fpage.
high_res_image = page._backend.get_page_image(scale=self.scale) high_res_image = page.get_image(scale=self.scale)
im = numpy.array(high_res_image) im = numpy.array(high_res_image)
result = self.reader.readtext(im) result = self.reader.readtext(im)

View File

@ -267,7 +267,9 @@ class LayoutModel:
def __call__(self, page_batch: Iterable[Page]) -> Iterable[Page]: def __call__(self, page_batch: Iterable[Page]) -> Iterable[Page]:
for page in page_batch: for page in page_batch:
clusters = [] clusters = []
for ix, pred_item in enumerate(self.layout_predictor.predict(page.image)): for ix, pred_item in enumerate(
self.layout_predictor.predict(page.get_image(scale=1.0))
):
cluster = Cluster( cluster = Cluster(
id=ix, id=ix,
label=pred_item["label"], label=pred_item["label"],

View File

@ -34,7 +34,9 @@ class TableStructureModel:
self.scale = 2.0 # Scale up table input images to 144 dpi self.scale = 2.0 # Scale up table input images to 144 dpi
def draw_table_and_cells(self, page: Page, tbl_list: List[TableElement]): def draw_table_and_cells(self, page: Page, tbl_list: List[TableElement]):
image = page._backend.get_page_image() image = (
page._backend.get_page_image()
) # make new image to avoid drawing on the saved ones
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
for table_element in tbl_list: for table_element in tbl_list:
@ -94,13 +96,7 @@ class TableStructureModel:
"width": page.size.width * self.scale, "width": page.size.width * self.scale,
"height": page.size.height * self.scale, "height": page.size.height * self.scale,
} }
# add image to page input. page_input["image"] = numpy.asarray(page.get_image(scale=self.scale))
if self.scale == 1.0:
page_input["image"] = numpy.asarray(page.image)
else: # render new page image on the fly at desired scale
page_input["image"] = numpy.asarray(
page._backend.get_page_image(scale=self.scale)
)
table_clusters, table_bboxes = zip(*in_tables) table_clusters, table_bboxes = zip(*in_tables)