Skip to content

Commit 85209d2

Browse files
authored
fix: add support for base64 URLs to the image filter (#60)
1 parent e7a19fe commit 85209d2

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/banks/filters/image.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,25 @@
11
# SPDX-FileCopyrightText: 2023-present Massimiliano Pippi <mpippi@gmail.com>
22
#
33
# SPDX-License-Identifier: MIT
4+
import re
45
from pathlib import Path
56
from urllib.parse import urlparse
67

78
from banks.types import ContentBlock, ImageUrl
89

10+
BASE64_PATH_REGEX = re.compile(r"image\/.*;base64,.*")
11+
912

1013
def _is_url(string: str) -> bool:
1114
result = urlparse(string)
12-
return all([result.scheme, result.netloc])
15+
if not result.scheme:
16+
return False
17+
18+
if not result.netloc:
19+
# The only valid format when netloc is empty is base64 data urls
20+
return all([result.scheme == "data", BASE64_PATH_REGEX.match(result.path)])
21+
22+
return True
1323

1424

1525
def image(value: str) -> str:

tests/test_image.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,23 @@ def test_image_with_file_path(tmp_path):
5757
assert content_block["image_url"]["url"].startswith("data:image/jpeg;base64,")
5858

5959

60+
def test_image_base64(tmp_path):
61+
"""Test image filter with a binary input"""
62+
test_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABMgA"
63+
result = image(test_image)
64+
65+
# Verify the content block wrapper
66+
assert result.startswith("<content_block>")
67+
assert result.endswith("</content_block>")
68+
69+
# Parse the JSON content
70+
json_content = result[15:-16] # Remove wrapper tags
71+
content_block = json.loads(json_content)
72+
73+
assert content_block["type"] == "image_url"
74+
assert content_block["image_url"]["url"].startswith("data:image/png;base64,")
75+
76+
6077
def test_image_with_nonexistent_file():
6178
"""Test image filter with a nonexistent file path"""
6279
with pytest.raises(FileNotFoundError):

0 commit comments

Comments
 (0)