Skip to content
Open
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
20 changes: 8 additions & 12 deletions opencontext/context_processing/processor/document_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down Expand Up @@ -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}")

Expand Down Expand Up @@ -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]}..."
Expand All @@ -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}")

Expand Down
13 changes: 4 additions & 9 deletions opencontext/utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down