-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(document-search): add support for images #121
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
57fbe14
feat(document-search): add support for images
konrad-czarnota-ds 85c055b
Merge branch 'main' into kc/add-support-for-images
konrad-czarnota-ds 0c184d0
Change pdf rendering library
konrad-czarnota-ds 651a567
Remove unused argument
konrad-czarnota-ds d52de07
Support images in example app
konrad-czarnota-ds 0be9224
Review fixes
konrad-czarnota-ds d3c628f
Make pdf class inherit from images and ignore mypy error
konrad-czarnota-ds cf3817a
Remove base class check
konrad-czarnota-ds c5ca279
Change LLMLite in ustructure providers to more generic LLM
konrad-czarnota-ds File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
...ts-document-search/src/ragbits/document_search/ingestion/providers/unstructured/images.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
from pathlib import Path | ||
from typing import Optional | ||
|
||
from PIL import Image | ||
from unstructured.chunking.basic import chunk_elements | ||
from unstructured.documents.elements import Element as UnstructuredElement | ||
from unstructured.documents.elements import ElementType | ||
|
||
from ragbits.core.llms.base import LLM | ||
from ragbits.core.llms.litellm import LiteLLM | ||
from ragbits.document_search.documents.document import DocumentMeta, DocumentType | ||
from ragbits.document_search.documents.element import Element, ImageElement | ||
from ragbits.document_search.ingestion.providers.unstructured.default import UnstructuredDefaultProvider | ||
from ragbits.document_search.ingestion.providers.unstructured.utils import ( | ||
ImageDescriber, | ||
crop_and_convert_to_bytes, | ||
extract_image_coordinates, | ||
to_text_element, | ||
) | ||
|
||
DEFAULT_LLM_IMAGE_SUMMARIZATION_MODEL = "gpt-4o-mini" | ||
|
||
|
||
class UnstructuredImageProvider(UnstructuredDefaultProvider): | ||
""" | ||
A specialized provider that handles pngs and jpgs using the Unstructured | ||
""" | ||
|
||
SUPPORTED_DOCUMENT_TYPES = { | ||
DocumentType.JPG, | ||
DocumentType.PNG, | ||
} | ||
|
||
def __init__( | ||
self, | ||
partition_kwargs: Optional[dict] = None, | ||
chunking_kwargs: Optional[dict] = None, | ||
api_key: Optional[str] = None, | ||
api_server: Optional[str] = None, | ||
use_api: bool = False, | ||
llm: Optional[LLM] = None, | ||
) -> None: | ||
"""Initialize the UnstructuredPdfProvider. | ||
|
||
Args: | ||
partition_kwargs: The additional arguments for the partitioning. Refer to the Unstructured API documentation | ||
for the available options: https://docs.unstructured.io/api-reference/api-services/api-parameters | ||
chunking_kwargs: The additional arguments for the chunking. | ||
api_key: The API key to use for the Unstructured API. If not specified, the UNSTRUCTURED_API_KEY environment | ||
variable will be used. | ||
api_server: The API server URL to use for the Unstructured API. If not specified, the | ||
UNSTRUCTURED_SERVER_URL environment variable will be used. | ||
llm: llm to use | ||
""" | ||
super().__init__(partition_kwargs, chunking_kwargs, api_key, api_server, use_api) | ||
self.image_summarizer = ImageDescriber(llm or LiteLLM(DEFAULT_LLM_IMAGE_SUMMARIZATION_MODEL)) | ||
|
||
async def _chunk_and_convert( | ||
self, elements: list[UnstructuredElement], document_meta: DocumentMeta, document_path: Path | ||
) -> list[Element]: | ||
image_elements = [e for e in elements if e.category == ElementType.IMAGE] | ||
other_elements = [e for e in elements if e.category != ElementType.IMAGE] | ||
chunked_other_elements = chunk_elements(other_elements, **self.chunking_kwargs) | ||
|
||
text_elements: list[Element] = [to_text_element(element, document_meta) for element in chunked_other_elements] | ||
if self.ignore_images: | ||
return text_elements | ||
return text_elements + [ | ||
await self._to_image_element(element, document_meta, document_path) for element in image_elements | ||
] | ||
|
||
async def _to_image_element( | ||
self, element: UnstructuredElement, document_meta: DocumentMeta, document_path: Path | ||
) -> ImageElement: | ||
top_x, top_y, bottom_x, bottom_y = extract_image_coordinates(element) | ||
image = self._load_document_as_image(document_path) | ||
top_x, top_y, bottom_x, bottom_y = self._convert_coordinates( | ||
top_x, top_y, bottom_x, bottom_y, image.width, image.height, element | ||
) | ||
|
||
img_bytes = crop_and_convert_to_bytes(image, top_x, top_y, bottom_x, bottom_y) | ||
image_description = await self.image_summarizer.get_image_description(img_bytes) | ||
return ImageElement( | ||
description=image_description, | ||
ocr_extracted_text=element.text, | ||
image_bytes=img_bytes, | ||
document_meta=document_meta, | ||
) | ||
|
||
@staticmethod | ||
def _load_document_as_image( | ||
document_path: Path, page: Optional[int] = None # pylint: disable=unused-argument | ||
) -> Image: | ||
return Image.open(document_path).convert("RGB") | ||
|
||
@staticmethod | ||
def _convert_coordinates( | ||
# pylint: disable=unused-argument | ||
top_x: float, | ||
top_y: float, | ||
bottom_x: float, | ||
bottom_y: float, | ||
image_width: int, | ||
image_height: int, | ||
element: UnstructuredElement, | ||
) -> tuple[float, float, float, float]: | ||
return top_x, top_y, bottom_x, bottom_y |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not a blocker for this PR but maybe this should use our built-in
core_config.default_llm_factory
functionality? Or if not (because there is no guarantee thatdefault_llm_factory
returns LLM that supports images) maybe we should have a separate config option for default visual LLM?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Created an issue for that, as discussed.