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:
TRexy
2026-12-02 12:43:07 +00:00
committed by GitHub
parent c85647526c
commit eea95c8778
7 changed files with 235 additions and 34 deletions
+40
View File
@@ -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")
+22 -3
View File
@@ -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.
<Info>
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}
</CodeBlock>
</CodeGroup>
## 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.
<CodeGroup>
<CodeBlock filename="Python" language="Python" icon="python">
{PyEmbeddingOpenclipSiglip}
</CodeBlock>
</CodeGroup>
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.
+2
View File
@@ -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";