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
10 changes: 10 additions & 0 deletions ollama/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,16 @@ def serialize_model(self):
return b64encode(self.value.read_bytes() if isinstance(self.value, Path) else self.value).decode()

if isinstance(self.value, str):
if self.value.lower().startswith('data:'):
header, separator, encoded = self.value.partition(',')
if not separator or not encoded or not header.lower().startswith('data:image/') or not header.lower().endswith(';base64'):
raise ValueError('Invalid image data URI, expected a base64-encoded image')
try:
b64decode(encoded, validate=True)
except Exception as exc:
raise ValueError('Invalid image data URI, expected a base64-encoded image') from exc
return encoded

try:
if Path(self.value).exists():
return b64encode(Path(self.value).read_bytes()).decode()
Expand Down
25 changes: 25 additions & 0 deletions tests/test_image_data_uri.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import base64

import pytest

from ollama._types import Image


def test_image_data_uri_serializes_as_base64():
encoded = base64.b64encode(b'example image bytes').decode()
assert Image(value=f'data:image/png;base64,{encoded}').model_dump() == encoded
assert Image(value=f'DATA:IMAGE/PNG;BASE64,{encoded}').model_dump() == encoded


@pytest.mark.parametrize(
'value',
[
'data:image/png,not-base64',
'data:image/png;base64,invalid!',
'data:image/png;base64,',
'data:text/plain;base64,ZXhhbXBsZQ==',
],
)
def test_invalid_image_data_uri_raises(value: str):
with pytest.raises(ValueError, match='Invalid image data URI'):
Image(value=value).model_dump()