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(privacy): add PII removal for audio transcriptions (#2117)
Louis Beaumontfbb94b719ba9
diff --git a/screenpipe-audio/src/audio_manager/builder.rs b/screenpipe-audio/src/audio_manager/builder.rsindex 0a4729369..e6a0b861d 100644--- a/screenpipe-audio/src/audio_manager/builder.rs+++ b/screenpipe-audio/src/audio_manager/builder.rs@@ -32,6 +32,8 @@ pub struct AudioManagerOptions {pub deepgram_url: Option<String>,pub deepgram_websocket_url: Option<String>,pub output_path: Option<PathBuf>,+ /// Enable PII removal from audio transcriptions+ pub use_pii_removal: bool,}impl Default for AudioManagerOptions {@@ -56,6 +58,7 @@ impl Default for AudioManagerOptions {db_path: None,deepgram_url,deepgram_websocket_url,+ use_pii_removal: false,}}}@@ -137,6 +140,11 @@ impl AudioManagerBuilder {self}+ pub fn use_pii_removal(mut self, use_pii_removal: bool) -> Self {+ self.options.use_pii_removal = use_pii_removal;+ self+ }+pub async fn build(&mut self, db: Arc<DatabaseManager>) -> Result<AudioManager> {self.validate_options()?;let options = &mut self.options;diff --git a/screenpipe-audio/src/audio_manager/manager.rs b/screenpipe-audio/src/audio_manager/manager.rsindex 7b6cea6d7..363b0c559 100644--- a/screenpipe-audio/src/audio_manager/manager.rs+++ b/screenpipe-audio/src/audio_manager/manager.rs@@ -347,11 +347,15 @@ impl AudioManager {async fn start_transcription_receiver_handler(&self) -> Result<JoinHandle<()>> {let transcription_receiver = self.transcription_receiver.clone();let db = self.db.clone();- let transcription_engine = self.options.read().await.transcription_engine.clone();+ let options = self.options.read().await;+ let transcription_engine = options.transcription_engine.clone();+ let use_pii_removal = options.use_pii_removal;+ drop(options); // Release lock before spawningOk(tokio::spawn(handle_new_transcript(db,transcription_receiver,transcription_engine,+ use_pii_removal,)))}diff --git a/screenpipe-audio/src/transcription/handle_new_transcript.rs b/screenpipe-audio/src/transcription/handle_new_transcript.rsindex 50b687d3d..e1e12bf14 100644--- a/screenpipe-audio/src/transcription/handle_new_transcript.rs+++ b/screenpipe-audio/src/transcription/handle_new_transcript.rs@@ -80,6 +80,7 @@ pub async fn handle_new_transcript(db: Arc<DatabaseManager>,transcription_receiver: Arc<crossbeam::channel::Receiver<TranscriptionResult>>,transcription_engine: Arc<AudioTranscriptionEngine>,+ use_pii_removal: bool,) {let mut previous_transcript = "".to_string();let mut previous_transcript_id: Option<i64> = None;@@ -152,6 +153,7 @@ pub async fn handle_new_transcript(transcription_engine.clone(),processed_previous,previous_transcript_id,+ use_pii_removal,).await{diff --git a/screenpipe-audio/src/transcription/transcription_result.rs b/screenpipe-audio/src/transcription/transcription_result.rsindex 029116e99..594ef2a81 100644--- a/screenpipe-audio/src/transcription/transcription_result.rs+++ b/screenpipe-audio/src/transcription/transcription_result.rs@@ -1,5 +1,6 @@use std::sync::Arc;+use screenpipe_core::pii_removal::remove_pii;use screenpipe_db::{DatabaseManager, Speaker};use tracing::{debug, error, info};@@ -54,6 +55,7 @@ pub async fn process_transcription_result(audio_transcription_engine: Arc<AudioTranscriptionEngine>,previous_transcript: Option<String>,previous_transcript_id: Option<i64>,+ use_pii_removal: bool,) -> Result<Option<i64>, anyhow::Error> {if result.error.is_some() || result.transcription.is_none() {error!(@@ -67,7 +69,13 @@ pub async fn process_transcription_result(info!("Detected speaker: {:?}", speaker);- let transcription = result.transcription.unwrap();+ let raw_transcription = result.transcription.unwrap();+ // Apply PII removal if enabled+ let transcription = if use_pii_removal {+ remove_pii(&raw_transcription)+ } else {+ raw_transcription+ };let transcription_engine = audio_transcription_engine.to_string();let mut chunk_id: Option<i64> = None;@@ -77,8 +85,14 @@ pub async fn process_transcription_result();if let Some(id) = previous_transcript_id {if let Some(prev_transcript) = previous_transcript {+ // Apply PII removal to previous transcript update as well+ let sanitized_prev = if use_pii_removal {+ remove_pii(&prev_transcript)+ } else {+ prev_transcript+ };match db- .update_audio_transcription(id, prev_transcript.as_str())+ .update_audio_transcription(id, sanitized_prev.as_str()).await{Ok(_) => {}@@ -151,3 +165,142 @@ async fn get_or_create_speaker_from_embedding(Ok(speaker)}}++#[cfg(test)]+mod tests {+ use super::*;++ /// Test that PII removal works correctly on transcription text+ #[test]+ fn test_pii_removal_on_transcription() {+ // Email addresses+ let input = "Please contact me at [email protected] for more info";+ let result = remove_pii(input);+ assert_eq!(result, "Please contact me at [EMAIL] for more info");+ assert!(!result.contains("[email protected]"));++ // SSN+ let input = "My social security number is 123-45-6789";+ let result = remove_pii(input);+ assert_eq!(result, "My social security number is [SSN]");+ assert!(!result.contains("123-45-6789"));++ // Credit card with dashes+ let input = "Charge it to 4532-1234-5678-9012";+ let result = remove_pii(input);+ assert_eq!(result, "Charge it to [CREDIT_CARD]");+ assert!(!result.contains("4532"));++ // Credit card with spaces+ let input = "Card number is 4532 1234 5678 9012";+ let result = remove_pii(input);+ assert_eq!(result, "Card number is [CREDIT_CARD]");++ // Credit card without separators+ let input = "Use card 4532123456789012 please";+ let result = remove_pii(input);+ assert_eq!(result, "Use card [CREDIT_CARD] please");+ }++ /// Test that PII removal handles multiple PII types in one transcription+ #[test]+ fn test_pii_removal_multiple_types() {+ let input = "Hi, I'm at [email protected], my SSN is 111-22-3333 and card 1234-5678-9012-3456";+ let result = remove_pii(input);++ assert!(result.contains("[EMAIL]"));+ assert!(result.contains("[SSN]"));+ assert!(result.contains("[CREDIT_CARD]"));+ assert!(!result.contains("[email protected]"));+ assert!(!result.contains("111-22-3333"));+ assert!(!result.contains("1234-5678-9012-3456"));+ }++ /// Test that PII removal preserves non-PII content+ #[test]+ fn test_pii_removal_preserves_non_pii() {+ let input = "The meeting is at 3 PM in conference room 42. We'll discuss the quarterly report.";+ let result = remove_pii(input);+ assert_eq!(result, input); // No changes - no PII present+ }++ /// Test edge cases for transcription PII removal+ #[test]+ fn test_pii_removal_edge_cases() {+ // Empty string+ assert_eq!(remove_pii(""), "");++ // Only whitespace+ assert_eq!(remove_pii(" "), " ");++ // Multiple emails in a row+ let input = "Contact [email protected] or [email protected]";+ let result = remove_pii(input);+ assert_eq!(result, "Contact [EMAIL] or [EMAIL]");++ // PII at start and end+ let input = "123-45-6789 is my SSN and email is [email protected]";+ let result = remove_pii(input);+ assert!(result.starts_with("[SSN]"));+ assert!(result.ends_with("[EMAIL]"));+ }++ /// Test that common false positives are NOT redacted+ #[test]+ fn test_pii_removal_no_false_positives() {+ // Regular numbers should not be redacted+ assert_eq!(remove_pii("Call me at 555-1234"), "Call me at 555-1234");++ // Short number sequences+ assert_eq!(remove_pii("Room 1234"), "Room 1234");++ // Dates that look like SSNs but aren't (different format)+ assert_eq!(remove_pii("Date: 12/34/5678"), "Date: 12/34/5678");++ // URLs that aren't emails+ assert_eq!(remove_pii("Visit example.com"), "Visit example.com");+ }++ /// Test realistic transcription scenarios+ #[test]+ fn test_pii_removal_realistic_transcriptions() {+ // Meeting transcription with email mention+ let input = "So Sarah said to email her at [email protected] about the proposal";+ let result = remove_pii(input);+ assert_eq!(result, "So Sarah said to email her at [EMAIL] about the proposal");++ // Customer service call with card number+ let input = "I'll read you the card number: 4111 1111 1111 1111";+ let result = remove_pii(input);+ assert!(result.contains("[CREDIT_CARD]"));+ assert!(!result.contains("4111"));++ // Medical context with SSN (HIPAA sensitive)+ let input = "Patient SSN for records is 987-65-4321";+ let result = remove_pii(input);+ assert!(result.contains("[SSN]"));+ assert!(!result.contains("987-65-4321"));+ }++ /// Benchmark-style test to ensure PII removal is fast+ #[test]+ fn test_pii_removal_performance() {+ use std::time::Instant;++ let input = "Contact [email protected] about SSN 123-45-6789 and card 4532-1234-5678-9012";++ let start = Instant::now();+ for _ in 0..1000 {+ let _ = remove_pii(input);+ }+ let duration = start.elapsed();++ // Should process 1000 iterations in under 100ms (very conservative)+ // Actual should be ~1-5ms for 1000 iterations+ assert!(+ duration.as_millis() < 100,+ "PII removal too slow: {:?} for 1000 iterations",+ duration+ );+ }+}diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rsindex 5743800d6..ce1afcd68 100644--- a/screenpipe-server/src/bin/screenpipe-server.rs+++ b/screenpipe-server/src/bin/screenpipe-server.rs@@ -755,7 +755,8 @@ async fn main() -> anyhow::Result<()> {.realtime(cli.enable_realtime_audio_transcription).enabled_devices(audio_devices).deepgram_api_key(cli.deepgram_api_key.clone())- .output_path(PathBuf::from(output_path_clone.clone().to_string()));+ .output_path(PathBuf::from(output_path_clone.clone().to_string()))+ .use_pii_removal(cli.use_pii_removal);let audio_manager = match audio_manager_builder.build(db.clone()).await {Ok(manager) => Arc::new(manager),@@ -878,6 +879,7 @@ async fn main() -> anyhow::Result<()> {cli.disable_audio,audio_manager.clone(),cli.enable_pipe_manager,+ cli.use_pii_removal,);// print screenpipe in gradientdiff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rsindex 6a8949bd5..15c2cb230 100644--- a/screenpipe-server/src/server.rs+++ b/screenpipe-server/src/server.rs@@ -110,6 +110,8 @@ pub struct AppState {pub ws_connection_count: Arc<AtomicUsize>,/// LRU cache for search results (10x faster for repeated queries)pub search_cache: SearchCache,+ /// Enable PII removal from text content+ pub use_pii_removal: bool,}// Update the SearchQuery struct@@ -1197,6 +1199,7 @@ pub struct SCServer {vision_disabled: bool,audio_disabled: bool,enable_pipe: bool,+ use_pii_removal: bool,}impl SCServer {@@ -1210,6 +1213,7 @@ impl SCServer {audio_disabled: bool,audio_manager: Arc<AudioManager>,enable_pipe: bool,+ use_pii_removal: bool,) -> Self {SCServer {db,@@ -1220,6 +1224,7 @@ impl SCServer {audio_disabled,audio_manager,enable_pipe,+ use_pii_removal,}}@@ -1274,6 +1279,7 @@ impl SCServer {.max_capacity(1000).time_to_live(Duration::from_secs(60)).build(),+ use_pii_removal: self.use_pii_removal,});let cors = CorsLayer::new()@@ -1519,13 +1525,22 @@ async fn add_transcription_to_db(transcription: &AudioTranscription,device_name: &str,) -> Result<(), anyhow::Error> {+ use screenpipe_core::pii_removal::remove_pii;+let db = &state.db;+ // Apply PII removal if enabled+ let sanitized_transcription = if state.use_pii_removal {+ remove_pii(&transcription.transcription)+ } else {+ transcription.transcription.clone()+ };+let dummy_audio_chunk_id = db.insert_audio_chunk("").await?;db.insert_audio_transcription(dummy_audio_chunk_id, // No associated audio chunk- &transcription.transcription,+ &sanitized_transcription,-1,&transcription.transcription_engine,&screenpipe_db::AudioDevice {diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rsindex 3c3e094e4..c01a32ef5 100644--- a/screenpipe-server/tests/endpoint_test.rs+++ b/screenpipe-server/tests/endpoint_test.rs@@ -48,6 +48,7 @@ mod tests {false,audio_manager,true,+ false, // use_pii_removal);let router = app.create_router(true).await;diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rsindex 10bcd0e22..70138a07e 100644--- a/screenpipe-server/tests/tags_test.rs+++ b/screenpipe-server/tests/tags_test.rs@@ -37,6 +37,7 @@ async fn setup_test_app() -> (Router, Arc<DatabaseManager>) {false,audio_manager,true,+ false, // use_pii_removal);let router = app.create_router(true).await;