Skip to content

Commit

Permalink
Fix image serialization for long image string (#348)
Browse files Browse the repository at this point in the history
  • Loading branch information
ParthSareen authored Nov 28, 2024
1 parent b50a65b commit d6528cf
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
9 changes: 7 additions & 2 deletions ollama/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,14 @@ 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 Path(self.value).exists():
return b64encode(Path(self.value).read_bytes()).decode()
try:
if Path(self.value).exists():
return b64encode(Path(self.value).read_bytes()).decode()
except Exception:
# Long base64 string can't be wrapped in Path, so try to treat as base64 string
pass

# String might be a file path, but might not exist
if self.value.split('.')[-1] in ('png', 'jpg', 'jpeg', 'webp'):
raise ValueError(f'File {self.value} does not exist')

Expand Down
6 changes: 6 additions & 0 deletions tests/test_type_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ def test_image_serialization_base64_string():
assert img.model_dump() == b64_str # Should return as-is if valid base64


def test_image_serialization_long_base64_string():
b64_str = 'dGVzdCBiYXNlNjQgc3RyaW5n' * 1000
img = Image(value=b64_str)
assert img.model_dump() == b64_str # Should return as-is if valid base64


def test_image_serialization_plain_string():
img = Image(value='not a path or base64')
assert img.model_dump() == 'not a path or base64' # Should return as-is
Expand Down

0 comments on commit d6528cf

Please sign in to comment.