pub mod hash;
#[cfg(feature = "onnx")]
pub mod onnx;
pub use hash::HashEmbedder;
#[cfg(feature = "onnx")]
pub use onnx::OnnxEmbedder;
use crate::error::Result;
use crate::metric::Metric;
use std::future::Future;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct EmbedderId(pub u64);
impl EmbedderId {
#[must_use]
pub fn derive(name: &str, dim: usize, params: u64) -> Self {
use graph_r::hash::xxh3_64;
let mut seed = xxh3_64(name.as_bytes());
seed ^= (dim as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
seed ^= params.wrapping_mul(0xC2B2_AE3D_27D4_EB4F);
Self(seed)
}
#[must_use]
pub fn raw(self) -> u64 {
self.0
}
}
pub trait Embedder: Send + Sync {
type EmbedFuture<'a>: Future<Output = Result<()>> + Send + 'a
where
Self: 'a;
fn dim(&self) -> usize;
fn metric(&self) -> Metric;
fn identity(&self) -> EmbedderId;
fn embed_batch<'a>(&'a self, texts: &'a [&'a str], out: &'a mut [f32])
-> Self::EmbedFuture<'a>;
}
pub async fn embed_one<E: Embedder>(embedder: &E, text: &str) -> Result<Vec<f32>> {
let mut out = vec![0.0f32; embedder.dim()];
let texts = [text];
embedder.embed_batch(&texts, &mut out).await?;
Ok(out)
}