mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat(python): support SigLIP image search with OpenCLIP (#5355)
## Summary - Use the existing OpenCLIP provider with the SigLIP SO400M checkpoint to embed image files and search them from Python. - Accept filesystem path objects for vector queries and preserve Windows drive letters and special characters in image ingestion paths. String queries continue to use the text encoder. - Add sync and async regression tests and a generated, runnable documentation example. Refs #4767 ## Validation - Embedding suite with 122 passing tests, CI-pinned Ruff, Linux-targeted Pyright, and strict MkDocs. - The real SigLIP checkpoint returned 1,152-dimensional unit-normalized vectors and ranked the matching image first. The Windows smoke test used the non-mapped safetensors reader and one shared model instance. - Five row-address tests also failed with the preview native extension on the unmodified base. The source-built CI run will cover these tests.
This commit is contained in:
@@ -6,6 +6,7 @@ import concurrent.futures
|
||||
import io
|
||||
import os
|
||||
import urllib.parse as urlparse
|
||||
from contextlib import nullcontext
|
||||
from typing import TYPE_CHECKING, List, Union
|
||||
from urllib.request import url2pathname
|
||||
|
||||
@@ -62,24 +63,23 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
||||
return self._ndims
|
||||
|
||||
def compute_query_embeddings(
|
||||
self, query: Union[str, "PIL.Image.Image"], *args, **kwargs
|
||||
self, query: Union[str, os.PathLike[str], "PIL.Image.Image"], *args, **kwargs
|
||||
) -> List[np.ndarray]:
|
||||
"""
|
||||
Compute the embeddings for a given user query
|
||||
|
||||
Parameters
|
||||
----------
|
||||
query : Union[str, PIL.Image.Image]
|
||||
The query to embed. A query can be either text or an image.
|
||||
query : Union[str, os.PathLike[str], PIL.Image.Image]
|
||||
Strings are text queries. Pass a path object or a PIL image for an
|
||||
image query.
|
||||
"""
|
||||
if isinstance(query, str):
|
||||
return [self.generate_text_embeddings(query)]
|
||||
else:
|
||||
PIL_Image = attempt_import_or_raise("PIL.Image", "pillow")
|
||||
if isinstance(query, PIL_Image.Image):
|
||||
return [self.generate_image_embedding(query)]
|
||||
else:
|
||||
raise TypeError("OpenClip supports str or PIL Image as query")
|
||||
PIL_Image = attempt_import_or_raise("PIL.Image", "pillow")
|
||||
if isinstance(query, (os.PathLike, PIL_Image.Image)):
|
||||
return [self.generate_image_embedding(query)]
|
||||
raise TypeError("OpenCLIP queries must be text, a path object, or a PIL image")
|
||||
|
||||
def generate_text_embeddings(self, text: str) -> np.ndarray:
|
||||
torch = attempt_import_or_raise("torch")
|
||||
@@ -130,41 +130,52 @@ class OpenClipEmbeddings(EmbeddingFunction):
|
||||
return [future.result() for future in tqdm(futures)]
|
||||
|
||||
def generate_image_embedding(
|
||||
self, image: Union[str, bytes, "PIL.Image.Image"]
|
||||
self, image: Union[str, bytes, os.PathLike[str], "PIL.Image.Image"]
|
||||
) -> np.ndarray:
|
||||
"""
|
||||
Generate the embedding for a single image
|
||||
|
||||
Parameters
|
||||
----------
|
||||
image : Union[str, bytes, PIL.Image.Image]
|
||||
The image to embed. If the image is a str, it is treated as a uri.
|
||||
If the image is bytes, it is treated as the raw image bytes.
|
||||
image : Union[str, bytes, os.PathLike[str], PIL.Image.Image]
|
||||
The image to embed. Accepts a filesystem path, a URI, encoded image
|
||||
bytes, or a PIL image.
|
||||
"""
|
||||
torch = attempt_import_or_raise("torch")
|
||||
# TODO handle retry and errors for https
|
||||
image = self._to_pil(image)
|
||||
image = self._preprocess(image).unsqueeze(0)
|
||||
pil_image = self._to_pil(image)
|
||||
# Close images opened here while leaving caller-owned PIL images open.
|
||||
image_context = nullcontext(pil_image) if pil_image is image else pil_image
|
||||
with image_context as opened:
|
||||
image_tensor = self._preprocess(opened).unsqueeze(0)
|
||||
with torch.no_grad():
|
||||
return self._encode_and_normalize_image(image)
|
||||
return self._encode_and_normalize_image(image_tensor)
|
||||
|
||||
def _to_pil(self, image: Union[str, bytes]):
|
||||
def _to_pil(self, image: Union[str, bytes, os.PathLike[str], "PIL.Image.Image"]):
|
||||
PIL_Image = attempt_import_or_raise("PIL.Image", "pillow")
|
||||
if isinstance(image, bytes):
|
||||
return PIL_Image.open(io.BytesIO(image))
|
||||
if isinstance(image, PIL_Image.Image):
|
||||
return image
|
||||
elif isinstance(image, str):
|
||||
if isinstance(image, os.PathLike):
|
||||
return PIL_Image.open(image)
|
||||
if isinstance(image, str):
|
||||
# On Windows a drive prefix can look like a URI scheme.
|
||||
if os.path.splitdrive(image)[0]:
|
||||
return PIL_Image.open(image)
|
||||
parsed = urlparse.urlparse(image)
|
||||
# TODO handle drive letter on windows.
|
||||
if not parsed.scheme:
|
||||
return PIL_Image.open(image)
|
||||
if parsed.scheme == "file":
|
||||
return PIL_Image.open(url2pathname(parsed.path))
|
||||
elif parsed.scheme == "":
|
||||
return PIL_Image.open(image if os.name == "nt" else parsed.path)
|
||||
elif parsed.scheme.startswith("http"):
|
||||
if parsed.scheme.startswith("http"):
|
||||
return PIL_Image.open(io.BytesIO(url_retrieve(image)))
|
||||
else:
|
||||
raise NotImplementedError("Only local and http(s) urls are supported")
|
||||
raise NotImplementedError(
|
||||
"Only filesystem paths and HTTP(S) URLs are supported"
|
||||
)
|
||||
raise TypeError(
|
||||
"OpenCLIP images must be a path, URI, encoded bytes, or a PIL image"
|
||||
)
|
||||
|
||||
def _encode_and_normalize_image(self, image_tensor: "torch.Tensor"):
|
||||
"""
|
||||
|
||||
@@ -828,7 +828,7 @@ class RemoteTable(Table):
|
||||
|
||||
def search(
|
||||
self,
|
||||
query: Union[VEC, str] = None,
|
||||
query: Union[VEC, str, os.PathLike[str]] = None,
|
||||
vector_column_name: Optional[str] = None,
|
||||
query_type="auto",
|
||||
ordering_field_name: Optional[str] = None,
|
||||
@@ -872,6 +872,8 @@ class RemoteTable(Table):
|
||||
|
||||
- *default None*.
|
||||
Acceptable types are: list, np.ndarray, PIL.Image.Image
|
||||
Use a path object with `query_type="vector"` when the embedding
|
||||
function supports image files.
|
||||
|
||||
vector_column_name: str, optional
|
||||
The name of the vector column to search.
|
||||
|
||||
@@ -14,6 +14,7 @@ from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from functools import cached_property
|
||||
from itertools import chain
|
||||
from os import PathLike
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
@@ -2733,7 +2734,7 @@ class Table(ABC):
|
||||
def search(
|
||||
self,
|
||||
query: Optional[
|
||||
Union[VEC, str, "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
Union[VEC, str, PathLike[str], "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
] = None,
|
||||
vector_column_name: Optional[str] = None,
|
||||
query_type: QueryType = "auto",
|
||||
@@ -2777,6 +2778,8 @@ class Table(ABC):
|
||||
|
||||
- *default None*.
|
||||
Acceptable types are: list, np.ndarray, PIL.Image.Image
|
||||
Use a path object with `query_type="vector"` when the embedding
|
||||
function supports image files.
|
||||
|
||||
- If None then the select/where/limit clauses are applied to filter
|
||||
the table
|
||||
@@ -6063,7 +6066,9 @@ class LanceTable(Table):
|
||||
@overload
|
||||
def search( # type: ignore
|
||||
self,
|
||||
query: Optional[Union[VEC, str, "PIL.Image.Image", Tuple]] = None,
|
||||
query: Optional[
|
||||
Union[VEC, str, PathLike[str], "PIL.Image.Image", Tuple]
|
||||
] = None,
|
||||
vector_column_name: Optional[str] = None,
|
||||
query_type: Literal["vector"] = "vector",
|
||||
ordering_field_name: Optional[str] = None,
|
||||
@@ -6117,7 +6122,7 @@ class LanceTable(Table):
|
||||
def search(
|
||||
self,
|
||||
query: Optional[
|
||||
Union[VEC, str, "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
Union[VEC, str, PathLike[str], "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
] = None,
|
||||
vector_column_name: Optional[str] = None,
|
||||
query_type: QueryType = "auto",
|
||||
@@ -6158,6 +6163,8 @@ class LanceTable(Table):
|
||||
|
||||
- *default None*.
|
||||
Acceptable types are: list, np.ndarray, PIL.Image.Image
|
||||
Use a path object with `query_type="vector"` when the embedding
|
||||
function supports image files.
|
||||
|
||||
- If None then the
|
||||
select/[where][lancedb.query.LanceQueryBuilder.where]/limit clauses
|
||||
@@ -8799,7 +8806,7 @@ class AsyncTable:
|
||||
@overload
|
||||
async def search(
|
||||
self,
|
||||
query: Union[VEC, str, "PIL.Image.Image", Tuple, FullTextQuery],
|
||||
query: Union[VEC, str, PathLike[str], "PIL.Image.Image", Tuple, FullTextQuery],
|
||||
vector_column_name: Optional[str] = None,
|
||||
query_type: Literal["vector"] = ...,
|
||||
ordering_field_name: Optional[str] = None,
|
||||
@@ -8811,7 +8818,7 @@ class AsyncTable:
|
||||
async def search(
|
||||
self,
|
||||
query: Optional[
|
||||
Union[VEC, str, "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
Union[VEC, str, PathLike[str], "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
] = None,
|
||||
vector_column_name: Optional[str] = None,
|
||||
query_type: QueryType = "auto",
|
||||
@@ -8833,6 +8840,8 @@ class AsyncTable:
|
||||
|
||||
- *default None*.
|
||||
Acceptable types are: list, np.ndarray, PIL.Image.Image
|
||||
Use a path object with `query_type="vector"` when the embedding
|
||||
function supports image files.
|
||||
|
||||
- If None then a plain [AsyncQuery][lancedb.query.AsyncQuery] is
|
||||
returned, equivalent to calling [query][lancedb.table.AsyncTable.query].
|
||||
@@ -8885,7 +8894,9 @@ class AsyncTable:
|
||||
async def get_embedding_func(
|
||||
vector_column_name: Optional[str],
|
||||
query_type: QueryType,
|
||||
query: Optional[Union[VEC, str, "PIL.Image.Image", Tuple, FullTextQuery]],
|
||||
query: Optional[
|
||||
Union[VEC, str, PathLike[str], "PIL.Image.Image", Tuple, FullTextQuery]
|
||||
],
|
||||
) -> Tuple[str, EmbeddingFunctionConfig]:
|
||||
if isinstance(query, FullTextQuery):
|
||||
query_type = "fts"
|
||||
|
||||
@@ -6,6 +6,7 @@ import json
|
||||
import os
|
||||
import pickle
|
||||
import threading
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
from typing import List, Optional, Union
|
||||
from unittest.mock import MagicMock, patch
|
||||
@@ -1303,6 +1304,121 @@ def test_open_clip_opens_percent_encoded_file_uri(tmp_path):
|
||||
assert image.size == (4, 4)
|
||||
|
||||
|
||||
def test_open_clip_preserves_image_inputs(tmp_path, monkeypatch):
|
||||
Image = pytest.importorskip("PIL.Image")
|
||||
from lancedb.embeddings import open_clip
|
||||
|
||||
image_path = tmp_path / "image #1%.png"
|
||||
Image.new("RGB", (4, 4)).save(image_path)
|
||||
encoded = image_path.read_bytes()
|
||||
url = "https://example.org/image.png"
|
||||
retrieve = MagicMock(return_value=encoded)
|
||||
monkeypatch.setattr(open_clip, "url_retrieve", retrieve)
|
||||
|
||||
for source in (str(image_path), image_path, encoded, url):
|
||||
with open_clip.OpenClipEmbeddings._to_pil(None, source) as image:
|
||||
assert image.size == (4, 4)
|
||||
retrieve.assert_called_once_with(url)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def open_clip_image_table(tmp_path, monkeypatch):
|
||||
Image = pytest.importorskip("PIL.Image")
|
||||
from lancedb.embeddings import open_clip
|
||||
|
||||
image_path = tmp_path / "frame #1%.png"
|
||||
Image.new("RGB", (4, 4), "red").save(image_path)
|
||||
|
||||
def preprocess(image):
|
||||
assert image.getpixel((0, 0)) == (255, 0, 0)
|
||||
return SimpleNamespace(unsqueeze=lambda _: np.array([1.0, 0.0]))
|
||||
|
||||
preprocess_image = MagicMock(side_effect=preprocess)
|
||||
backend = MagicMock()
|
||||
backend.create_model_and_transforms.return_value = (
|
||||
MagicMock(),
|
||||
None,
|
||||
preprocess_image,
|
||||
)
|
||||
modules = {
|
||||
"open_clip": backend,
|
||||
"torch": SimpleNamespace(no_grad=nullcontext),
|
||||
"PIL.Image": Image,
|
||||
}
|
||||
monkeypatch.setattr(
|
||||
open_clip, "attempt_import_or_raise", lambda name, *_: modules[name]
|
||||
)
|
||||
text_encoder = MagicMock(return_value=np.array([0.0, 1.0]))
|
||||
monkeypatch.setattr(
|
||||
open_clip.OpenClipEmbeddings, "generate_text_embeddings", text_encoder
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
open_clip.OpenClipEmbeddings,
|
||||
"_encode_and_normalize_image",
|
||||
lambda _, tensor: tensor,
|
||||
)
|
||||
embedder = get_registry().get("open-clip").create(max_retries=0)
|
||||
|
||||
class Frames(LanceModel):
|
||||
image_path: str = embedder.SourceField()
|
||||
vector: Vector(embedder.ndims()) = embedder.VectorField()
|
||||
|
||||
text_encoder.reset_mock()
|
||||
return Frames, image_path, text_encoder, preprocess_image
|
||||
|
||||
|
||||
def test_open_clip_image_path_search(tmp_path, open_clip_image_table):
|
||||
from PIL import Image
|
||||
|
||||
schema, image_path, text_encoder, preprocess_image = open_clip_image_table
|
||||
db = lancedb.connect(tmp_path / "db")
|
||||
table = db.create_table("frames", schema=schema)
|
||||
table.add([{"image_path": str(image_path)}])
|
||||
table = db.open_table("frames")
|
||||
assert table.to_arrow()["vector"].to_pylist() == [[1.0, 0.0]]
|
||||
|
||||
with Image.open(image_path) as image:
|
||||
for query in (str(image_path), image, image_path):
|
||||
result = table.search(query, query_type="vector").limit(1).to_list()
|
||||
assert result[0]["image_path"] == str(image_path)
|
||||
assert image.getpixel((0, 0)) == (255, 0, 0)
|
||||
|
||||
text_encoder.assert_called_once_with(str(image_path))
|
||||
assert preprocess_image.call_count == 3 # ingestion, PIL query, path query
|
||||
|
||||
corrupt_path = tmp_path / "corrupt.png"
|
||||
corrupt_path.write_bytes(b"invalid image")
|
||||
for path, error in (
|
||||
(tmp_path / "missing.png", FileNotFoundError),
|
||||
(corrupt_path, Image.UnidentifiedImageError),
|
||||
):
|
||||
with pytest.raises(Exception, match=r"Maximum number of retries") as exc:
|
||||
table.search(path, query_type="vector")
|
||||
assert isinstance(exc.value.__cause__, error)
|
||||
text_encoder.assert_called_once_with(str(image_path))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_open_clip_image_path_search(tmp_path, open_clip_image_table):
|
||||
from PIL import Image
|
||||
|
||||
schema, image_path, text_encoder, preprocess_image = open_clip_image_table
|
||||
db = await lancedb.connect_async(tmp_path / "db")
|
||||
table = await db.create_table("frames", schema=schema)
|
||||
await table.add([{"image_path": str(image_path)}])
|
||||
table = await db.open_table("frames")
|
||||
assert (await table.to_arrow())["vector"].to_pylist() == [[1.0, 0.0]]
|
||||
|
||||
with Image.open(image_path) as image:
|
||||
for query in (str(image_path), image, image_path):
|
||||
search = await table.search(query, query_type="vector")
|
||||
result = await search.limit(1).to_list()
|
||||
assert result[0]["image_path"] == str(image_path)
|
||||
|
||||
text_encoder.assert_called_once_with(str(image_path))
|
||||
assert preprocess_image.call_count == 3 # ingestion, PIL query, path query
|
||||
|
||||
|
||||
def test_open_clip_model_in_eval_mode():
|
||||
"""
|
||||
open_clip.create_model_and_transforms returns the model in training mode,
|
||||
|
||||
Reference in New Issue
Block a user