-
Notifications
You must be signed in to change notification settings - Fork 161
Support using ColPali library to compute embedding #796
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+430
−17
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
e499789
Copy image_search folder to image_search_colpali as diff base
badmonster0 00bebb2
Update ColPali image search example
badmonster0 8428018
Move functon to functions.py and use multi-vector search
badmonster0 b0459c5
Optimize ColPali with functools.cache and add colpali feature
badmonster0 19c64ea
Merge branch 'main' into colpali
badmonster0 a4122b9
clean up for examples
badmonster0 5f10f91
clean up for Colpali functions
badmonster0 67c68d8
add troubleshooting notice to `README.md`
badmonster0 45a7135
run the model on GPU
badmonster0 6798e23
use stronger type and cleanup
badmonster0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1 @@ | ||
COCOINDEX_DATABASE_URL="postgresql://cocoindex:cocoindex@127.0.0.1:5432/cocoindex" | ||
export COCOINDEX_DATABASE_URL="postgres://cocoindex:cocoindex@localhost/cocoindex" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
import datetime | ||
import os | ||
from contextlib import asynccontextmanager | ||
from typing import Any | ||
|
||
import cocoindex | ||
from dotenv import load_dotenv | ||
from fastapi import FastAPI, Query | ||
from fastapi.middleware.cors import CORSMiddleware | ||
from fastapi.staticfiles import StaticFiles | ||
from qdrant_client import QdrantClient | ||
|
||
|
||
# --- Config --- | ||
|
||
# Use GRPC | ||
QDRANT_URL = os.getenv("QDRANT_URL", "localhost:6334") | ||
PREFER_GRPC = os.getenv("QDRANT_PREFER_GRPC", "true").lower() == "true" | ||
|
||
# Use HTTP | ||
# QDRANT_URL = os.getenv("QDRANT_URL", "localhost:6333") | ||
# PREFER_GRPC = os.getenv("QDRANT_PREFER_GRPC", "false").lower() == "true" | ||
|
||
OLLAMA_URL = os.getenv("OLLAMA_URL", "http://localhost:11434/") | ||
QDRANT_COLLECTION = "ImageSearchColpali" | ||
COLPALI_MODEL_NAME = os.getenv("COLPALI_MODEL", "vidore/colpali-v1.2") | ||
print(f"📐 Using ColPali model {COLPALI_MODEL_NAME}") | ||
|
||
|
||
# Create ColPali embedding function using the class-based pattern | ||
colpali_embed = cocoindex.functions.ColPaliEmbedImage(model=COLPALI_MODEL_NAME) | ||
|
||
|
||
@cocoindex.transform_flow() | ||
def text_to_colpali_embedding( | ||
text: cocoindex.DataSlice[str], | ||
) -> cocoindex.DataSlice[list[list[float]]]: | ||
""" | ||
Embed text using a ColPali model, returning multi-vector format. | ||
This is shared logic between indexing and querying, ensuring consistent embeddings. | ||
""" | ||
return text.transform( | ||
cocoindex.functions.ColPaliEmbedQuery(model=COLPALI_MODEL_NAME) | ||
) | ||
|
||
|
||
@cocoindex.flow_def(name="ImageObjectEmbeddingColpali") | ||
def image_object_embedding_flow( | ||
flow_builder: cocoindex.FlowBuilder, data_scope: cocoindex.DataScope | ||
) -> None: | ||
data_scope["images"] = flow_builder.add_source( | ||
cocoindex.sources.LocalFile( | ||
path="img", included_patterns=["*.jpg", "*.jpeg", "*.png"], binary=True | ||
), | ||
refresh_interval=datetime.timedelta(minutes=1), | ||
) | ||
img_embeddings = data_scope.add_collector() | ||
with data_scope["images"].row() as img: | ||
ollama_model_name = os.getenv("OLLAMA_MODEL") | ||
if ollama_model_name is not None: | ||
# If an Ollama model is specified, generate an image caption | ||
img["caption"] = flow_builder.transform( | ||
cocoindex.functions.ExtractByLlm( | ||
llm_spec=cocoindex.llm.LlmSpec( | ||
api_type=cocoindex.LlmApiType.OLLAMA, model=ollama_model_name | ||
), | ||
instruction=( | ||
"Describe the image in one detailed sentence. " | ||
"Name all visible animal species, objects, and the main scene. " | ||
"Be specific about type, color, and notable features. " | ||
"Mention what each animal is doing." | ||
), | ||
output_type=str, | ||
), | ||
image=img["content"], | ||
) | ||
img["embedding"] = img["content"].transform(colpali_embed) | ||
|
||
collect_fields = { | ||
"id": cocoindex.GeneratedField.UUID, | ||
"filename": img["filename"], | ||
"embedding": img["embedding"], | ||
} | ||
|
||
if ollama_model_name is not None: | ||
print(f"Using Ollama model '{ollama_model_name}' for captioning.") | ||
collect_fields["caption"] = img["caption"] | ||
else: | ||
print(f"No Ollama model '{ollama_model_name}' found — skipping captioning.") | ||
|
||
img_embeddings.collect(**collect_fields) | ||
|
||
img_embeddings.export( | ||
"img_embeddings", | ||
cocoindex.targets.Qdrant(collection_name=QDRANT_COLLECTION), | ||
primary_key_fields=["id"], | ||
) | ||
|
||
|
||
@asynccontextmanager | ||
async def lifespan(app: FastAPI) -> None: | ||
load_dotenv() | ||
cocoindex.init() | ||
image_object_embedding_flow.setup(report_to_stdout=True) | ||
|
||
app.state.qdrant_client = QdrantClient(url=QDRANT_URL, prefer_grpc=PREFER_GRPC) | ||
|
||
# Start updater | ||
app.state.live_updater = cocoindex.FlowLiveUpdater(image_object_embedding_flow) | ||
app.state.live_updater.start() | ||
|
||
yield | ||
|
||
|
||
# --- FastAPI app for web API --- | ||
app = FastAPI(lifespan=lifespan) | ||
|
||
app.add_middleware( | ||
CORSMiddleware, | ||
allow_origins=["*"], | ||
allow_credentials=True, | ||
allow_methods=["*"], | ||
allow_headers=["*"], | ||
) | ||
# Serve images from the 'img' directory at /img | ||
app.mount("/img", StaticFiles(directory="img"), name="img") | ||
|
||
|
||
# --- Search API --- | ||
@app.get("/search") | ||
def search( | ||
q: str = Query(..., description="Search query"), | ||
limit: int = Query(5, description="Number of results"), | ||
) -> Any: | ||
# Get the multi-vector embedding for the query | ||
query_embedding = text_to_colpali_embedding.eval(q) | ||
print( | ||
f"🔍 Query multi-vector shape: {len(query_embedding)} tokens x {len(query_embedding[0]) if query_embedding else 0} dims" | ||
) | ||
|
||
# Search in Qdrant with multi-vector MaxSim scoring using query_points API | ||
search_results = app.state.qdrant_client.query_points( | ||
collection_name=QDRANT_COLLECTION, | ||
query=query_embedding, # Multi-vector format: list[list[float]] | ||
using="embedding", # Specify the vector field name | ||
limit=limit, | ||
with_payload=True, | ||
) | ||
|
||
print(f"📈 Found {len(search_results.points)} results with MaxSim scoring") | ||
|
||
return { | ||
"results": [ | ||
{ | ||
"filename": result.payload["filename"], | ||
"score": result.score, | ||
"caption": result.payload.get("caption"), | ||
} | ||
for result in search_results.points | ||
] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.