use adk_rag::EmbeddingProvider;
use async_trait::async_trait;
const STOP_WORDS: &[&str] = &[
"a", "about", "an", "and", "any", "are", "as", "at", "be", "been", "by", "can", "do", "does",
"did", "during", "for", "from", "has", "have", "here", "in", "into", "is", "it", "its", "of",
"on", "one", "or", "over", "part", "seen", "so", "some", "that", "the", "their", "them",
"then", "there", "these", "this", "those", "to", "up", "was", "were", "what", "when", "where",
"which", "while", "who", "with", "image", "images", "frame", "frames", "video", "scene",
"show", "shows", "shown", "visible",
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WordHashEmbedding {
dimensions: usize,
}
impl Default for WordHashEmbedding {
fn default() -> Self {
Self::new(1_024)
}
}
impl WordHashEmbedding {
pub fn new(dimensions: usize) -> Self {
Self { dimensions: dimensions.max(16) }
}
pub fn vector(&self, text: &str) -> Vec<f32> {
let mut vector = vec![0.0f32; self.dimensions];
for word in text
.split(|c: char| !c.is_alphanumeric())
.map(str::to_lowercase)
.filter(|w| !w.is_empty() && !STOP_WORDS.contains(&w.as_str()))
{
let hash = stem(&word).bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
});
vector[(hash % self.dimensions as u64) as usize] += 1.0;
}
let norm = vector.iter().map(|v| v * v).sum::<f32>().sqrt();
if norm == 0.0 {
vector[0] = 1.0;
} else {
vector.iter_mut().for_each(|v| *v /= norm);
}
vector
}
}
fn stem(word: &str) -> std::borrow::Cow<'_, str> {
let n = word.len();
if n > 4 && word.ends_with("ies") {
return format!("{}y", &word[..n - 3]).into();
}
let cut = |len: usize| std::borrow::Cow::Borrowed(&word[..len]);
if n > 5 && word.ends_with("ing") {
return cut(n - 3);
}
if n > 4 && word.ends_with("ied") {
return format!("{}y", &word[..n - 3]).into();
}
if n > 4 && word.ends_with("ed") {
return cut(n - 2);
}
if n > 4 && (word.ends_with("ches") || word.ends_with("shes") || word.ends_with("xes")) {
return cut(n - 2);
}
if n > 3 && word.ends_with('s') && !word.ends_with("ss") {
return cut(n - 1);
}
cut(n)
}
#[async_trait]
impl EmbeddingProvider for WordHashEmbedding {
async fn embed(&self, text: &str) -> adk_rag::Result<Vec<f32>> {
Ok(self.vector(text))
}
fn dimensions(&self) -> usize {
self.dimensions
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stems_join_forms_of_one_word() {
for (a, b) in [
("falls", "falling"),
("boxes", "box"),
("climbs", "climbed"),
("ladders", "ladder"),
("carries", "carry"),
("carried", "carry"),
] {
assert_eq!(stem(a), stem(b), "{a} / {b}");
}
assert_eq!(stem("glass"), "glass");
assert_eq!(stem("fell"), "fell");
}
#[test]
fn vectors_are_unit_length_and_stable() {
let words = WordHashEmbedding::new(64);
let v = words.vector("The truck backs into dock 1");
assert!((v.iter().map(|x| x * x).sum::<f32>() - 1.0).abs() < 1e-5);
assert_eq!(v, words.vector("the TRUCK backs into Dock 1."));
assert_eq!(words.vector("the of a")[0], 1.0);
}
}