diff --git a/opencontext/context_processing/processor/document_converter.py b/opencontext/context_processing/processor/document_converter.py index 22b3109d..f2f29b7f 100644 --- a/opencontext/context_processing/processor/document_converter.py +++ b/opencontext/context_processing/processor/document_converter.py @@ -93,9 +93,8 @@ def _load_image(self, image_path: str) -> List[Image.Image]: """Load single image""" logger.info(f"Loading image: {image_path}") try: - img = Image.open(image_path) - if img.mode != "RGB": - img = img.convert("RGB") + with Image.open(image_path) as fp: + img = fp.convert("RGB") return [img] except Exception as e: logger.exception(f"Error loading image: {e}") @@ -395,9 +394,8 @@ def _extract_paragraph_images(self, paragraph, doc) -> List[Image.Image]: # Convert image data to PIL.Image import io - img = Image.open(io.BytesIO(image_data)) - if img.mode != "RGB": - img = img.convert("RGB") + with Image.open(io.BytesIO(image_data)) as fp: + img = fp.convert("RGB") images.append(img) logger.debug(f"Extracted image from paragraph: {img.size}") @@ -569,9 +567,8 @@ def _extract_markdown_images(self, md_text: str, md_dir: Path) -> tuple: # Handle remote image by downloading it with urllib.request.urlopen(img_path_str, timeout=10) as response: image_data = response.read() - img = Image.open(io.BytesIO(image_data)) - if img.mode != "RGB": - img = img.convert("RGB") + with Image.open(io.BytesIO(image_data)) as fp: + img = fp.convert("RGB") images.append(img) logger.debug( f"Successfully downloaded remote image: {img_path_str[:70]}..." @@ -589,9 +586,8 @@ def _extract_markdown_images(self, md_text: str, md_dir: Path) -> tuple: logger.warning(f"Local image file not found: {img_path}") continue - img = Image.open(img_path) - if img.mode != "RGB": - img = img.convert("RGB") + with Image.open(img_path) as fp: + img = fp.convert("RGB") images.append(img) logger.debug(f"Loaded local image: {img_path}") diff --git a/opencontext/utils/image.py b/opencontext/utils/image.py index 9a2cb0d9..1b20520f 100644 --- a/opencontext/utils/image.py +++ b/opencontext/utils/image.py @@ -21,11 +21,8 @@ def calculate_bytes2phash(image_bytes: bytes) -> Optional[str]: try: import io - from PIL import Image - - image = Image.open(io.BytesIO(image_bytes)) - hash_result = str(imagehash.dhash(image, hash_size=8)) - return hash_result + with Image.open(io.BytesIO(image_bytes)) as image: + return str(imagehash.dhash(image, hash_size=8)) except Exception: return None @@ -35,10 +32,8 @@ def calculate_phash(path: str) -> Optional[str]: Calculate perceptual hash of image file (cached). """ try: - from PIL import Image - - image = Image.open(path) - return str(imagehash.dhash(image, hash_size=8)) + with Image.open(path) as image: + return str(imagehash.dhash(image, hash_size=8)) except Exception: return None