Skip to content

AIImageAnnotator

Base classes

Name Children Inherits
Annotator
docler.annotators.base
Base class for chunk annotation processors.
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  2532931700["ai_image_annotator.AIImageAnnotator"]
  808376040["base.Annotator"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  1753584424["provider.BaseProvider"]
  3481597255["typing.Generic"]
  808376040 --> 2532931700
  925645236 --> 808376040
  2751680898 --> 925645236
  1753584424 --> 808376040
  3481597255 --> 1753584424
  2751680898 --> 3481597255
  3481597255 --> 808376040
  3481597255 --> 2532931700

🛈 DocStrings

Bases: Annotator[AIImageAnnotatorConfig]

AI-based image annotator.

Analyzes images in chunks and adds descriptions and metadata.

Class Type Parameters:

Name Bound or Constraints Description Default
TMetadata Schema

Type of metadata model to use. Must be a Pydantic Schema.

DefaultImageMetadata
Source code in src/docler/annotators/ai_image_annotator.py
class AIImageAnnotator[TMetadata: Schema = DefaultImageMetadata](Annotator[AIImageAnnotatorConfig]):
    """AI-based image annotator.

    Analyzes images in chunks and adds descriptions and metadata.

    Type Parameters:
        TMetadata: Type of metadata model to use. Must be a Pydantic Schema.
    """

    Config = AIImageAnnotatorConfig

    REQUIRED_PACKAGES: ClassVar = {"agentpool"}

    def __init__(
        self,
        model: str | None = None,
        system_prompt: str | None = None,
        user_prompt: str | None = None,
        metadata_model: type[TMetadata] = DefaultImageMetadata,  # type: ignore
        batch_size: int = 3,
    ) -> None:
        """Initialize the AI image annotator.

        Args:
            model: Vision model to use (must support images)
            system_prompt: Custom prompt for image analysis
            user_prompt: Custom user prompt template for image analysis
            metadata_model: Pydantic model for image metadata
            batch_size: Number of images to process concurrently
        """
        super().__init__()
        self.model = model or DEFAULT_IMAGE_ANNOTATOR_MODEL
        self.system_prompt = system_prompt or DEFAULT_IMAGE_SYSTEM_PROMPT
        self.user_prompt = user_prompt or DEFAULT_IMAGE_PROMPT_TEMPLATE
        self.metadata_model = metadata_model
        self.batch_size = batch_size

    async def _process_image(self, image: Image) -> Image:
        """Process a single image with the vision model.

        Args:
            image: Image to analyze

        Returns:
            Image with added description and metadata
        """
        import base64

        from agentpool import Agent
        from pydantic_ai import BinaryImage

        if image.description and image.metadata:
            return image

        if isinstance(image.content, bytes):
            data = image.content
        else:
            data = base64.b64decode(image.content)
        img_content = BinaryImage(data=data, media_type=image.mime_type)
        agent = Agent(
            model=self.model,
            system_prompt=self.system_prompt,
            output_type=self.metadata_model,
        )

        try:
            filename_info = f" ({image.filename})" if image.filename else ""
            prompt = self.user_prompt.format(
                image_id=image.id,
                filename_info=filename_info,
                filename=image.filename or "",
                mime_type=image.mime_type,
            )

            result = await agent.run(prompt, img_content)
            metadata = result.content.model_dump()
            description = metadata.pop("description", None)
            if description:
                image.description = description
            image.metadata.update(metadata)

        except Exception:
            self.logger.exception("Error processing image %s", image.id)

        return image

    async def annotate(self, document: ChunkedDocument) -> ChunkedDocument:
        """Annotate all images in the chunks with AI-generated descriptions.

        Args:
            document: Chunked document containing chunks with images to annotate

        Returns:
            Document with annotated images in chunks
        """
        # Images of all chunks at once (an image shared by chunks only once).
        images = list({id(img): img for c in document.chunks for img in c.images}.values())
        semaphore = asyncio.Semaphore(self.batch_size)

        async def process(image: Image) -> None:
            async with semaphore:
                await self._process_image(image)  # logs its own errors

        await anyenv.gather(*(process(img) for img in images))
        return document

__init__

__init__(
    model: str | None = None,
    system_prompt: str | None = None,
    user_prompt: str | None = None,
    metadata_model: type[TMetadata] = DefaultImageMetadata,
    batch_size: int = 3,
) -> None

Initialize the AI image annotator.

Parameters:

Name Type Description Default
model str | None

Vision model to use (must support images)

None
system_prompt str | None

Custom prompt for image analysis

None
user_prompt str | None

Custom user prompt template for image analysis

None
metadata_model type[TMetadata]

Pydantic model for image metadata

DefaultImageMetadata
batch_size int

Number of images to process concurrently

3
Source code in src/docler/annotators/ai_image_annotator.py
def __init__(
    self,
    model: str | None = None,
    system_prompt: str | None = None,
    user_prompt: str | None = None,
    metadata_model: type[TMetadata] = DefaultImageMetadata,  # type: ignore
    batch_size: int = 3,
) -> None:
    """Initialize the AI image annotator.

    Args:
        model: Vision model to use (must support images)
        system_prompt: Custom prompt for image analysis
        user_prompt: Custom user prompt template for image analysis
        metadata_model: Pydantic model for image metadata
        batch_size: Number of images to process concurrently
    """
    super().__init__()
    self.model = model or DEFAULT_IMAGE_ANNOTATOR_MODEL
    self.system_prompt = system_prompt or DEFAULT_IMAGE_SYSTEM_PROMPT
    self.user_prompt = user_prompt or DEFAULT_IMAGE_PROMPT_TEMPLATE
    self.metadata_model = metadata_model
    self.batch_size = batch_size

annotate async

annotate(document: ChunkedDocument) -> ChunkedDocument

Annotate all images in the chunks with AI-generated descriptions.

Parameters:

Name Type Description Default
document ChunkedDocument

Chunked document containing chunks with images to annotate

required

Returns:

Type Description
ChunkedDocument

Document with annotated images in chunks

Source code in src/docler/annotators/ai_image_annotator.py
async def annotate(self, document: ChunkedDocument) -> ChunkedDocument:
    """Annotate all images in the chunks with AI-generated descriptions.

    Args:
        document: Chunked document containing chunks with images to annotate

    Returns:
        Document with annotated images in chunks
    """
    # Images of all chunks at once (an image shared by chunks only once).
    images = list({id(img): img for c in document.chunks for img in c.images}.values())
    semaphore = asyncio.Semaphore(self.batch_size)

    async def process(image: Image) -> None:
        async with semaphore:
            await self._process_image(image)  # logs its own errors

    await anyenv.gather(*(process(img) for img in images))
    return document

:fa-brands-github: Show source on GitHub