Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions docreader/parser/docx_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -965,8 +965,8 @@ def _collect_process_results(self, future_to_idx, args_list, batch_start_time):
# Collect temporary image paths for later cleanup
for line in page_lines:
for image_data in line.images:
if image_data.local_path and image_data.local_path.startswith(
"/tmp/docx_img_"
if image_data.local_path and _is_temp_image_file(
image_data.local_path
):
temp_img_paths.add(image_data.local_path)

Expand Down Expand Up @@ -1139,9 +1139,7 @@ def _cleanup_temp_image_files(self, temp_paths):
# Delete temporary directory (if empty)
try:
temp_dir = os.path.dirname(path)
if temp_dir.startswith("/tmp/docx_img_") and os.path.exists(
temp_dir
):
if _is_temp_image_dir(temp_dir) and os.path.exists(temp_dir):
os.rmdir(temp_dir)
except OSError:
# If directory is not empty, ignore error
Expand Down Expand Up @@ -1261,6 +1259,30 @@ def _safe_concat_images(self, images):
return images[0]


# ``_save_image_to_temp`` gives every image its own ``tempfile.mkdtemp``
# directory. Cleanup used to recognise them by the literal POSIX prefix
# ``/tmp/docx_img_``, which never matches on Windows: ``mkdtemp`` there returns
# ``C:\Users\...\Temp\docx_img_xxxx``, so no path was collected and every
# multimodal parse left its PNGs (and their directories) behind.
_DOCX_IMAGE_TEMP_PREFIX = "docx_img_"


def _is_temp_image_dir(path):
"""Whether *path* is one of the directories ``_save_image_to_temp`` made."""
if not path:
return False
return os.path.basename(os.path.normpath(path)).startswith(
_DOCX_IMAGE_TEMP_PREFIX
)


def _is_temp_image_file(path):
"""Whether *path* is an image written by ``_save_image_to_temp``."""
if not path:
return False
return _is_temp_image_dir(os.path.dirname(path))


def _save_image_to_temp(logger, image, page_num, img_idx):
"""Save image to a temporary file to pass between processes

Expand Down
38 changes: 38 additions & 0 deletions docreader/tests/test_docx_temp_images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import logging
import os
import unittest

from PIL import Image

from docreader.parser.docx_parser import (
Docx,
_is_temp_image_file,
_save_image_to_temp,
)


class TempImageCleanupTest(unittest.TestCase):
def test_an_image_saved_for_a_worker_is_collected_and_removed(self):
logger = logging.getLogger("docx-temp-image-test")
path = _save_image_to_temp(logger, Image.new("RGB", (4, 4)), 1, 0)
self.assertIsNotNone(path)
self.addCleanup(lambda: os.path.exists(path) and os.unlink(path))
self.assertTrue(os.path.exists(path))

# The collector recognised temporary images by the literal POSIX
# prefix "/tmp/docx_img_", which never matches a Windows temp path.
self.assertTrue(_is_temp_image_file(path))

Docx()._cleanup_temp_image_files({path})

self.assertFalse(os.path.exists(path))
self.assertFalse(os.path.exists(os.path.dirname(path)))

def test_a_path_outside_the_image_temp_dirs_is_not_collected(self):
self.assertFalse(_is_temp_image_file(None))
self.assertFalse(_is_temp_image_file(""))
self.assertFalse(_is_temp_image_file(os.path.join("some", "dir", "a.png")))


if __name__ == "__main__":
unittest.main()