fix(python): preserve local paths for Jina image embeddings (#5256)

Fixes #5255.

## Problem

The Python Jina adapter treats local paths as URL paths when opening an
image. This strips a literal `#` and anything after it from a filename.
It also passes the encoded path from a `file:` URI straight to Pillow,
so a URI returned by `Path.as_uri()` fails for filenames containing
spaces or non-ASCII characters.

## Changes

- Pass filesystem paths to Pillow as supplied and convert explicit
`file:` URI paths with Python's platform-specific `url2pathname`.
- Cover a path containing a literal `#` and a file URI for a filename
containing spaces, Unicode, `#`, and `%`.

## Validation

- Both filename regressions fail on `main` with `FileNotFoundError` and
pass after the change.
- `pytest python/tests/test_embeddings.py -q -k jina` passed all three
selected tests, using the matching `0.42.0b38` native extension and the
Python sources from this checkout. The Jina API call is stubbed in the
regression.
- Ruff formatting and lint checks passed for both changed files.

AI-assisted implementation and testing.
This commit is contained in:
Divyam Talwar
2026-11-30 20:12:11 +08:00
committed by GitHub
parent 3b8584cd7d
commit 2d7dceaad1
2 changed files with 29 additions and 6 deletions
+10 -5
View File
@@ -7,6 +7,7 @@ import io
import base64
from functools import cached_property
from urllib.parse import urlparse
from urllib.request import url2pathname
from pathlib import Path
from typing import TYPE_CHECKING, List, Union, Optional, Any, Dict
@@ -87,14 +88,18 @@ class JinaEmbeddings(EmbeddingFunction):
if isinstance(image, bytes):
image_dict = {"image": base64.b64encode(image).decode("utf-8")}
elif isinstance(image, (str, Path)):
parsed = urlparse(str(image))
parsed = urlparse(image) if isinstance(image, str) else None
PIL_Image = attempt_import_or_raise("PIL.Image", "pillow")
if parsed.scheme == "file":
pil_image = PIL_Image.open(parsed.path)
elif parsed.scheme == "" or (os.name == "nt" and len(parsed.scheme) == 1):
if (
parsed is None
or not parsed.scheme
or (os.name == "nt" and len(parsed.scheme) == 1)
):
# A Windows drive letter parses as a one-character scheme
# ("C:\\img.png" -> scheme="c"), so treat it as a local path.
pil_image = PIL_Image.open(image if os.name == "nt" else parsed.path)
pil_image = PIL_Image.open(image)
elif parsed.scheme == "file":
pil_image = PIL_Image.open(url2pathname(parsed.path))
elif parsed.scheme.startswith("http"):
pil_image = PIL_Image.open(io.BytesIO(url_retrieve(image)))
else:
+19 -1
View File
@@ -1241,7 +1241,7 @@ def test_jina_generate_image_input_dict_local_path(tmp_path):
Image = pytest.importorskip("PIL.Image")
from lancedb.embeddings.jinaai import JinaEmbeddings
image_path = tmp_path / "test.png"
image_path = tmp_path / "test image #1.png"
Image.new("RGB", (4, 4), color="red").save(image_path, format="PNG")
for image in (str(image_path), image_path):
@@ -1250,6 +1250,24 @@ def test_jina_generate_image_input_dict_local_path(tmp_path):
assert isinstance(image_dict["image"], str) and len(image_dict["image"]) > 0
def test_jina_embeds_a_file_uri_as_an_image(tmp_path):
image_module = pytest.importorskip("PIL.Image")
from lancedb.embeddings.jinaai import JinaEmbeddings
image_path = tmp_path / "photo \u2603 #1%.png"
image = image_module.new("RGB", (4, 4), color="red")
image.save(image_path)
image_uri = image_path.as_uri()
expected_input = JinaEmbeddings._generate_image_input_dict(image)
embedding = JinaEmbeddings()
with patch.object(
JinaEmbeddings, "_generate_embeddings", return_value=[[0.0]]
) as embed:
assert embedding.generate_image_embedding(image_uri) == [0.0]
embed.assert_called_once_with(input=[expected_input])
def test_jina_embeddings_use_their_own_api_key(monkeypatch):
"""Each JinaEmbeddings instance must send its own API key."""
pytest.importorskip("requests")