diff --git a/docs/web-tests/py/test_integrations.py b/docs/web-tests/py/test_integrations.py index d3f472ba0..2fe696080 100644 --- a/docs/web-tests/py/test_integrations.py +++ b/docs/web-tests/py/test_integrations.py @@ -623,6 +623,46 @@ def test_embedding_ollama_usage() -> None: # --8<-- [end:embedding_ollama_usage] +def test_embedding_openclip_siglip_example(tmp_path, monkeypatch) -> None: + require_flag("RUN_SIGLIP_SNIPPETS") + from PIL import Image as PILImage + + monkeypatch.chdir(tmp_path) + PILImage.new("RGB", (384, 384), "red").save("frame.jpg") + + # --8<-- [start:embedding_openclip_siglip] + from pathlib import Path + + import lancedb + from lancedb.embeddings import get_registry + from lancedb.pydantic import LanceModel, Vector + from PIL import Image + + embedder = get_registry().get("open-clip").create( + name="ViT-SO400M-14-SigLIP-384", + pretrained="webli", + ) + + class Frame(LanceModel): + image_path: str = embedder.SourceField() + vector: Vector(embedder.ndims()) = embedder.VectorField() + + db = lancedb.connect("./frame-search") + table = db.create_table("frames", schema=Frame) + frame = Path("frame.jpg") + table.add([{"image_path": str(frame)}]) + + text_matches = table.search("a dog running", query_type="vector").limit(5).to_list() + path_matches = table.search(frame, query_type="vector").limit(5).to_list() + with Image.open(frame) as image: + image_matches = table.search(image, query_type="vector").limit(5).to_list() + # --8<-- [end:embedding_openclip_siglip] + + for matches in (text_matches, path_matches, image_matches): + assert matches[0]["image_path"] == str(frame) + assert len(matches[0]["vector"]) == 1152 + + def test_embedding_openclip_examples() -> None: require_flag("RUN_OPENCLIP_SNIPPETS") diff --git a/docs/web/integrations/embedding/openclip.mdx b/docs/web/integrations/embedding/openclip.mdx index 118bb26c1..e9c3a2bc1 100644 --- a/docs/web/integrations/embedding/openclip.mdx +++ b/docs/web/integrations/embedding/openclip.mdx @@ -7,6 +7,7 @@ import { PyEmbeddingOpenclipSetup, PyEmbeddingOpenclipTextSearch, PyEmbeddingOpenclipImageSearch, + PyEmbeddingOpenclipSiglip, } from '/snippets/integrations.mdx'; We support CLIP model embeddings using the open source alternative, [open-clip](https://github.com/mlfoundations/open_clip) which supports various customizations. It is registered as `open-clip` and supports the following customizations: @@ -15,11 +16,11 @@ We support CLIP model embeddings using the open source alternative, [open-clip]( |---|---|---|---| | `name` | `str` | `"ViT-B-32"` | The name of the model. | | `pretrained` | `str` | `"laion2b_s34b_b79k"` | The name of the pretrained model to load. | -| `device` | `str` | `"cpu"` | The device to run the model on. Can be `"cpu"` or `"gpu"`. | +| `device` | `str` | `"cpu"` | The PyTorch device to run the model on, such as `"cpu"` or `"cuda"`. | | `batch_size` | `int` | `64` | The number of images to process in a batch. | -| `normalize` | `bool` | `True` | Whether to normalize the input images before feeding them to the model. | +| `normalize` | `bool` | `True` | Whether to normalize the output embeddings to unit length. | -This embedding function supports ingesting images as both bytes and urls. You can query them using both text and other images. +This embedding function accepts image files, encoded image bytes, and URLs at ingestion. For vector search, pass text, a PIL image, or a path object such as `Path("frame.jpg")`. A string query is always treated as text. LanceDB supports ingesting images directly from accessible links. @@ -44,3 +45,21 @@ Because we're using a multimodal embedding function, we can also search using im {PyEmbeddingOpenclipImageSearch} + +## Search video frames with SigLIP {#search-video-frames-with-siglip} + +Use the [SigLIP SO400M checkpoint](https://huggingface.co/timm/ViT-SO400M-14-SigLIP-384) to generate 1,152-dimensional vectors for images and text. Install OpenCLIP and the tokenizer dependencies. + +```bash +pip install "lancedb[clip]" "transformers[sentencepiece]" +``` + +The Python example starts with an extracted frame named `frame.jpg`. LanceDB Embedded fills the vector column when you add the frame. + + + + {PyEmbeddingOpenclipSiglip} + + + +With `AsyncTable`, use `await table.search(frame, query_type="vector")` to build the image query. Use the same model and preprocessing for ingestion and search. If you switch from another embedding pipeline, regenerate the stored vectors unless you have verified compatibility. diff --git a/docs/web/snippets/integrations.mdx b/docs/web/snippets/integrations.mdx index cc3cf9add..cf9947c1b 100644 --- a/docs/web/snippets/integrations.mdx +++ b/docs/web/snippets/integrations.mdx @@ -40,6 +40,8 @@ export const PyEmbeddingOpenclipImageSearch = "import io\n\nfrom PIL import Imag export const PyEmbeddingOpenclipSetup = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nimport pandas as pd\nimport requests\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"openclip-demo\"))\nfunc = get_registry().get(\"open-clip\").create()\n\nclass Images(LanceModel):\n label: str\n image_uri: str = func.SourceField()\n image_bytes: bytes = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n vec_from_bytes: Vector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"images\", schema=Images)\nlabels = [\"cat\", \"cat\", \"dog\", \"dog\", \"horse\", \"horse\"]\nuris = [\n \"http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg\",\n \"http://farm1.staticflickr.com/134/332220238_da527d8140_z.jpg\",\n \"http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg\",\n \"http://farm5.staticflickr.com/4092/5017326486_1f46057f5f_z.jpg\",\n \"http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg\",\n \"http://farm6.staticflickr.com/5142/5835678453_4f3a4edb45_z.jpg\",\n]\nimage_bytes = [requests.get(uri).content for uri in uris]\ntable.add(\n pd.DataFrame({\"label\": labels, \"image_uri\": uris, \"image_bytes\": image_bytes})\n)\n"; +export const PyEmbeddingOpenclipSiglip = "from pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\nfrom PIL import Image\n\nembedder = get_registry().get(\"open-clip\").create(\n name=\"ViT-SO400M-14-SigLIP-384\",\n pretrained=\"webli\",\n)\n\nclass Frame(LanceModel):\n image_path: str = embedder.SourceField()\n vector: Vector(embedder.ndims()) = embedder.VectorField()\n\ndb = lancedb.connect(\"./frame-search\")\ntable = db.create_table(\"frames\", schema=Frame)\nframe = Path(\"frame.jpg\")\ntable.add([{\"image_path\": str(frame)}])\n\ntext_matches = table.search(\"a dog running\", query_type=\"vector\").limit(5).to_list()\npath_matches = table.search(frame, query_type=\"vector\").limit(5).to_list()\nwith Image.open(frame) as image:\n image_matches = table.search(image, query_type=\"vector\").limit(5).to_list()\n"; + export const PyEmbeddingOpenclipTextSearch = "actual = table.search(\"man's best friend\").limit(1).to_pydantic(Images)[0]\nprint(actual.label)\n\nfrombytes = (\n table.search(\"man's best friend\", vector_column_name=\"vec_from_bytes\")\n .limit(1)\n .to_pydantic(Images)[0]\n)\nprint(frombytes.label)\n"; export const PyEmbeddingSentenceTransformersBaai = "import tempfile\nfrom pathlib import Path\n\nimport lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel, Vector\n\ndb = lancedb.connect(str(Path(tempfile.mkdtemp()) / \"sentence-transformers\"))\nmodel = (\n get_registry()\n .get(\"sentence-transformers\")\n .create(name=\"BAAI/bge-small-en-v1.5\", device=\"cpu\")\n)\n\nclass Words(LanceModel):\n text: str = model.SourceField()\n vector: Vector(model.ndims()) = model.VectorField()\n\ntable = db.create_table(\"words\", schema=Words)\ntable.add(\n [\n {\"text\": \"hello world\"},\n {\"text\": \"goodbye world\"},\n ]\n)\n\nquery = \"greetings\"\nactual = table.search(query).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n"; diff --git a/python/python/lancedb/embeddings/open_clip.py b/python/python/lancedb/embeddings/open_clip.py index 6199ef271..62bb4950e 100644 --- a/python/python/lancedb/embeddings/open_clip.py +++ b/python/python/lancedb/embeddings/open_clip.py @@ -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"): """ diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index e46795adf..ef4582f5e 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -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. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index e2d815115..cd6928857 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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" diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 8d629aff5..373ff09f9 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -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,