Skip to content

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

Reenable event api (#1363)

Louis Beaumontf9d6f763f468
diff --git a/screenpipe-audio/Cargo.toml b/screenpipe-audio/Cargo.toml
index dd15aaa55..783803e75 100644
--- a/screenpipe-audio/Cargo.toml
+++ b/screenpipe-audio/Cargo.toml
@@ -62,6 +62,7 @@ webrtc-vad = "0.4.0"
reqwest = { workspace = true }
screenpipe-core = { path = "../screenpipe-core" }
+screenpipe-events = { path = "../screenpipe-events" }
# crossbeam
crossbeam = { workspace = true }
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 1d33ac988..48ecae9ae 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -1,5 +1,5 @@
use crate::audio_processing::audio_to_mono;
-use crate::realtime::{realtime_stt, RealtimeTranscriptionEvent};
+use crate::realtime::realtime_stt;
use crate::AudioInput;
use anyhow::{anyhow, Result};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
@@ -201,14 +201,12 @@ pub async fn start_realtime_recording(
audio_stream: Arc<AudioStream>,
languages: Vec<Language>,
is_running: Arc<AtomicBool>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
deepgram_api_key: Option<String>,
) -> Result<()> {
while is_running.load(Ordering::Relaxed) {
match realtime_stt(
audio_stream.clone(),
languages.clone(),
- realtime_transcription_sender.clone(),
is_running.clone(),
deepgram_api_key.clone(),
)
diff --git a/screenpipe-audio/src/deepgram/realtime.rs b/screenpipe-audio/src/deepgram/realtime.rs
index a5949fd5a..1f245e55a 100644
--- a/screenpipe-audio/src/deepgram/realtime.rs
+++ b/screenpipe-audio/src/deepgram/realtime.rs
@@ -1,5 +1,6 @@
use crate::{
- deepgram::CUSTOM_DEEPGRAM_API_TOKEN, realtime::RealtimeTranscriptionEvent, AudioStream,
+ deepgram::CUSTOM_DEEPGRAM_API_TOKEN, deepgram::DEEPGRAM_WEBSOCKET_URL,
+ realtime::RealtimeTranscriptionEvent, AudioStream,
};
use crate::{AudioDevice, DeviceType};
use anyhow::Result;
@@ -12,15 +13,16 @@ use deepgram::common::stream_response::StreamResponse;
use futures::channel::mpsc::{self, Receiver as FuturesReceiver};
use futures::{SinkExt, TryStreamExt};
use screenpipe_core::Language;
+use screenpipe_events::send_event;
use std::sync::{atomic::AtomicBool, Arc};
use std::time::Duration;
use tokio::sync::broadcast::Receiver;
-use tracing::error;
+use tokio::sync::oneshot;
+use tracing::info;
pub async fn stream_transcription_deepgram(
stream: Arc<AudioStream>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
- languages: Vec<Language>,
+ _languages: Vec<Language>, // TODO impl language
is_running: Arc<AtomicBool>,
deepgram_api_key: Option<String>,
) -> Result<()> {
@@ -28,9 +30,7 @@ pub async fn stream_transcription_deepgram(
stream.subscribe().await,
stream.device.clone(),
stream.device_config.sample_rate().0,
- realtime_transcription_sender,
is_running,
- languages,
deepgram_api_key,
)
.await?;
@@ -42,9 +42,7 @@ pub async fn start_deepgram_stream(
stream: Receiver<Vec<f32>>,
device: Arc<AudioDevice>,
sample_rate: u32,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
is_running: Arc<AtomicBool>,
- _languages: Vec<Language>,
deepgram_api_key: Option<String>,
) -> Result<()> {
let api_key = deepgram_api_key.unwrap_or(CUSTOM_DEEPGRAM_API_TOKEN.to_string());
@@ -53,7 +51,28 @@ pub async fn start_deepgram_stream(
return Err(anyhow::anyhow!("Deepgram API key not found"));
}
- let deepgram = deepgram::Deepgram::new(api_key)?;
+ // create shutdown rx from is_running
+ let (shutdown_tx, mut shutdown_rx) = oneshot::channel();
+
+ tokio::spawn(async move {
+ loop {
+ let running = is_running.load(std::sync::atomic::Ordering::SeqCst);
+ if !running {
+ shutdown_tx.send(()).unwrap();
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ });
+
+ info!("Starting deepgram stream for device: {}", device);
+
+ let deepgram = match DEEPGRAM_WEBSOCKET_URL.as_str().is_empty() {
+ true => deepgram::Deepgram::new(api_key)?,
+ false => {
+ deepgram::Deepgram::with_base_url_and_api_key(DEEPGRAM_WEBSOCKET_URL.as_str(), api_key)?
+ }
+ };
let deepgram_transcription = deepgram.transcription();
@@ -71,20 +90,18 @@ pub async fn start_deepgram_stream(
let mut handle = req.clone().handle().await?;
let mut results = req.stream(get_stream(stream)).await?;
- let realtime_transcription_sender_clone = realtime_transcription_sender.clone();
let device_clone = device.clone();
loop {
- if !is_running.load(std::sync::atomic::Ordering::SeqCst) {
- break;
- }
-
tokio::select! {
+ _ = &mut shutdown_rx => {
+ info!("Shutting down deepgram stream for device: {}", device);
+ break;
+ }
result = results.try_next() => {
if let Ok(Some(result)) = result {
handle_transcription(
result,
- realtime_transcription_sender_clone.clone(),
device_clone.clone(),
).await;
}
@@ -108,18 +125,16 @@ fn get_stream(mut stream: Receiver<Vec<f32>>) -> FuturesReceiver<Result<Bytes, R
for sample in data {
bytes.put_i16_le((sample * i16::MAX as f32) as i16);
}
- tx.send(Ok(bytes.freeze())).await.unwrap();
+ if tx.send(Ok(bytes.freeze())).await.is_err() {
+ tx.close_channel();
+ }
}
});
rx
}
-async fn handle_transcription(
- result: StreamResponse,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
- device: Arc<AudioDevice>,
-) {
+async fn handle_transcription(result: StreamResponse, device: Arc<AudioDevice>) {
if let StreamResponse::TranscriptResponse {
channel, is_final, ..
} = result
@@ -129,20 +144,16 @@ async fn handle_transcription(
let is_input = device.device_type == DeviceType::Input;
if !text.is_empty() {
- match realtime_transcription_sender.send(RealtimeTranscriptionEvent {
- timestamp: chrono::Utc::now(),
- device: device.to_string(),
- transcription: text.to_string(),
- is_final,
- is_input,
- }) {
- Ok(_) => {}
- Err(e) => {
- if !e.to_string().contains("channel closed") {
- error!("Error sending transcription event: {}", e);
- }
- }
- }
+ let _ = send_event(
+ "transcription",
+ RealtimeTranscriptionEvent {
+ timestamp: chrono::Utc::now(),
+ device: device.to_string(),
+ transcription: text.to_string(),
+ is_final,
+ is_input,
+ },
+ );
}
}
}
diff --git a/screenpipe-audio/src/realtime.rs b/screenpipe-audio/src/realtime.rs
index 5baf1a6e8..37569d49f 100644
--- a/screenpipe-audio/src/realtime.rs
+++ b/screenpipe-audio/src/realtime.rs
@@ -2,29 +2,21 @@ use crate::{deepgram::stream_transcription_deepgram, AudioStream};
use anyhow::Result;
use chrono::{DateTime, Utc};
use screenpipe_core::Language;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use std::sync::{atomic::AtomicBool, Arc};
pub async fn realtime_stt(
stream: Arc<AudioStream>,
languages: Vec<Language>,
- realtime_transcription_sender: Arc<tokio::sync::broadcast::Sender<RealtimeTranscriptionEvent>>,
is_running: Arc<AtomicBool>,
deepgram_api_key: Option<String>,
) -> Result<()> {
- stream_transcription_deepgram(
- stream,
- realtime_transcription_sender,
- languages,
- is_running,
- deepgram_api_key,
- )
- .await?;
+ stream_transcription_deepgram(stream, languages, is_running, deepgram_api_key).await?;
Ok(())
}
-#[derive(Serialize, Clone)]
+#[derive(Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RealtimeTranscriptionEvent {
pub timestamp: DateTime<Utc>,
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index bb472819d..3c3448210 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -397,8 +397,6 @@ async fn record_audio(
let realtime_audio_devices_clone = realtime_audio_devices_clone.clone();
let languages_clone = languages_clone.clone();
let is_running_loop = is_running_loop.clone();
- let realtime_transcription_sender_clone =
- realtime_transcription_sender_clone.clone();
let live_transcription_handle = Some(tokio::spawn(async move {
if realtime_audio_enabled
&& realtime_audio_devices_clone.contains(&audio_device_clone)
@@ -407,7 +405,6 @@ async fn record_audio(
audio_stream_clone,
languages_clone.clone(),
is_running_loop.clone(),
- realtime_transcription_sender_clone.clone(),
deepgram_api_key.clone(),
)
.await;