Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

6.1 KB
Raw Blame
//! Image Search with CLIP + Qdrant β€” Rust port of the Python `image_search`
//! example.
//!
//! Pipeline: walk an image folder -> embed each image with the CLIP ViT-B/32
//! vision tower -> store in a Qdrant collection. Queries embed text with the
//! matching CLIP *text* tower (same 512-dim space) and run a vector search, so
//! you can search images by natural-language text.
//!
//!   cargo run -- index [IMAGE_DIR]     # incremental (unchanged images memo-skipped)
//!   cargo run -- query "a red bicycle" # CLIP text -> image vector search
//!
//! Both embedders run locally via `fastembed` (ONNX, no Python). The Python
//! example uses `transformers` CLIPModel; here `cocoindex::ops::image` (vision)
//! and `cocoindex::ops::sentence_transformers` (text) load the Qdrant-published
//! CLIP ONNX towers, which share an embedding space.
//!
//! Build note: `qdrant-client` compiles protobufs, so a `protoc` binary is
//! required to build (set `PROTOC` or put it on `PATH`). `fastembed` downloads
//! the CLIP ONNX models on first run.
//!
//! Parallels the Python example:
//!   - source            : `walk_dir(..).live()` + `ctx.mount_each_live` (cf. `localfs.walk_dir(live=True)` + `coco.mount_each`)
//!   - per-image compute : `#[cocoindex::function(memo)]` declaring its point (cf. `@coco.fn(memo=True)`)

use std::path::PathBuf;

use cocoindex::connectors::qdrant::{self, CollectionSchema, Distance, QdrantConnection};
use cocoindex::ops::image::ImageEmbedder;
use cocoindex::ops::sentence_transformers::SentenceTransformerEmbedder;
use cocoindex::prelude::*;
use serde_json::json;

/// CLIP ViT-B/32 vision tower (images) and text tower (queries). Both output
/// 512-dim vectors in a shared space.
const IMAGE_MODEL: &str = "Qdrant/clip-ViT-B-32-vision";
const TEXT_MODEL: &str = "Qdrant/clip-ViT-B-32-text";
const EMBED_DIM: u64 = 512;
const COLLECTION: &str = "ImageSearch";
const TOP_K: u64 = 5;

const IMAGE_GLOBS: &[&str] = &[
    "**/*.jpg",
    "**/*.jpeg",
    "**/*.png",
    "**/*.webp",
    "**/*.gif",
    "**/*.bmp",
];

cocoindex::context_key!(static DB: QdrantConnection);
cocoindex::context_key!(
    static EMBEDDER: ImageEmbedder,
    detect_change
);

/// Embed one image and declare its point (cf. Python `process_file`).
/// Memoized on the file: an unchanged image keeps its point without re-embedding.
/// The collection target is one per app, so it is not part of the memo key.
#[cocoindex::function(memo, memo_key(target = skip))]
async fn process_image(
    ctx: &Ctx,
    file: &FileEntry,
    target: &qdrant::CollectionTarget,
) -> Result<()> {
    let filename = file.key();
    let bytes = file.read().await?;
    let vector = ctx.get_key(&EMBEDDER)?.embed(ctx, bytes).await?;
    let id = IdGenerator::new().next_id(ctx, &filename).await?;
    let serde_json::Value::Object(payload) = json!({ "filename": filename }) else {
        return Err(Error::engine("point payload is not a JSON object"));
    };
    target.declare_point(ctx, id, vector, payload)
}

async fn app_main(ctx: Ctx, sourcedir: PathBuf) -> Result<()> {
    let target = qdrant::mount_collection_target(
        &ctx,
        &DB,
        COLLECTION,
        CollectionSchema::new(EMBED_DIM, Distance::Cosine),
    )
    .await?;

    // The source supports live watch (cf. Python `localfs.walk_dir(live=True)`).
    let files = walk_dir(sourcedir)
        .recursive(true)
        .path_matcher(PatternFilePathMatcher::include(IMAGE_GLOBS)?)
        .live();
    // One processing component per image: its point syncs and cleans up with
    // the image (cf. Python `coco.mount_each(process_file, files.items(), target)`).
    ctx.mount_each_live(&"process_image", files, move |ctx, file: FileEntry| {
        let target = target.clone();
        async move { process_image(&ctx, &file, &target).await }
    })
    .await
}

async fn query_once(
    conn: &QdrantConnection,
    text_embedder: &SentenceTransformerEmbedder,
    query: &str,
) -> Result<()> {
    let query_vec = text_embedder
        .embed_batch(vec![query.to_string()])
        .await?
        .remove(0);
    let hits = qdrant::vector_search(conn, COLLECTION, query_vec, TOP_K).await?;
    for hit in hits {
        let filename = hit
            .payload
            .get("filename")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        println!("[{:.3}] {filename}", hit.score);
    }
    Ok(())
}

fn qdrant_url() -> String {
    std::env::var("QDRANT_URL").unwrap_or_else(|_| "http://localhost:6334".to_string())
}

fn default_sourcedir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("img")
}

#[tokio::main]
async fn main() -> Result<()> {
    dotenvy::dotenv().ok();
    let args: Vec<String> = std::env::args().skip(1).collect();

    match args.first().map(String::as_str) {
        Some("query") => {
            let q = args[1..].join(" ");
            if q.trim().is_empty() {
                eprintln!("usage: cargo run -- query \"your search text\"");
                std::process::exit(2);
            }
            let conn = QdrantConnection::connect(&qdrant_url()).await?;
            // Text tower shares CLIP's image embedding space.
            let text_embedder = SentenceTransformerEmbedder::load(TEXT_MODEL).await?;
            query_once(&conn, &text_embedder, &q).await?;
        }
        sub => {
            let dir = match sub {
                Some("index") => args.get(1).map(PathBuf::from),
                Some(other) => Some(PathBuf::from(other)),
                None => None,
            }
            .unwrap_or_else(default_sourcedir);

            let conn = QdrantConnection::connect(&qdrant_url()).await?;
            let embedder = ImageEmbedder::load(IMAGE_MODEL).await?;
            let app = Environment::builder()
                .db_path(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(".cocoindex_db"))
                .provide_key(&DB, conn)
                .provide_key(&EMBEDDER, embedder)
                .build()
                .await?
                .app("ImageSearchRust")
                .await?;
            let stats = app.run(move |ctx| app_main(ctx, dir)).await?;
            println!("{stats}");
        }
    }
    Ok(())
}