-
Notifications
You must be signed in to change notification settings - Fork 979
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
draft for picture description models
Signed-off-by: Michele Dolfi <[email protected]>
- Loading branch information
1 parent
6c22cba
commit e1cba8a
Showing
5 changed files
with
279 additions
and
2 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
import base64 | ||
import io | ||
import logging | ||
from typing import List, Optional | ||
|
||
import httpx | ||
from docling_core.types.doc import PictureItem | ||
from docling_core.types.doc.document import ( # TODO: move import to docling_core.types.doc | ||
PictureDescriptionData, | ||
) | ||
from pydantic import BaseModel, ConfigDict | ||
|
||
from docling.datamodel.pipeline_options import PicDescApiOptions | ||
from docling.models.pic_description_base_model import PictureDescriptionBaseModel | ||
|
||
_log = logging.getLogger(__name__) | ||
|
||
|
||
class ChatMessage(BaseModel): | ||
role: str | ||
content: str | ||
|
||
|
||
class ResponseChoice(BaseModel): | ||
index: int | ||
message: ChatMessage | ||
finish_reason: str | ||
|
||
|
||
class ResponseUsage(BaseModel): | ||
prompt_tokens: int | ||
completion_tokens: int | ||
total_tokens: int | ||
|
||
|
||
class ApiResponse(BaseModel): | ||
model_config = ConfigDict( | ||
protected_namespaces=(), | ||
) | ||
|
||
id: str | ||
model: Optional[str] = None # returned bu openai | ||
choices: List[ResponseChoice] | ||
created: int | ||
usage: ResponseUsage | ||
|
||
|
||
class PictureDescriptionApiModel(PictureDescriptionBaseModel): | ||
|
||
def __init__(self, enabled: bool, options: PicDescApiOptions): | ||
super().__init__(enabled=enabled, options=options) | ||
self.options: PicDescApiOptions | ||
|
||
def _annotate_image(self, picture: PictureItem) -> PictureDescriptionData: | ||
assert picture.image is not None | ||
|
||
img_io = io.BytesIO() | ||
picture.image.pil_image.save(img_io, "PNG") | ||
|
||
image_base64 = base64.b64encode(img_io.getvalue()).decode("utf-8") | ||
|
||
messages = [ | ||
{ | ||
"role": "user", | ||
"content": [ | ||
{ | ||
"type": "text", | ||
"text": self.options.llm_prompt, | ||
}, | ||
{ | ||
"type": "image_url", | ||
"image_url": {"url": f"data:image/png;base64,{image_base64}"}, | ||
}, | ||
], | ||
} | ||
] | ||
|
||
payload = { | ||
"messages": messages, | ||
**self.options.params, | ||
} | ||
|
||
r = httpx.post( | ||
str(self.options.url), | ||
headers=self.options.headers, | ||
json=payload, | ||
timeout=self.options.timeout, | ||
) | ||
if not r.is_success: | ||
_log.error(f"Error calling the API. Reponse was {r.text}") | ||
r.raise_for_status() | ||
|
||
api_resp = ApiResponse.model_validate_json(r.text) | ||
generated_text = api_resp.choices[0].message.content.strip() | ||
|
||
return PictureDescriptionData( | ||
provenance=self.options.provenance, | ||
text=generated_text, | ||
) |
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,46 @@ | ||
import logging | ||
from pathlib import Path | ||
from typing import Any, Iterable | ||
|
||
from docling_core.types.doc import ( | ||
DoclingDocument, | ||
NodeItem, | ||
PictureClassificationClass, | ||
PictureItem, | ||
) | ||
from docling_core.types.doc.document import ( # TODO: move import to docling_core.types.doc | ||
PictureDescriptionData, | ||
) | ||
|
||
from docling.datamodel.pipeline_options import PicDescBaseOptions | ||
from docling.models.base_model import BaseEnrichmentModel | ||
|
||
|
||
class PictureDescriptionBaseModel(BaseEnrichmentModel): | ||
|
||
def __init__(self, enabled: bool, options: PicDescBaseOptions): | ||
self.enabled = enabled | ||
self.options = options | ||
self.provenance = "TODO" | ||
|
||
def is_processable(self, doc: DoclingDocument, element: NodeItem) -> bool: | ||
# TODO: once the image classifier is active, we can differentiate among image types | ||
return self.enabled and isinstance(element, PictureItem) | ||
|
||
def _annotate_image(self, picture: PictureItem) -> PictureDescriptionData: | ||
raise NotImplemented | ||
|
||
def __call__( | ||
self, doc: DoclingDocument, element_batch: Iterable[NodeItem] | ||
) -> Iterable[Any]: | ||
if not self.enabled: | ||
return | ||
|
||
for element in element_batch: | ||
assert isinstance(element, PictureItem) | ||
assert element.image is not None | ||
|
||
annotation = self._annotate_image(element) | ||
element.annotations.append(annotation) | ||
|
||
yield element |
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,59 @@ | ||
import json | ||
from typing import List | ||
|
||
from docling_core.types.doc import PictureItem | ||
from docling_core.types.doc.document import ( # TODO: move import to docling_core.types.doc | ||
PictureDescriptionData, | ||
) | ||
|
||
from docling.datamodel.pipeline_options import PicDescVllmOptions | ||
from docling.models.pic_description_base_model import PictureDescriptionBaseModel | ||
|
||
|
||
class PictureDescriptionVllmModel(PictureDescriptionBaseModel): | ||
|
||
def __init__(self, enabled: bool, options: PicDescVllmOptions): | ||
super().__init__(enabled=enabled, options=options) | ||
self.options: PicDescVllmOptions | ||
|
||
if self.enabled: | ||
raise NotImplemented | ||
|
||
if self.enabled: | ||
try: | ||
from vllm import LLM, SamplingParams # type: ignore | ||
except ImportError: | ||
raise ImportError( | ||
"VLLM is not installed. Please install Docling with the required extras `pip install docling[vllm]`." | ||
) | ||
|
||
self.sampling_params = SamplingParams(**self.options.sampling_params) # type: ignore | ||
self.llm = LLM(model=self.options.llm_name, **self.options.llm_extra) # type: ignore | ||
|
||
# Generate a stable hash from the extra parameters | ||
def create_hash(t): | ||
return "" | ||
|
||
params_hash = create_hash( | ||
json.dumps(self.options.llm_extra, sort_keys=True) | ||
+ json.dumps(self.options.sampling_params, sort_keys=True) | ||
) | ||
self.provenance = f"{self.options.llm_name}-{params_hash[:8]}" | ||
|
||
def _annotate_image(self, picture: PictureItem) -> PictureDescriptionData: | ||
assert picture.image is not None | ||
|
||
from vllm import RequestOutput | ||
|
||
inputs = [ | ||
{ | ||
"prompt": self.options.llm_prompt, | ||
"multi_modal_data": {"image": picture.image.pil_image}, | ||
} | ||
] | ||
outputs: List[RequestOutput] = self.llm.generate( # type: ignore | ||
inputs, sampling_params=self.sampling_params # type: ignore | ||
) | ||
|
||
generated_text = outputs[0].outputs[0].text | ||
return PictureDescriptionData(provenance=self.provenance, text=generated_text) |
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