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(timeline): add speaker assignment UI for audio transcriptions
Louis Beaumonta9f5523c61dd
diff --git a/screenpipe-app-tauri/components/rewind/timeline.tsx b/screenpipe-app-tauri/components/rewind/timeline.tsxindex 7a1784c70..8eda2a2f9 100644--- a/screenpipe-app-tauri/components/rewind/timeline.tsx+++ b/screenpipe-app-tauri/components/rewind/timeline.tsx@@ -47,6 +47,9 @@ export interface AudioData {audio_file_path: string;duration_secs: number;start_offset: number;+ audio_chunk_id: number;+ speaker_id?: number;+ speaker_name?: string;}export interface TimeRange {diff --git a/screenpipe-app-tauri/components/rewind/timeline/audio-transcript.tsx b/screenpipe-app-tauri/components/rewind/timeline/audio-transcript.tsxindex b74f0352d..1222db8c5 100644--- a/screenpipe-app-tauri/components/rewind/timeline/audio-transcript.tsx+++ b/screenpipe-app-tauri/components/rewind/timeline/audio-transcript.tsx@@ -4,6 +4,7 @@ import { Button } from "@/components/ui/button";import { Card } from "@/components/ui/card";import { Play, Pause, Volume2, GripHorizontal, X } from "lucide-react";import { VideoComponent } from "@/components/rewind/video";+import { SpeakerAssignPopover } from "@/components/speaker-assign-popover";interface AudioGroup {deviceName: string;@@ -73,6 +74,22 @@ export function AudioTranscript({const resizerRef = useRef<HTMLDivElement | null>(null);const panelRef = useRef<HTMLDivElement | null>(null);+ // Track speaker assignments (audio_chunk_id -> {speaker_id, speaker_name})+ const [speakerOverrides, setSpeakerOverrides] = useState<+ Map<number, { speakerId: number; speakerName: string }>+ >(new Map());++ const handleSpeakerAssigned = useCallback(+ (audioChunkId: number, newSpeakerId: number, newSpeakerName: string) => {+ setSpeakerOverrides((prev) => {+ const next = new Map(prev);+ next.set(audioChunkId, { speakerId: newSpeakerId, speakerName: newSpeakerName });+ return next;+ });+ },+ []+ );+// 2. Memoize the audio grouping logicconst audioGroups = useMemo(() => {if (!frames.length) return [];@@ -250,42 +267,61 @@ export function AudioTranscript({</div></div>- {group.audioItems.map((audio, index) => (- <div key={index} className="space-y-2 mb-2 last:mb-0">- <div className="flex items-center gap-2">- <Button- variant="ghost"- size="sm"- className="h-6 w-6 p-0 text-foreground hover:text-accent-foreground hover:bg-accent"- onClick={() => handlePlay(audio.audio_file_path)}- >- {playing === audio.audio_file_path ? (- <Pause className="h-3 w-3" />- ) : (- <Play className="h-3 w-3" />- )}- </Button>- <div className="flex items-center gap-1 text-xs text-muted-foreground">- <Volume2 className="h-3 w-3" />- <span>- {formatDurationHuman(Math.round(audio.duration_secs))}- </span>- </div>- </div>-- {audio.transcription && (- <div className="text-xs pl-8 text-muted-foreground">- {audio.transcription}+ {group.audioItems.map((audio, index) => {+ // Get speaker info (use override if available, otherwise from audio data)+ const override = speakerOverrides.get(audio.audio_chunk_id);+ const speakerId = override?.speakerId ?? audio.speaker_id;+ const speakerName = override?.speakerName ?? audio.speaker_name;++ return (+ <div key={index} className="space-y-2 mb-3 last:mb-0 pb-3 last:pb-0 border-b last:border-b-0 border-border/50">+ <div className="flex items-center gap-2 flex-wrap">+ <Button+ variant="ghost"+ size="sm"+ className="h-6 w-6 p-0 text-foreground hover:text-accent-foreground hover:bg-accent"+ onClick={() => handlePlay(audio.audio_file_path)}+ >+ {playing === audio.audio_file_path ? (+ <Pause className="h-3 w-3" />+ ) : (+ <Play className="h-3 w-3" />+ )}+ </Button>++ {/* Speaker badge with assignment popover */}+ <SpeakerAssignPopover+ audioChunkId={audio.audio_chunk_id}+ speakerId={speakerId}+ speakerName={speakerName}+ audioFilePath={audio.audio_file_path}+ onAssigned={(newId, newName) =>+ handleSpeakerAssigned(audio.audio_chunk_id, newId, newName)+ }+ />++ <div className="flex items-center gap-1 text-xs text-muted-foreground">+ <Volume2 className="h-3 w-3" />+ <span>+ {formatDurationHuman(Math.round(audio.duration_secs))}+ </span>+ </div></div>- )}- {playing === audio.audio_file_path && (- <div className="pl-8">- <VideoComponent filePath={audio.audio_file_path} />- </div>- )}- </div>- ))}+ {audio.transcription && (+ <div className="text-xs pl-8 text-muted-foreground">+ {audio.transcription}+ </div>+ )}++ {playing === audio.audio_file_path && (+ <div className="pl-8">+ <VideoComponent filePath={audio.audio_file_path} />+ </div>+ )}+ </div>+ );+ })}</Card>))}</div>diff --git a/screenpipe-app-tauri/components/speaker-assign-popover.tsx b/screenpipe-app-tauri/components/speaker-assign-popover.tsxnew file mode 100644index 000000000..e7fb70392--- /dev/null+++ b/screenpipe-app-tauri/components/speaker-assign-popover.tsx@@ -0,0 +1,281 @@+"use client";++import { useState, useEffect, useCallback } from "react";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Input } from "@/components/ui/input";+import { Button } from "@/components/ui/button";+import { SpeakerBadge } from "@/components/speaker-badge";+import { useToast } from "@/components/ui/use-toast";+import { Check, Ghost, Loader2, Plus, Volume2 } from "lucide-react";+import { VideoComponent } from "@/components/rewind/video";+import { cn } from "@/lib/utils";++interface Speaker {+ id: number;+ name: string;+ metadata?: string;+}++interface SpeakerAssignPopoverProps {+ audioChunkId: number;+ speakerId?: number;+ speakerName?: string;+ audioFilePath: string;+ onAssigned?: (newSpeakerId: number, newSpeakerName: string) => void;+}++export function SpeakerAssignPopover({+ audioChunkId,+ speakerId,+ speakerName,+ audioFilePath,+ onAssigned,+}: SpeakerAssignPopoverProps) {+ const [open, setOpen] = useState(false);+ const [searchTerm, setSearchTerm] = useState("");+ const [speakers, setSpeakers] = useState<Speaker[]>([]);+ const [isSearching, setIsSearching] = useState(false);+ const [isAssigning, setIsAssigning] = useState(false);+ const [showAudioPreview, setShowAudioPreview] = useState(false);+ const { toast } = useToast();++ // Search for speakers when search term changes+ useEffect(() => {+ if (!searchTerm || searchTerm.length < 1) {+ setSpeakers([]);+ return;+ }++ const searchSpeakers = async () => {+ setIsSearching(true);+ try {+ const response = await fetch(+ `http://localhost:3030/speakers/search?name=${encodeURIComponent(searchTerm)}`+ );+ if (response.ok) {+ const results = await response.json();+ setSpeakers(results);+ }+ } catch (error) {+ console.error("Error searching speakers:", error);+ } finally {+ setIsSearching(false);+ }+ };++ const debounceTimeout = setTimeout(searchSpeakers, 300);+ return () => clearTimeout(debounceTimeout);+ }, [searchTerm]);++ const handleAssign = useCallback(+ async (name: string) => {+ if (!name.trim()) return;++ setIsAssigning(true);+ try {+ const response = await fetch("http://localhost:3030/speakers/reassign", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ audio_chunk_id: audioChunkId,+ new_speaker_name: name.trim(),+ propagate_similar: true,+ }),+ });++ if (!response.ok) {+ throw new Error("Failed to assign speaker");+ }++ const result = await response.json();+ toast({+ title: "Speaker assigned",+ description: `Assigned to "${name}". ${result.embeddings_moved} similar voices updated.`,+ });++ onAssigned?.(result.new_speaker_id, result.new_speaker_name);+ setOpen(false);+ setSearchTerm("");+ } catch (error) {+ console.error("Error assigning speaker:", error);+ toast({+ title: "Error",+ description: "Failed to assign speaker. Please try again.",+ variant: "destructive",+ });+ } finally {+ setIsAssigning(false);+ }+ },+ [audioChunkId, onAssigned, toast]+ );++ const handleMarkAsHallucination = useCallback(async () => {+ if (!speakerId) return;++ setIsAssigning(true);+ try {+ const response = await fetch("http://localhost:3030/speakers/hallucination", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ speaker_id: speakerId }),+ });++ if (!response.ok) {+ throw new Error("Failed to mark as hallucination");+ }++ toast({+ title: "Marked as noise",+ description: "This audio will be ignored in future processing.",+ });++ setOpen(false);+ } catch (error) {+ console.error("Error marking hallucination:", error);+ toast({+ title: "Error",+ description: "Failed to mark as noise. Please try again.",+ variant: "destructive",+ });+ } finally {+ setIsAssigning(false);+ }+ }, [speakerId, toast]);++ const handleSelectSpeaker = (speaker: Speaker) => {+ handleAssign(speaker.name);+ };++ const handleCreateNew = () => {+ if (searchTerm.trim()) {+ handleAssign(searchTerm.trim());+ }+ };++ const showCreateOption =+ searchTerm.trim() &&+ !speakers.some((s) => s.name.toLowerCase() === searchTerm.toLowerCase());++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild>+ <span>+ <SpeakerBadge+ speakerId={speakerId}+ speakerName={speakerName}+ onClick={() => setOpen(true)}+ />+ </span>+ </PopoverTrigger>+ <PopoverContent className="w-80 p-3" align="start">+ <div className="space-y-3">+ <div className="text-sm font-medium">Assign speaker</div>++ {/* Search input */}+ <div className="relative">+ <Input+ placeholder="Type speaker name..."+ value={searchTerm}+ onChange={(e) => setSearchTerm(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && searchTerm.trim()) {+ e.preventDefault();+ handleCreateNew();+ }+ }}+ disabled={isAssigning}+ autoFocus+ />+ {isSearching && (+ <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />+ )}+ </div>++ {/* Suggestions list */}+ {(speakers.length > 0 || showCreateOption) && (+ <div className="max-h-[150px] overflow-y-auto border rounded-md">+ {/* Existing speakers */}+ {speakers.map((speaker) => (+ <button+ key={speaker.id}+ type="button"+ className={cn(+ "w-full px-3 py-2 text-left text-sm hover:bg-accent flex items-center gap-2",+ isAssigning && "opacity-50 pointer-events-none"+ )}+ onClick={() => handleSelectSpeaker(speaker)}+ disabled={isAssigning}+ >+ <Check className="h-3 w-3 text-muted-foreground" />+ <span className="truncate">{speaker.name}</span>+ </button>+ ))}++ {/* Create new option */}+ {showCreateOption && (+ <button+ type="button"+ className={cn(+ "w-full px-3 py-2 text-left text-sm hover:bg-accent flex items-center gap-2 border-t",+ isAssigning && "opacity-50 pointer-events-none"+ )}+ onClick={handleCreateNew}+ disabled={isAssigning}+ >+ <Plus className="h-3 w-3 text-muted-foreground" />+ <span>+ Create "<span className="font-medium">{searchTerm}</span>"+ </span>+ </button>+ )}+ </div>+ )}++ {/* Audio preview toggle */}+ <div className="pt-2 border-t">+ <Button+ variant="ghost"+ size="sm"+ className="w-full justify-start text-xs"+ onClick={() => setShowAudioPreview(!showAudioPreview)}+ >+ <Volume2 className="h-3 w-3 mr-2" />+ {showAudioPreview ? "Hide audio preview" : "Play audio to confirm"}+ </Button>++ {showAudioPreview && (+ <div className="mt-2">+ <VideoComponent filePath={audioFilePath} />+ </div>+ )}+ </div>++ {/* Mark as noise button */}+ {speakerId && (+ <div className="pt-2 border-t">+ <Button+ variant="ghost"+ size="sm"+ className="w-full justify-start text-xs text-muted-foreground hover:text-foreground"+ onClick={handleMarkAsHallucination}+ disabled={isAssigning}+ >+ <Ghost className="h-3 w-3 mr-2" />+ This is just noise (nobody speaking)+ </Button>+ </div>+ )}++ {/* Loading indicator */}+ {isAssigning && (+ <div className="flex items-center justify-center py-2">+ <Loader2 className="h-4 w-4 animate-spin mr-2" />+ <span className="text-sm text-muted-foreground">Assigning...</span>+ </div>+ )}+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/screenpipe-app-tauri/components/speaker-badge.tsx b/screenpipe-app-tauri/components/speaker-badge.tsxnew file mode 100644index 000000000..fb441e13e--- /dev/null+++ b/screenpipe-app-tauri/components/speaker-badge.tsx@@ -0,0 +1,58 @@+"use client";++import { cn } from "@/lib/utils";+import { User } from "lucide-react";++// Color palette for speakers (works in light/dark mode)+const SPEAKER_COLORS = [+ "bg-blue-500/20 text-blue-700 dark:text-blue-300 border-blue-500/30",+ "bg-green-500/20 text-green-700 dark:text-green-300 border-green-500/30",+ "bg-purple-500/20 text-purple-700 dark:text-purple-300 border-purple-500/30",+ "bg-orange-500/20 text-orange-700 dark:text-orange-300 border-orange-500/30",+ "bg-pink-500/20 text-pink-700 dark:text-pink-300 border-pink-500/30",+ "bg-cyan-500/20 text-cyan-700 dark:text-cyan-300 border-cyan-500/30",+ "bg-yellow-500/20 text-yellow-700 dark:text-yellow-300 border-yellow-500/30",+ "bg-red-500/20 text-red-700 dark:text-red-300 border-red-500/30",+];++function getSpeakerColor(speakerId: number): string {+ return SPEAKER_COLORS[speakerId % SPEAKER_COLORS.length];+}++export interface SpeakerBadgeProps {+ speakerId?: number;+ speakerName?: string;+ onClick?: () => void;+ className?: string;+}++export function SpeakerBadge({+ speakerId,+ speakerName,+ onClick,+ className,+}: SpeakerBadgeProps) {+ const isUnknown = !speakerName;+ const displayName = speakerName || `Unknown #${speakerId || "?"}`;++ const colorClass = speakerId ? getSpeakerColor(speakerId) : "";++ return (+ <button+ type="button"+ onClick={onClick}+ className={cn(+ "inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium transition-all",+ "hover:ring-2 hover:ring-offset-1 hover:ring-offset-background",+ isUnknown+ ? "border border-dashed border-muted-foreground/50 text-muted-foreground hover:ring-muted-foreground/50"+ : cn("border", colorClass, "hover:ring-current"),+ onClick && "cursor-pointer",+ className+ )}+ >+ <User className="h-3 w-3" />+ <span className="max-w-[100px] truncate">{displayName}</span>+ </button>+ );+}diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rsindex 3cc88db56..1171f9e64 100644--- a/screenpipe-db/src/db.rs+++ b/screenpipe-db/src/db.rs@@ -1576,13 +1576,17 @@ impl DatabaseManager {at.device as audio_device,at.is_input_device,ac.file_path as audio_path,+ ac.id as audio_chunk_id,at.start_time,at.end_time,+ at.speaker_id,+ s.name as speaker_name,CAST((julianday(datetime(at.timestamp, '+' || at.end_time || ' seconds')) -julianday(datetime(at.timestamp, '+' || at.start_time || ' seconds'))) * 86400as REAL) as duration_secsFROM audio_transcriptions atJOIN audio_chunks ac ON at.audio_chunk_id = ac.id+ LEFT JOIN speakers s ON at.speaker_id = s.idWHERE at.timestamp >= ?1 AND at.timestamp <= ?2ORDER BY at.timestamp DESC"#;@@ -1645,6 +1649,9 @@ impl DatabaseManager {is_input: row.get("is_input_device"),audio_file_path: row.get("audio_path"),duration_secs: row.get("duration_secs"),+ audio_chunk_id: row.get("audio_chunk_id"),+ speaker_id: row.try_get("speaker_id").ok(),+ speaker_name: row.try_get("speaker_name").ok(),});}}@@ -2430,6 +2437,288 @@ LIMIT ? OFFSET ?}).collect())}++ // ===== Speaker Reassignment Functions =====++ /// Find a speaker by exact name match+ pub async fn find_speaker_by_name(&self, name: &str) -> Result<Option<Speaker>, sqlx::Error> {+ sqlx::query_as::<_, Speaker>(+ "SELECT id, name, metadata FROM speakers WHERE name = ? AND hallucination = 0",+ )+ .bind(name)+ .fetch_optional(&self.pool)+ .await+ }++ /// Count the number of embeddings for a speaker+ pub async fn count_embeddings_for_speaker(&self, speaker_id: i64) -> Result<i64, sqlx::Error> {+ let count = sqlx::query_scalar::<_, i64>(+ "SELECT COUNT(*) FROM speaker_embeddings WHERE speaker_id = ?",+ )+ .bind(speaker_id)+ .fetch_one(&self.pool)+ .await?;+ Ok(count)+ }++ /// Get the embedding ID associated with an audio chunk (transcription)+ pub async fn get_embedding_id_for_audio_chunk(+ &self,+ audio_chunk_id: i64,+ ) -> Result<Option<i64>, sqlx::Error> {+ // Audio transcriptions are linked to speakers, and speakers have embeddings+ // We need to find the embedding that was used to identify this transcription+ // The relationship is: audio_transcription -> speaker_id -> speaker_embeddings+ // But we need to find which specific embedding matched this transcription+ // For now, we get the speaker_id and find any embedding for that speaker+ let result = sqlx::query_scalar::<_, i64>(+ r#"+ SELECT se.id+ FROM audio_transcriptions at+ JOIN speaker_embeddings se ON at.speaker_id = se.speaker_id+ WHERE at.audio_chunk_id = ?+ LIMIT 1+ "#,+ )+ .bind(audio_chunk_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(result)+ }++ /// Move an embedding from one speaker to another+ pub async fn move_embedding(+ &self,+ embedding_id: i64,+ to_speaker_id: i64,+ ) -> Result<(), sqlx::Error> {+ sqlx::query("UPDATE speaker_embeddings SET speaker_id = ? WHERE id = ?")+ .bind(to_speaker_id)+ .bind(embedding_id)+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// Update the speaker_id for all transcriptions in an audio chunk+ pub async fn update_transcriptions_speaker(+ &self,+ audio_chunk_id: i64,+ new_speaker_id: i64,+ ) -> Result<u64, sqlx::Error> {+ let result =+ sqlx::query("UPDATE audio_transcriptions SET speaker_id = ? WHERE audio_chunk_id = ?")+ .bind(new_speaker_id)+ .bind(audio_chunk_id)+ .execute(&self.pool)+ .await?;+ Ok(result.rows_affected())+ }++ /// Create a new speaker with a name (no embedding)+ pub async fn create_speaker_with_name(&self, name: &str) -> Result<Speaker, sqlx::Error> {+ let id = sqlx::query("INSERT INTO speakers (name) VALUES (?)")+ .bind(name)+ .execute(&self.pool)+ .await?+ .last_insert_rowid();++ Ok(Speaker {+ id,+ name: name.to_string(),+ metadata: String::new(),+ })+ }++ /// Find embeddings similar to the embeddings of a given speaker+ /// Returns a list of (embedding_id, speaker_id) pairs+ pub async fn find_similar_embedding_ids(+ &self,+ source_speaker_id: i64,+ threshold: f64,+ ) -> Result<Vec<(i64, i64)>, sqlx::Error> {+ // Get embeddings that are similar to any embedding of the source speaker+ // but belong to different speakers+ let rows = sqlx::query(+ r#"+ SELECT DISTINCT se2.id as embedding_id, se2.speaker_id+ FROM speaker_embeddings se1+ JOIN speaker_embeddings se2 ON se1.speaker_id != se2.speaker_id+ WHERE se1.speaker_id = ?+ AND vec_distance_cosine(se1.embedding, se2.embedding) < ?+ "#,+ )+ .bind(source_speaker_id)+ .bind(threshold)+ .fetch_all(&self.pool)+ .await?;++ let results: Vec<(i64, i64)> = rows+ .iter()+ .map(|row| {+ let embedding_id: i64 = row.get("embedding_id");+ let speaker_id: i64 = row.get("speaker_id");+ (embedding_id, speaker_id)+ })+ .collect();++ Ok(results)+ }++ /// Reassign a speaker: move transcriptions and embeddings to a new or existing speaker+ /// This is the main function for the correction flow+ /// Returns (new_speaker_id, transcriptions_updated, embeddings_moved)+ pub async fn reassign_speaker(+ &self,+ audio_chunk_id: i64,+ new_speaker_name: &str,+ propagate_similar: bool,+ ) -> Result<(i64, u64, u64), sqlx::Error> {+ let mut tx = self.pool.begin().await?;++ // 1. Get the current speaker_id for this audio chunk+ let current_speaker_id: Option<i64> = sqlx::query_scalar(+ "SELECT speaker_id FROM audio_transcriptions WHERE audio_chunk_id = ? LIMIT 1",+ )+ .bind(audio_chunk_id)+ .fetch_optional(&mut *tx)+ .await?;++ let current_speaker_id = match current_speaker_id {+ Some(id) => id,+ None => {+ tx.rollback().await?;+ return Err(sqlx::Error::RowNotFound);+ }+ };++ // 2. Find or create the target speaker+ let target_speaker: Speaker = match sqlx::query_as::<_, Speaker>(+ "SELECT id, name, metadata FROM speakers WHERE name = ? AND hallucination = 0",+ )+ .bind(new_speaker_name)+ .fetch_optional(&mut *tx)+ .await?+ {+ Some(speaker) => speaker,+ None => {+ // Create new speaker+ let id = sqlx::query("INSERT INTO speakers (name) VALUES (?)")+ .bind(new_speaker_name)+ .execute(&mut *tx)+ .await?+ .last_insert_rowid();++ Speaker {+ id,+ name: new_speaker_name.to_string(),+ metadata: String::new(),+ }+ }+ };++ // 3. Update the transcription's speaker_id+ let transcriptions_updated =+ sqlx::query("UPDATE audio_transcriptions SET speaker_id = ? WHERE audio_chunk_id = ?")+ .bind(target_speaker.id)+ .bind(audio_chunk_id)+ .execute(&mut *tx)+ .await?+ .rows_affected();++ // 4. Move the embedding from old speaker to new speaker+ let embedding_id: Option<i64> = sqlx::query_scalar(+ "SELECT id FROM speaker_embeddings WHERE speaker_id = ? LIMIT 1",+ )+ .bind(current_speaker_id)+ .fetch_optional(&mut *tx)+ .await?;++ let mut embeddings_moved = 0u64;+ if let Some(emb_id) = embedding_id {+ sqlx::query("UPDATE speaker_embeddings SET speaker_id = ? WHERE id = ?")+ .bind(target_speaker.id)+ .bind(emb_id)+ .execute(&mut *tx)+ .await?;+ embeddings_moved = 1;+ }++ // 5. If propagate_similar, find and reassign similar embeddings+ if propagate_similar {+ let threshold = 0.5; // Same as speaker matching threshold++ // Find similar embeddings from other speakers+ let similar_rows = sqlx::query(+ r#"+ SELECT se2.id as embedding_id, se2.speaker_id+ FROM speaker_embeddings se1+ JOIN speaker_embeddings se2 ON se1.speaker_id != se2.speaker_id+ WHERE se1.speaker_id = ?+ AND vec_distance_cosine(se1.embedding, se2.embedding) < ?+ AND se2.speaker_id != ?+ "#,+ )+ .bind(target_speaker.id)+ .bind(threshold)+ .bind(target_speaker.id)+ .fetch_all(&mut *tx)+ .await?;++ for row in similar_rows {+ let emb_id: i64 = row.get("embedding_id");+ let old_speaker_id: i64 = row.get("speaker_id");++ // Move the embedding+ sqlx::query("UPDATE speaker_embeddings SET speaker_id = ? WHERE id = ?")+ .bind(target_speaker.id)+ .bind(emb_id)+ .execute(&mut *tx)+ .await?;+ embeddings_moved += 1;++ // Move transcriptions from the old speaker+ sqlx::query("UPDATE audio_transcriptions SET speaker_id = ? WHERE speaker_id = ?")+ .bind(target_speaker.id)+ .bind(old_speaker_id)+ .execute(&mut *tx)+ .await?;++ // Check if old speaker has no more embeddings, delete if empty+ let remaining: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM speaker_embeddings WHERE speaker_id = ?",+ )+ .bind(old_speaker_id)+ .fetch_one(&mut *tx)+ .await?;++ if remaining == 0 {+ sqlx::query("DELETE FROM speakers WHERE id = ?")+ .bind(old_speaker_id)+ .execute(&mut *tx)+ .await?;+ }+ }+ }++ // 6. Clean up: if original speaker has no embeddings left, delete it+ let remaining: i64 =+ sqlx::query_scalar("SELECT COUNT(*) FROM speaker_embeddings WHERE speaker_id = ?")+ .bind(current_speaker_id)+ .fetch_one(&mut *tx)+ .await?;++ if remaining == 0 && current_speaker_id != target_speaker.id {+ sqlx::query("DELETE FROM speakers WHERE id = ?")+ .bind(current_speaker_id)+ .execute(&mut *tx)+ .await?;+ }++ tx.commit().await?;++ Ok((target_speaker.id, transcriptions_updated, embeddings_moved))+ }}pub fn find_matching_positions(blocks: &[OcrTextBlock], query: &str) -> Vec<TextPosition> {diff --git a/screenpipe-db/src/types.rs b/screenpipe-db/src/types.rsindex ecdc0c544..8a2012c34 100644--- a/screenpipe-db/src/types.rs+++ b/screenpipe-db/src/types.rs@@ -181,6 +181,9 @@ pub struct AudioEntry {pub is_input: bool,pub audio_file_path: String,pub duration_secs: f64,+ pub audio_chunk_id: i64,+ pub speaker_id: Option<i64>,+ pub speaker_name: Option<String>,}#[derive(OaSchema, Debug, Clone)]diff --git a/screenpipe-db/tests/speaker_reassignment_test.rs b/screenpipe-db/tests/speaker_reassignment_test.rsnew file mode 100644index 000000000..dc2ba4175--- /dev/null+++ b/screenpipe-db/tests/speaker_reassignment_test.rs@@ -0,0 +1,346 @@+#[cfg(test)]+mod speaker_reassignment_tests {+ use screenpipe_db::{AudioDevice, DatabaseManager, DeviceType};++ async fn setup_test_db() -> DatabaseManager {+ let _ = tracing_subscriber::fmt()+ .with_max_level(tracing::Level::INFO)+ .try_init();++ let db = DatabaseManager::new("sqlite::memory:").await.unwrap();++ sqlx::migrate!("./src/migrations")+ .run(&db.pool)+ .await+ .expect("Failed to run migrations");++ db+ }++ /// Helper to create a speaker with an embedding+ async fn create_speaker_with_embedding(db: &DatabaseManager, embedding: &[f32]) -> i64 {+ let speaker = db.insert_speaker(embedding).await.unwrap();+ speaker.id+ }++ /// Helper to create an audio transcription linked to a speaker+ async fn create_audio_with_speaker(+ db: &DatabaseManager,+ speaker_id: i64,+ transcription: &str,+ ) -> i64 {+ let audio_chunk_id = db+ .insert_audio_chunk(&format!("audio_{}.mp4", speaker_id))+ .await+ .unwrap();++ db.insert_audio_transcription(+ audio_chunk_id,+ transcription,+ 0,+ "",+ &AudioDevice {+ name: "test_mic".to_string(),+ device_type: DeviceType::Input,+ },+ Some(speaker_id),+ Some(0.0),+ Some(5.0),+ )+ .await+ .unwrap();++ audio_chunk_id+ }++ // =========================================================================+ // TEST: find_speaker_by_name+ // =========================================================================++ #[tokio::test]+ async fn test_find_speaker_by_name_exists() {+ let db = setup_test_db().await;++ // Create a speaker with a name+ let embedding: Vec<f32> = vec![0.1; 512];+ let speaker_id = create_speaker_with_embedding(&db, &embedding).await;+ db.update_speaker_name(speaker_id, "Alice").await.unwrap();++ // Find by name+ let found = db.find_speaker_by_name("Alice").await.unwrap();+ assert!(found.is_some());+ assert_eq!(found.unwrap().name, "Alice");+ }++ #[tokio::test]+ async fn test_find_speaker_by_name_not_exists() {+ let db = setup_test_db().await;++ let found = db.find_speaker_by_name("NonExistent").await.unwrap();+ assert!(found.is_none());+ }++ #[tokio::test]+ async fn test_find_speaker_by_name_excludes_hallucinations() {+ let db = setup_test_db().await;++ // Create a speaker and mark as hallucination+ let embedding: Vec<f32> = vec![0.1; 512];+ let speaker_id = create_speaker_with_embedding(&db, &embedding).await;+ db.update_speaker_name(speaker_id, "Ghost").await.unwrap();+ db.mark_speaker_as_hallucination(speaker_id).await.unwrap();++ // Should not find hallucinated speaker+ let found = db.find_speaker_by_name("Ghost").await.unwrap();+ assert!(found.is_none());+ }++ // =========================================================================+ // TEST: count_embeddings_for_speaker+ // =========================================================================++ #[tokio::test]+ async fn test_count_embeddings_for_speaker() {+ let db = setup_test_db().await;++ let embedding: Vec<f32> = vec![0.1; 512];+ let speaker_id = create_speaker_with_embedding(&db, &embedding).await;++ let count = db.count_embeddings_for_speaker(speaker_id).await.unwrap();+ assert_eq!(count, 1);+ }++ #[tokio::test]+ async fn test_count_embeddings_for_nonexistent_speaker() {+ let db = setup_test_db().await;++ let count = db.count_embeddings_for_speaker(99999).await.unwrap();+ assert_eq!(count, 0);+ }++ // =========================================================================+ // TEST: create_speaker_with_name+ // =========================================================================++ #[tokio::test]+ async fn test_create_speaker_with_name() {+ let db = setup_test_db().await;++ let speaker = db.create_speaker_with_name("Bob").await.unwrap();+ assert_eq!(speaker.name, "Bob");+ assert!(speaker.id > 0);++ // Verify it can be found+ let found = db.find_speaker_by_name("Bob").await.unwrap();+ assert!(found.is_some());+ }++ // =========================================================================+ // TEST: update_transcriptions_speaker+ // =========================================================================++ #[tokio::test]+ async fn test_update_transcriptions_speaker() {+ let db = setup_test_db().await;++ // Create speaker and audio+ let embedding: Vec<f32> = vec![0.1; 512];+ let speaker_id = create_speaker_with_embedding(&db, &embedding).await;+ let audio_chunk_id =+ create_audio_with_speaker(&db, speaker_id, "Hello, this is a test").await;++ // Create new speaker+ let new_speaker = db.create_speaker_with_name("NewPerson").await.unwrap();++ // Update transcriptions+ let rows_updated = db+ .update_transcriptions_speaker(audio_chunk_id, new_speaker.id)+ .await+ .unwrap();++ assert!(rows_updated > 0);+ }++ // =========================================================================+ // TEST: reassign_speaker (main flow)+ // =========================================================================++ #[tokio::test]+ async fn test_reassign_speaker_to_new_name() {+ let db = setup_test_db().await;++ // Create speaker and audio+ let embedding: Vec<f32> = vec![0.1; 512];+ let speaker_id = create_speaker_with_embedding(&db, &embedding).await;+ let audio_chunk_id =+ create_audio_with_speaker(&db, speaker_id, "Hello, this is Louis speaking").await;++ // Reassign to new name+ let (new_speaker_id, transcriptions_updated, embeddings_moved) = db+ .reassign_speaker(audio_chunk_id, "Louis", false)+ .await+ .unwrap();++ assert!(new_speaker_id > 0);+ assert!(transcriptions_updated > 0);+ assert!(embeddings_moved > 0);++ // Verify the new speaker exists with the name+ let speaker = db.get_speaker_by_id(new_speaker_id).await.unwrap();+ assert_eq!(speaker.name, "Louis");+ }++ #[tokio::test]+ async fn test_reassign_speaker_to_existing_name() {+ let db = setup_test_db().await;++ // Create first speaker "Alice"+ let embedding1: Vec<f32> = vec![0.1; 512];+ let alice_id = create_speaker_with_embedding(&db, &embedding1).await;+ db.update_speaker_name(alice_id, "Alice").await.unwrap();++ // Create second speaker (unknown)+ let embedding2: Vec<f32> = vec![0.2; 512];+ let unknown_id = create_speaker_with_embedding(&db, &embedding2).await;+ let audio_chunk_id =+ create_audio_with_speaker(&db, unknown_id, "This is also Alice speaking").await;++ // Reassign unknown to "Alice"+ let (new_speaker_id, transcriptions_updated, embeddings_moved) = db+ .reassign_speaker(audio_chunk_id, "Alice", false)+ .await+ .unwrap();++ // Should merge to existing Alice+ assert_eq!(new_speaker_id, alice_id);+ assert!(transcriptions_updated > 0);+ assert!(embeddings_moved > 0);++ // Original unknown speaker should be deleted (no embeddings left)+ let old_count = db.count_embeddings_for_speaker(unknown_id).await.unwrap();+ assert_eq!(old_count, 0);+ }++ #[tokio::test]+ async fn test_reassign_speaker_propagate_similar() {+ let db = setup_test_db().await;++ // Create speaker with embedding+ let embedding1: Vec<f32> = vec![0.5; 512];+ let speaker1_id = create_speaker_with_embedding(&db, &embedding1).await;+ let audio_chunk_id1 =+ create_audio_with_speaker(&db, speaker1_id, "First transcription").await;++ // Create another speaker with very similar embedding+ let mut embedding2: Vec<f32> = vec![0.5; 512];+ embedding2[0] = 0.51; // Very similar+ let speaker2_id = create_speaker_with_embedding(&db, &embedding2).await;+ let _audio_chunk_id2 =+ create_audio_with_speaker(&db, speaker2_id, "Second transcription").await;++ // Reassign first speaker to "Bob" with propagation+ let (new_speaker_id, transcriptions_updated, embeddings_moved) = db+ .reassign_speaker(audio_chunk_id1, "Bob", true)+ .await+ .unwrap();++ assert!(new_speaker_id > 0);+ // With propagate_similar=true, similar embeddings should also be moved+ // Note: The actual number depends on the similarity threshold+ println!(+ "Reassignment: new_id={}, transcriptions={}, embeddings={}",+ new_speaker_id, transcriptions_updated, embeddings_moved+ );+ }++ #[tokio::test]+ async fn test_reassign_speaker_invalid_audio_chunk() {+ let db = setup_test_db().await;++ // Try to reassign non-existent audio chunk+ let result = db.reassign_speaker(99999, "SomeName", false).await;++ assert!(result.is_err());+ }++ // =========================================================================+ // TEST: Edge cases+ // =========================================================================++ #[tokio::test]+ async fn test_reassign_to_same_name_twice() {+ let db = setup_test_db().await;++ // Create speaker and audio+ let embedding: Vec<f32> = vec![0.1; 512];+ let speaker_id = create_speaker_with_embedding(&db, &embedding).await;+ let audio_chunk_id = create_audio_with_speaker(&db, speaker_id, "Test audio").await;++ // First reassignment+ let (first_id, _, _) = db+ .reassign_speaker(audio_chunk_id, "Charlie", false)+ .await+ .unwrap();++ // Second reassignment to same name should return same speaker+ let (second_id, _, _) = db+ .reassign_speaker(audio_chunk_id, "Charlie", false)+ .await+ .unwrap();++ assert_eq!(first_id, second_id);+ }++ #[tokio::test]+ async fn test_reassign_corrects_misidentification() {+ let db = setup_test_db().await;++ // Scenario: Audio was incorrectly assigned to "Alice", should be "Bob"+ // Note: When we reassign, the embedding gets moved from Alice to Bob.+ // If Alice only had one embedding, she'll be deleted (cleanup behavior).++ // Create "Alice" speaker with her own embedding and audio+ let alice_embedding: Vec<f32> = vec![0.1; 512];+ let alice_id = create_speaker_with_embedding(&db, &alice_embedding).await;+ db.update_speaker_name(alice_id, "Alice").await.unwrap();++ // Give Alice some legitimate audio so she doesn't get deleted+ let _alice_audio =+ create_audio_with_speaker(&db, alice_id, "This is Alice speaking correctly").await;++ // Create a second embedding that will be "misidentified" as Alice+ // In reality, this would happen at recording time via embedding matching+ let misidentified_embedding: Vec<f32> = vec![0.9; 512]; // Different voice+ let misidentified_speaker_id =+ create_speaker_with_embedding(&db, &misidentified_embedding).await;++ // This audio was incorrectly assigned to the misidentified speaker+ // (which initially has no name, just like when diarization creates a new speaker)+ let audio_chunk_id = create_audio_with_speaker(+ &db,+ misidentified_speaker_id,+ "This is actually Bob speaking",+ )+ .await;++ // Correct the misidentification by naming it "Bob"+ let (bob_id, transcriptions_updated, _embeddings_moved) = db+ .reassign_speaker(audio_chunk_id, "Bob", false)+ .await+ .unwrap();++ // Bob should be a new speaker (the renamed misidentified one)+ assert!(bob_id > 0);+ assert!(transcriptions_updated > 0);++ // Verify Bob exists with the correct name+ let bob = db.get_speaker_by_id(bob_id).await.unwrap();+ assert_eq!(bob.name, "Bob");++ // Alice should still exist with her embedding+ let alice = db.get_speaker_by_id(alice_id).await.unwrap();+ assert_eq!(alice.name, "Alice");+ let alice_embedding_count = db.count_embeddings_for_speaker(alice_id).await.unwrap();+ assert_eq!(alice_embedding_count, 1); // Alice still has her original embedding+ }+}diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex f06da0aba..389367e4b 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -188,6 +188,26 @@ pub struct SearchSpeakersRequest {pub name: Option<String>,}+#[derive(OaSchema, Serialize, Deserialize, Debug)]+pub struct ReassignSpeakerRequest {+ pub audio_chunk_id: i64,+ pub new_speaker_name: String,+ #[serde(default = "default_propagate_similar")]+ pub propagate_similar: bool,+}++fn default_propagate_similar() -> bool {+ true+}++#[derive(OaSchema, Serialize, Debug)]+pub struct ReassignSpeakerResponse {+ pub new_speaker_id: i64,+ pub new_speaker_name: String,+ pub transcriptions_updated: u64,+ pub embeddings_moved: u64,+}+#[derive(OaSchema, Serialize, Deserialize, Debug)]pub struct DeleteSpeakerRequest {pub id: i64,@@ -1240,6 +1260,7 @@ impl SCServer {.post("/speakers/hallucination", mark_as_hallucination_handler).post("/speakers/merge", merge_speakers_handler).get("/speakers/similar", get_similar_speakers_handler)+ .post("/speakers/reassign", reassign_speaker_handler).post("/experimental/frames/merge", merge_frames_handler).get("/experimental/validate/media", validate_media_handler).post("/experimental/operator", find_elements_handler)@@ -1717,6 +1738,9 @@ pub struct AudioData {pub audio_file_path: String,pub duration_secs: f64,pub start_offset: f64, // offset from frame timestamp+ pub audio_chunk_id: i64,+ pub speaker_id: Option<i64>,+ pub speaker_name: Option<String>,}impl From<TimeSeriesFrame> for StreamTimeSeriesResponse {@@ -1749,6 +1773,9 @@ impl From<TimeSeriesFrame> for StreamTimeSeriesResponse {audio_file_path: audio.audio_file_path,duration_secs: audio.duration_secs,start_offset: 0.0, // calculate based on audio timestamp vs frame timestamp+ audio_chunk_id: audio.audio_chunk_id,+ speaker_id: audio.speaker_id,+ speaker_name: audio.speaker_name,}}).collect(),@@ -1973,6 +2000,35 @@ async fn get_similar_speakers_handler(Ok(JsonResponse(similar_speakers))}++#[oasgen]+async fn reassign_speaker_handler(+ State(state): State<Arc<AppState>>,+ Json(payload): Json<ReassignSpeakerRequest>,+) -> Result<JsonResponse<ReassignSpeakerResponse>, (StatusCode, JsonResponse<Value>)> {+ let (new_speaker_id, transcriptions_updated, embeddings_moved) = state+ .db+ .reassign_speaker(+ payload.audio_chunk_id,+ &payload.new_speaker_name,+ payload.propagate_similar,+ )+ .await+ .map_err(|e| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ JsonResponse(json!({"error": e.to_string()})),+ )+ })?;++ Ok(JsonResponse(ReassignSpeakerResponse {+ new_speaker_id,+ new_speaker_name: payload.new_speaker_name,+ transcriptions_updated,+ embeddings_moved,+ }))+}+// #[derive(OaSchema, Deserialize)]// pub struct AudioDeviceControlRequest {// device_name: String,@@ -3175,6 +3231,9 @@ fn create_time_series_frame(chunk: FrameData) -> TimeSeriesFrame {is_input: a.is_input,audio_file_path: a.audio_file_path.clone(),duration_secs: a.duration_secs,+ audio_chunk_id: a.audio_chunk_id,+ speaker_id: a.speaker_id,+ speaker_name: a.speaker_name.clone(),}).collect(),})diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rsindex 032aae848..e1b39e7ca 100644--- a/screenpipe-server/src/video_cache.rs+++ b/screenpipe-server/src/video_cache.rs@@ -41,6 +41,9 @@ pub struct AudioEntry {pub is_input: bool,pub audio_file_path: String,pub duration_secs: f64,+ pub audio_chunk_id: i64,+ pub speaker_id: Option<i64>,+ pub speaker_name: Option<String>,}impl From<screenpipe_db::AudioEntry> for AudioEntry {@@ -51,6 +54,9 @@ impl From<screenpipe_db::AudioEntry> for AudioEntry {is_input: db_entry.is_input,audio_file_path: db_entry.audio_file_path,duration_secs: db_entry.duration_secs,+ audio_chunk_id: db_entry.audio_chunk_id,+ speaker_id: db_entry.speaker_id,+ speaker_name: db_entry.speaker_name,}}}@@ -522,6 +528,9 @@ impl FrameCache {is_input: a.is_input,audio_file_path: a.audio_file_path.clone(),duration_secs: a.duration_secs,+ audio_chunk_id: a.audio_chunk_id,+ speaker_id: a.speaker_id,+ speaker_name: a.speaker_name.clone(),}).collect(),});@@ -804,6 +813,9 @@ async fn extract_frame(is_input: a.is_input,audio_file_path: a.audio_file_path.clone(),duration_secs: a.duration_secs,+ audio_chunk_id: a.audio_chunk_id,+ speaker_id: a.speaker_id,+ speaker_name: a.speaker_name.clone(),}).collect(),}],