WeKnora/docreader/parser/image_parser.py

69 lines
2.3 KiB
Python
Raw Normal View History

2025-08-05 07:08:07 +00:00
import logging
import os
import asyncio
from PIL import Image
import io
2025-08-13 13:56:20 +00:00
from typing import Dict, Any, Tuple, Union
2025-08-05 07:08:07 +00:00
from .base_parser import BaseParser, ParseResult
import numpy as np
# Set up logger for this module
logger = logging.getLogger(__name__)
2025-08-13 13:56:20 +00:00
logger.setLevel(logging.INFO)
2025-08-05 07:08:07 +00:00
class ImageParser(BaseParser):
"""
Parser for image files with OCR capability.
Extracts text from images and generates captions.
This parser handles image processing by:
1. Uploading the image to storage
2. Generating a descriptive caption
3. Performing OCR to extract text content
4. Returning a combined result with both text and image reference
"""
2025-08-13 13:56:20 +00:00
def parse_into_text(self, content: bytes) -> Union[str, Tuple[str, Dict[str, Any]]]:
2025-08-05 07:08:07 +00:00
"""
2025-08-13 13:56:20 +00:00
Parse image content, upload the image and return Markdown reference along with image map.
2025-08-05 07:08:07 +00:00
Args:
content: Raw image data (bytes)
Returns:
2025-08-13 13:56:20 +00:00
Tuple of (markdown_text, image_map) where image_map maps image URLs to PIL Image objects
2025-08-05 07:08:07 +00:00
"""
logger.info(f"Parsing image content, size: {len(content)} bytes")
2025-08-13 13:56:20 +00:00
image_map = {}
2025-08-05 07:08:07 +00:00
try:
# Upload image to storage service
logger.info("Uploading image to storage")
_, ext = os.path.splitext(self.file_name)
2025-08-13 13:56:20 +00:00
image_url = self.upload_bytes(content, file_ext=ext)
2025-08-05 07:08:07 +00:00
if not image_url:
logger.error("Failed to upload image to storage")
2025-08-13 13:56:20 +00:00
return "", {}
2025-08-05 07:08:07 +00:00
logger.info(
f"Successfully uploaded image, URL: {image_url[:50]}..."
if len(image_url) > 50
else f"Successfully uploaded image, URL: {image_url}"
)
2025-08-13 13:56:20 +00:00
# Create image object and add to map
try:
from PIL import Image
import io
image = Image.open(io.BytesIO(content))
image_map[image_url] = image
logger.info(f"Added image to image_map for URL: {image_url}")
except Exception as img_err:
logger.error(f"Error creating image object: {str(img_err)}")
2025-08-05 07:08:07 +00:00
2025-08-13 13:56:20 +00:00
markdown_text = f"![{self.file_name}]({image_url})"
return markdown_text, image_map
2025-08-05 07:08:07 +00:00
except Exception as e:
logger.error(f"Error parsing image: {str(e)}")
2025-08-13 13:56:20 +00:00
return "", {}