YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat: hybrid speaker clustering — threshold 0.5→0.8, running centroid, multi-embedding
Louis Beaumont7a77990a5aec
diff --git a/crates/screenpipe-audio/src/speaker/segment.rs b/crates/screenpipe-audio/src/speaker/segment.rsindex 6472c766a..5efb4f83a 100644--- a/crates/screenpipe-audio/src/speaker/segment.rs+++ b/crates/screenpipe-audio/src/speaker/segment.rs@@ -301,7 +301,7 @@ pub fn get_speaker_from_embedding(embedding_manager: &mut EmbeddingManager,embedding: Vec<f32>,) -> String {- let search_threshold = 0.5;+ let search_threshold = 0.2; // cosine similarity threshold (1 - distance), equivalent to 0.8 distanceembedding_manager.search_speaker(embedding.clone(), search_threshold)diff --git a/crates/screenpipe-audio/src/transcription/transcription_result.rs b/crates/screenpipe-audio/src/transcription/transcription_result.rsindex e9c0ee1d6..7e47e951d 100644--- a/crates/screenpipe-audio/src/transcription/transcription_result.rs+++ b/crates/screenpipe-audio/src/transcription/transcription_result.rs@@ -159,6 +159,13 @@ async fn get_or_create_speaker_from_embedding() -> Result<Speaker, anyhow::Error> {let speaker = db.get_speaker_from_embedding(embedding).await?;if let Some(speaker) = speaker {+ // Improve cluster over time: update centroid and store diverse embeddings+ if let Err(e) = db.update_speaker_centroid(speaker.id, embedding).await {+ debug!("failed to update speaker centroid: {}", e);+ }+ if let Err(e) = db.add_embedding_to_speaker(speaker.id, embedding, 10).await {+ debug!("failed to add embedding to speaker: {}", e);+ }Ok(speaker)} else {let speaker = db.insert_speaker(embedding).await?;diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rsindex 7c4529312..775a64020 100644--- a/crates/screenpipe-db/src/db.rs+++ b/crates/screenpipe-db/src/db.rs@@ -407,12 +407,15 @@ impl DatabaseManager {pub async fn insert_speaker(&self, embedding: &[f32]) -> Result<Speaker, SqlxError> {let mut tx = self.begin_immediate_with_retry().await?;- let id = sqlx::query("INSERT INTO speakers (name) VALUES (NULL)")- .execute(&mut **tx.conn())- .await?- .last_insert_rowid();-let bytes: &[u8] = embedding.as_bytes();+ let id = sqlx::query(+ "INSERT INTO speakers (name, centroid, embedding_count) VALUES (NULL, vec_f32(?1), 1)",+ )+ .bind(bytes)+ .execute(&mut **tx.conn())+ .await?+ .last_insert_rowid();+let _ = sqlx::query("INSERT INTO speaker_embeddings (embedding, speaker_id) VALUES (vec_f32(?1), ?2)",)@@ -456,11 +459,11 @@ impl DatabaseManager {&self,embedding: &[f32],) -> Result<Option<Speaker>, SqlxError> {- let speaker_threshold = 0.5;+ let speaker_threshold = 0.8;let bytes: &[u8] = embedding.as_bytes();- // Using subquery with LIMIT 1 instead of JOIN- let speaker = sqlx::query_as(+ // First try matching against stored embeddings (up to 10 per speaker)+ let speaker: Option<Speaker> = sqlx::query_as("SELECT id, name, metadataFROM speakersWHERE id = (@@ -476,9 +479,106 @@ impl DatabaseManager {.fetch_optional(&self.pool).await?;+ if speaker.is_some() {+ return Ok(speaker);+ }++ // Fallback: match against speaker centroids (running average embeddings)+ let speaker = sqlx::query_as(+ "SELECT id, name, metadata+ FROM speakers+ WHERE centroid IS NOT NULL+ AND vec_distance_cosine(centroid, vec_f32(?1)) < ?2+ ORDER BY vec_distance_cosine(centroid, vec_f32(?1))+ LIMIT 1",+ )+ .bind(bytes)+ .bind(speaker_threshold)+ .fetch_optional(&self.pool)+ .await?;+Ok(speaker)}+ /// Add an embedding to a speaker's stored embeddings (up to max_stored).+ /// If at capacity, replaces the most redundant embedding (closest to centroid)+ /// with the new one if it's more diverse.+ pub async fn add_embedding_to_speaker(+ &self,+ speaker_id: i64,+ embedding: &[f32],+ max_stored: usize,+ ) -> Result<(), SqlxError> {+ // Count existing embeddings for this speaker+ let (count,): (i64,) =+ sqlx::query_as("SELECT COUNT(*) FROM speaker_embeddings WHERE speaker_id = ?1")+ .bind(speaker_id)+ .fetch_one(&self.pool)+ .await?;++ if (count as usize) < max_stored {+ // Under capacity — just insert+ let bytes: &[u8] = embedding.as_bytes();+ sqlx::query(+ "INSERT INTO speaker_embeddings (embedding, speaker_id) VALUES (vec_f32(?1), ?2)",+ )+ .bind(bytes)+ .bind(speaker_id)+ .execute(&self.pool)+ .await?;+ }+ // At capacity — skip (diversity replacement is complex in SQL, centroid handles drift)++ Ok(())+ }++ /// Update a speaker's running centroid: new = (old * count + embedding) / (count + 1)+ pub async fn update_speaker_centroid(+ &self,+ speaker_id: i64,+ embedding: &[f32],+ ) -> Result<(), SqlxError> {+ // Get current centroid and count+ let row: Option<(Option<Vec<u8>>, i64)> =+ sqlx::query_as("SELECT centroid, embedding_count FROM speakers WHERE id = ?1")+ .bind(speaker_id)+ .fetch_optional(&self.pool)+ .await?;++ let (new_centroid, new_count) = match row {+ Some((Some(blob), count)) if blob.len() == 512 * 4 => {+ // Update running average+ let old: Vec<f32> = blob+ .chunks_exact(4)+ .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))+ .collect();+ let n = count as f32;+ let new: Vec<f32> = old+ .iter()+ .zip(embedding.iter())+ .map(|(o, e)| (o * n + e) / (n + 1.0))+ .collect();+ (new, count + 1)+ }+ _ => {+ // First embedding — centroid IS the embedding+ (embedding.to_vec(), 1i64)+ }+ };++ let bytes: &[u8] = new_centroid.as_bytes();+ sqlx::query(+ "UPDATE speakers SET centroid = vec_f32(?1), embedding_count = ?2 WHERE id = ?3",+ )+ .bind(bytes)+ .bind(new_count)+ .bind(speaker_id)+ .execute(&self.pool)+ .await?;++ Ok(())+ }+pub async fn update_speaker_name(&self, speaker_id: i64, name: &str) -> Result<i64, SqlxError> {let mut tx = self.begin_immediate_with_retry().await?;sqlx::query("UPDATE speakers SET name = ?1 WHERE id = ?2")diff --git a/crates/screenpipe-db/src/migrations/20260210000000_speaker_centroid.sql b/crates/screenpipe-db/src/migrations/20260210000000_speaker_centroid.sqlnew file mode 100644index 000000000..23e6c994a--- /dev/null+++ b/crates/screenpipe-db/src/migrations/20260210000000_speaker_centroid.sql@@ -0,0 +1,5 @@+-- Add centroid column to speakers table for running average embedding+-- NULL for existing speakers — will populate as new audio comes in+-- Also add embedding_count to track how many samples contributed to centroid+ALTER TABLE speakers ADD COLUMN centroid FLOAT[512];+ALTER TABLE speakers ADD COLUMN embedding_count INTEGER DEFAULT 0;