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

🐒

Louis Beaumont30f86ccf997a
diff --git a/Formula/screenpipe.rb b/Formula/screenpipe.rb
index 9f4e32ff1..5724889dd 100644
--- a/Formula/screenpipe.rb
+++ b/Formula/screenpipe.rb
@@ -15,6 +15,7 @@ class Screenpipe < Formula
end
depends_on "ffmpeg"
+ depends_on "tesseract"
def install
bin.install "screenpipe"
diff --git a/README.md b/README.md
index 799ac239a..34d728a57 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ brew install jq
```
3. Install library
```bash
-brew tap louis030195/screen-pipe https://github.com/louis030195/screen-pipe
+brew tap louis030195/screen-pipe https://github.com/louis030195/screen-pipe.git
brew install screenpipe
```
4. Run it:
diff --git a/examples/apps/screenpipe-app-tauri/.gitignore b/examples/apps/screenpipe-app-tauri/.gitignore
index ccd7f81b1..ccc2f3dda 100644
--- a/examples/apps/screenpipe-app-tauri/.gitignore
+++ b/examples/apps/screenpipe-app-tauri/.gitignore
@@ -38,3 +38,6 @@ next-env.d.ts
ffmpeg*
+*src-tauri/screenpipe*
+*src-tauri/tesseract*
+
diff --git a/examples/apps/screenpipe-app-tauri/scripts/pre_build.js b/examples/apps/screenpipe-app-tauri/scripts/pre_build.js
index f4c564025..36beecd67 100644
--- a/examples/apps/screenpipe-app-tauri/scripts/pre_build.js
+++ b/examples/apps/screenpipe-app-tauri/scripts/pre_build.js
@@ -126,6 +126,11 @@ if (platform == 'macos') {
await $`mv ${config.macos.ffmpegName} ${config.ffmpegRealname}`
await $`rm ${config.macos.ffmpegName}.tar.xz`
}
+ // install screenpipe through brew
+ // await $`brew tap louis030195/screen-pipe https://github.com/louis030195/screen-pipe.git`
+ // await $`brew install screenpipe`
+ await $`cp ../../../../target/release/screenpipe ./`
+ await $`sudo cp /opt/homebrew/bin/tesseract ./`
}
// Nvidia
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index d5e344f64..2dc03f730 100644
--- a/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -52,6 +52,8 @@ tauri-plugin-store = "2.0.0-beta"
anyhow = "1.0.71"
+which = "6.0.1"
+
# M series MacOS
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/Info.plist b/examples/apps/screenpipe-app-tauri/src-tauri/Info.plist
index cc7959d8f..bf11072b1 100644
--- a/examples/apps/screenpipe-app-tauri/src-tauri/Info.plist
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/Info.plist
@@ -6,6 +6,8 @@
<string>This app requires microphone access to record audio.</string>
<key>NSScreenCaptureUsageDescription</key>
<string>This app requires screen capture access to record the screen.</string>
+ <key>CGRequestScreenCaptureAccess</key>
+ <string>This app requires screen capture access to record the screen.</string>
<!-- <key>NSSystemExtensionUsageDescription</key>
<string>This app requires system extension access to capture audio output.</string> -->
</dict>
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/entitlements.plist b/examples/apps/screenpipe-app-tauri/src-tauri/entitlements.plist
index 27ab646b2..d6b7409ae 100644
--- a/examples/apps/screenpipe-app-tauri/src-tauri/entitlements.plist
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/entitlements.plist
@@ -2,27 +2,31 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
+ <key>com.apple.security.device.camera</key>
+ <true/>
<key>com.apple.security.device.audio-input</key>
<true/>
- <key>com.apple.security.temporary-exception.audio-unit-host</key>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+ <!-- <key>com.apple.security.device.audio-input</key>
<true/>
- <key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
+ <key>com.apple.security.temporary-exception.audio-unit-host</key>
+ <true/> -->
+ <!-- <key>com.apple.security.temporary-exception.mach-lookup.global-name</key>
<array>
<string>com.apple.audio.coreaudiod</string>
<string>com.apple.audio.audiohald</string>
- </array>
- <key>com.apple.security.device.camera</key>
+ </array> -->
+ <!-- <key>com.apple.security.device.camera</key>
<true/>
<key>com.apple.security.device.microphone</key>
<true/>
- <key>com.apple.security.files.user-selected.read-write</key>
- <true/>
- <key>com.apple.security.screen-capture</key>
- <true/>
+
+
<key>com.apple.developer.persistent-content-capture</key>
- <true/>
- <key>com.apple.developer.sustained-execution</key>
- <true/>
+ <true/> -->
+ <!-- <key>com.apple.developer.sustained-execution</key>
+ <true/> -->
<!-- <key>com.apple.security.temporary-exception.sbpl</key>
<string>(allow mach-lookup (global-name-regex #"^com.apple.coreservices.launchservicesd$"))</string>
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/find_screenpipe.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/find_screenpipe.rs
new file mode 100644
index 000000000..ee85b7942
--- /dev/null
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/find_screenpipe.rs
@@ -0,0 +1,98 @@
+use log::{debug, error};
+use std::path::PathBuf;
+use which::which;
+
+#[cfg(windows)]
+use std::os::windows::process::CommandExt;
+
+#[cfg(not(windows))]
+const EXECUTABLE_NAME: &str = "screenpipe";
+
+#[cfg(windows)]
+const EXECUTABLE_NAME: &str = "screenpipe.exe";
+
+#[cfg(windows)]
+const CREATE_NO_WINDOW: u32 = 0x08000000;
+
+pub fn find_screenpipe_path() -> Option<PathBuf> {
+ debug!("Starting search for screenpipe executable");
+
+ // Check if `ffmpeg` is in the PATH environment variable
+ if let Ok(path) = which(EXECUTABLE_NAME) {
+ debug!("Found screenpipe in PATH: {:?}", path);
+ return Some(path);
+ }
+ debug!("screenpipe not found in PATH");
+
+ // Check in current working directory
+ if let Ok(cwd) = std::env::current_dir() {
+ debug!("Current working directory: {:?}", cwd);
+ let screenpipe_in_cwd = cwd.join(EXECUTABLE_NAME);
+ if screenpipe_in_cwd.is_file() && screenpipe_in_cwd.exists() {
+ debug!(
+ "Found screenpipe in current working directory: {:?}",
+ screenpipe_in_cwd
+ );
+ return Some(screenpipe_in_cwd);
+ }
+ debug!("screenpipe not found in current working directory");
+ }
+
+ // Check in the same folder as the executable
+ if let Ok(exe_path) = std::env::current_exe() {
+ if let Some(exe_folder) = exe_path.parent() {
+ debug!("Executable folder: {:?}", exe_folder);
+ let screenpipe_in_exe_folder = exe_folder.join(EXECUTABLE_NAME);
+ if screenpipe_in_exe_folder.exists() {
+ debug!(
+ "Found screenpipe in executable folder: {:?}",
+ screenpipe_in_exe_folder
+ );
+ return Some(screenpipe_in_exe_folder);
+ }
+ debug!("screenpipe not found in executable folder");
+
+ // Platform-specific checks
+ #[cfg(target_os = "macos")]
+ {
+ let resources_folder = exe_folder.join("../Resources");
+ debug!("Resources folder: {:?}", resources_folder);
+ let screenpipe_in_resources = resources_folder.join(EXECUTABLE_NAME);
+ if screenpipe_in_resources.exists() {
+ debug!(
+ "Found screenpipe in Resources folder: {:?}",
+ screenpipe_in_resources
+ );
+ return Some(screenpipe_in_resources);
+ }
+ debug!("screenpipe not found in Resources folder");
+ }
+
+ #[cfg(target_os = "linux")]
+ {
+ let lib_folder = exe_folder.join("lib");
+ debug!("Lib folder: {:?}", lib_folder);
+ let screenpipe_in_lib = lib_folder.join(EXECUTABLE_NAME);
+ if screenpipe_in_lib.exists() {
+ debug!("Found screenpipe in lib folder: {:?}", screenpipe_in_lib);
+ return Some(screenpipe_in_lib);
+ }
+ debug!("screenpipe not found in lib folder");
+ }
+ }
+ }
+
+ // check in $HOME/.local/bin
+ let home = dirs::home_dir().unwrap();
+ let screenpipe_in_home = PathBuf::from(home).join(".local/bin").join(EXECUTABLE_NAME);
+ if screenpipe_in_home.exists() {
+ debug!(
+ "Found screenpipe in $HOME/.local/bin: {:?}",
+ screenpipe_in_home
+ );
+ return Some(screenpipe_in_home);
+ }
+
+ error!("screenpipe not found");
+ None // Return None if screenpipe is not found
+}
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index ff379bdab..5eff441ed 100644
--- a/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -4,42 +4,24 @@
use dirs::home_dir;
use log::{debug, error, info, LevelFilter};
use logs::MultiWriter;
-use screenpipe_audio::{
- default_input_device, default_output_device, list_audio_devices, parse_audio_device,
- AudioDevice, DeviceControl,
-};
-use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server};
use serde_json::Value;
-use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
-use std::ops::Deref;
+use tokio::sync::mpsc::unbounded_channel;
+
+use std::fs;
use std::path::PathBuf;
-use std::{
- fs,
- net::SocketAddr,
- sync::{atomic::AtomicBool, Arc},
- time::Duration,
-};
-use tauri::image::Image;
-use tauri::menu::{CheckMenuItem, IconMenuItem, Menu, MenuItem, SubmenuBuilder};
-use tauri::tray::{MouseButton, MouseButtonState, TrayIconEvent};
-use tauri::{
- menu::{MenuBuilder, MenuItemBuilder},
- tray::TrayIconBuilder,
- Manager,
-};
-use tauri::{State, Wry};
-use tauri_plugin_shell::ShellExt;
+
+use tauri::Manager;
+use tauri::Wry;
use tauri_plugin_store::{with_store, StoreCollection};
-use tokio::sync::mpsc;
use tauri_plugin_autostart::MacosLauncher;
mod analytics;
-use analytics::AnalyticsManager;
use crate::analytics::start_analytics;
+mod find_screenpipe;
mod logs;
fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {
@@ -59,179 +41,6 @@ struct TrayState {
menu: Option<tauri::menu::Menu<tauri::Wry>>,
}
-async fn initialize_audio(
- disable_audio: bool,
- custom_devices: &[String],
- audio_devices_control_sender: Arc<tokio::sync::mpsc::Sender<(AudioDevice, DeviceControl)>>,
-) -> (Vec<Arc<AudioDevice>>, HashMap<AudioDevice, DeviceControl>) {
- debug!(
- "Entering initialize_audio function, disable_audio={}",
- disable_audio
- );
- let mut audio_devices = Vec::new();
- let mut devices_status = HashMap::new();
-
- if disable_audio {
- info!("Audio recording is disabled");
- return (audio_devices, devices_status);
- }
-
- info!("Initializing audio devices...");
- let all_audio_devices = list_audio_devices().unwrap_or_default();
-
- for device in all_audio_devices {
- let device_control = DeviceControl {
- is_running: false,
- is_paused: false,
- };
- info!("Audio device: {:?}", device.to_string());
- devices_status.insert(device, device_control);
- }
-
- if custom_devices.is_empty() {
- if let Ok(input_device) = default_input_device() {
- info!("Default input device found: {:?}", input_device.to_string());
- audio_devices.push(Arc::new(input_device));
- }
- if let Ok(output_device) = default_output_device() {
- info!(
- "Default output device found: {:?}",
- output_device.to_string()
- );
- audio_devices.push(Arc::new(output_device));
- }
- } else {
- for device_str in custom_devices {
- if let Ok(device) = parse_audio_device(device_str) {
- info!("Custom device added: {:?}", device.to_string());
- audio_devices.push(Arc::new(device));
- } else {
- error!("Failed to parse audio device: {}", device_str);
- }
- }
- }
-
- if audio_devices.is_empty() {
- error!("No audio devices available. Audio recording will be disabled.");
- } else {
- info!("Using audio devices:");
- for device in &audio_devices {
- info!(" {}", device);
-
- let device_control = DeviceControl {
- is_running: true,
- is_paused: false,
- };
- let device_clone = device.deref().clone();
- let sender_clone = audio_devices_control_sender.clone();
- // send signal after everything started
- tokio::spawn(async move {
- tokio::time::sleep(Duration::from_secs(15)).await;
- let _ = sender_clone.send((device_clone, device_control)).await;
- });
- }
- }
-
- debug!("Exiting initialize_audio function");
- (audio_devices, devices_status)
-}
-
-async fn setup_server_and_recording(
- app: tauri::AppHandle,
- db: Arc<DatabaseManager>,
- local_data_dir: Arc<String>,
- port: u16,
- fps: f64,
- audio_chunk_duration: u64,
- disable_audio: bool,
- memory_threshold: f64,
- runtime_threshold: u64,
-) -> (
- Vec<Arc<AudioDevice>>,
- Arc<tokio::sync::mpsc::Sender<(AudioDevice, DeviceControl)>>,
-) {
- debug!("Entering setup_server_and_recording function");
- info!("Setting up server and recording...");
- info!("Configuration: port={}, fps={}, audio_chunk_duration={}s, disable_audio={}, memory_threshold={}%, runtime_threshold={}s",
- port, fps, audio_chunk_duration, disable_audio, memory_threshold, runtime_threshold);
-
- let (audio_devices_control_sender, audio_devices_control_receiver) = mpsc::channel(64);
- let audio_devices_control_sender = Arc::new(audio_devices_control_sender);
- let audio_sender_for_server = audio_devices_control_sender.clone();
- let audio_sender_for_return = audio_devices_control_sender.clone();
-
- debug!("Initializing audio devices");
- let (audio_devices, devices_status) = initialize_audio(
- disable_audio,
- &[], // No custom devices for the app version
- audio_devices_control_sender,
- )
- .await;
-
- info!("Starting resource monitoring...");
- ResourceMonitor::new(memory_threshold, runtime_threshold, false)
- .start_monitoring(Duration::from_secs(10));
-
- let db_record = db.clone();
- let db_server = db.clone();
-
- let (_control_tx, control_rx) = tokio::sync::mpsc::channel(64);
- let vision_control = Arc::new(AtomicBool::new(true));
- let vision_control_server_clone = vision_control.clone();
-
- info!("Spawning continuous recording task...");
- let _recording_task = tokio::spawn({
- let local_data_dir = local_data_dir.clone();
- async move {
- let audio_chunk_duration = Duration::from_secs(audio_chunk_duration);
-
- info!("Starting continuous recording...");
- start_continuous_recording(
- db_record,
- local_data_dir,
- fps,
- audio_chunk_duration,
- control_rx,
- vision_control,
- audio_devices_control_receiver,
- false,
- )
- .await
- }
- });
- let _app_handle = app.app_handle();
-
- let analytics_manager = app.state::<Arc<AnalyticsManager>>().inner().clone();
- let api_plugin = move |req: &axum::http::Request<axum::body::Body>| {
- if req.uri().path() == "/search" {
- let analytics_manager = analytics_manager.clone();
- tokio::spawn(async move {
- if let Err(e) = analytics_manager.track_search().await {
- error!("Failed to track search request: {}", e);
- }
- });
- }
- };
- info!("Spawning server task...");
- tokio::spawn(async move {
- let server = Server::new(
- db_server,
- SocketAddr::from(([0, 0, 0, 0], port)),
- vision_control_server_clone,
- audio_sender_for_server.deref().clone(),
- );
- info!("Starting server...");
-
- if let Err(e) = server.start(devices_status, api_plugin).await {
- error!("Failed to start server: {}", e);
- }
- });
-
- info!("Server started on http://localhost:{}", port);
-
- (audio_devices, audio_sender_for_return)
-}
-
#[tokio::main]
async fn main() {
let _guard = sentry::init(("https://cf682877173997afc8463e5ca2fbe3c7@o4507617161314304.ingest.us.sentry.io/4507617170161664", sentry::ClientOptions {
@@ -263,17 +72,18 @@ async fn main() {
builder
.filter(None, LevelFilter::Info)
.filter_module("tokenizers", LevelFilter::Error)
- .filter_module("rusty_tesseract", LevelFilter::Error)
+ // .filter_module("rusty_tesseract", LevelFilter::Error)
.filter_module("symphonia", LevelFilter::Error);
if debug {
builder.filter_module("screenpipe", LevelFilter::Debug);
+ builder.filter_module("app", LevelFilter::Debug);
}
// debug!("all param: {:?}", cli.args);
let log_file =
- File::create(format!("{}/screenpipe.log", base_dir.to_string_lossy())).unwrap();
+ File::create(format!("{}/screenpipe-app.log", base_dir.to_string_lossy())).unwrap();
let multi_writer = MultiWriter::new(vec![
Box::new(log_file) as Box<dyn Write + Send>,
Box::new(std::io::stdout()) as Box<dyn Write + Send>,
@@ -319,200 +129,141 @@ async fn main() {
Ok(())
});
- // let handle = app.handle();
- // let menu = MenuBuilder::new(handle)
- // .item(&MenuItem::new(handle, "MenuItem 1", true, None::<&str>)?)
- // .items(&[
- // &CheckMenuItem::new(handle, "CheckMenuItem 1", true, true, None::<&str>)?,
- // &IconMenuItem::new(
- // handle,
- // "IconMenuItem 1",
- // true,
- // Some(tauri::image::Image::from_bytes(include_bytes!(
- // "../icons/32x32.png"
- // ))?),
- // None::<&str>,
- // )?,
- // ])
- // .text("item2", "MenuItem 2")
- // .check("checkitem2", "CheckMenuItem 2")
- // .icon(
- // "iconitem2",
- // "IconMenuItem 2",
- // app.default_window_icon().cloned().unwrap(),
- // )
- // .build()?;
-
- // let _tray = tauri::tray::TrayIconBuilder::with_id("main")
- // .menu(&menu)
- // .on_menu_event(|app, event| match event.id().as_ref() {
- // "show" => {
- // info!("show");
- // }
- // "quit" => {
- // app.exit(0);
- // }
- // _ => {
- // info!("other: {:?}", event.id());
- // }
- // })
- // .build(app)?;
-
- // _tray.set_show_menu_on_left_click(true);
-
- // let _menu = app.set_menu(menu).unwrap().unwrap();
- // app.on_tray_icon_event(|app, event| {
- // info!("tray icon event: {:?}", event);
- // if let tauri::tray::TrayIconEvent::Click {
- // button,
- // button_state,
- // ..
- // } = event
- // {
- // // if let Some(tray_handle) = app.tray_by_id("main") {
- // // let _ = tray_handle.set_visible(true);
- // // let menu = app.menu().unwrap();
- // // let items = menu.items();
- // // // print!(
- // // // "hhh {:?}",
- // // // items.map(|item| item).into_iter().collect::<Vec<_>>()
- // // // );
-
- // // if let Some(item) = menu.get("MenuItem 1") {
- // // let _ = item.as_menuitem().unwrap().set_text("Enable Analytics");
- // // }
- // // }
- // }
- // });
- // info!("Menu set: {:?}", menu);
- // Tray setup
- // let quit_item = MenuItemBuilder::with_id("quit", "Quit").build(app)?;
- // let send_feedback_item =
- // MenuItemBuilder::with_id("send_feedback", "Send Feedback").build(app)?;
- // let toggle_analytics_item =
- // MenuItemBuilder::with_id("toggle_analytics", "Disable Analytics").build(app)?;
- // let toggle_autostart_item =
- // MenuItemBuilder::with_id("toggle_autostart", "Disable Autostart").build(app)?;
-
- // let menu = MenuBuilder::new(app)
- // .item(&send_feedback_item)
- // .item(&toggle_analytics_item)
- // .item(&toggle_autostart_item)
- // .separator()
- // .item(&quit_item)
- // .build()?;
-
- // app.manage(TrayState {
- // menu: Some(menu.clone()),
- // });
-
- // let _tray = TrayIconBuilder::new()
- // .title("Screenpipe")
- // // .icon(tauri::Icon::Raw(
- // // include_bytes!("../icons/icon.png").to_vec(),
- // // ))
- // .menu(&menu)
- // .on_menu_event(move |app, event| {
- // let tray_state: State<TrayState> = app.app_handle().state();
- // let menu = tray_state.menu.as_ref().unwrap();
-
- // match event.id().as_ref() {
- // "quit" => {
- // std::process::exit(0);
- // }
- // "send_feedback" => {
- // let email = "[email protected]";
- // let subject = "Screenpipe Feedback";
- // let body = r#"Please enter your feedback here...
-
- // ... or let's chat?
- // https://cal.com/louis030195/screenpipe
- // "#;
- // let url = format!("mailto:{}?subject={}&body={}", email, subject, body);
- // let app_handle = app.app_handle();
- // if let Err(e) = app_handle.shell().open(url, None) {
- // error!("Failed to open URL: {}", e);
- // }
- // }
- // "toggle_analytics" => {
- // let analytics_manager = app.state::<Arc<AnalyticsManager>>();
- // let is_enabled = analytics_manager.toggle_analytics();
- // if let Some(item) = menu.get("toggle_analytics") {
- // if is_enabled {
- // let _ =
- // item.as_menuitem().unwrap().set_text("Enable Analytics");
- // } else {
- // let _ =
- // item.as_menuitem().unwrap().set_text("Disable Analytics");
- // }
- // }
- // }
- // _ => {}
- // }
- // })
- // .on_tray_icon_event(|_tray, event| {
- // if let TrayIconEvent::Click {
- // button,
- // button_state,
- // ..
- // } = event
- // {
- // if button_state == MouseButtonState::Up && button == MouseButton::Left {
- // // Handle left-click event
- // }
- // }
- // })
- // .build(app)
- // .expect("Failed to build tray");
-
Ok(())
})
.build(tauri::generate_context!())
.expect("error while building tauri application");
// Run the app
- app.run(|app_handle, event| match event {
+ app.run(|_app_handle, event| match event {
tauri::RunEvent::Ready { .. } => {
- let app_handle_clone = app_handle.clone();
- start_server(app_handle_clone);
+ debug!("Ready event");
+ tauri::async_runtime::spawn(async move {
+ let _ = start_server().await;
+ });
+ }
+ tauri::RunEvent::ExitRequested { .. } => {
+ debug!("ExitRequested event");
+ // tauri::async_runtime::spawn(async move {
+ // tx.send(()).unwrap();
+ // });
}
-
_ => {}
});
}
-fn start_server(app_handle: tauri::AppHandle) {
- tokio::spawn(async move {
+use tokio::io::{AsyncBufReadExt, BufReader};
+
+async fn start_server() -> anyhow::Result<()> {
+ let _t = tokio::spawn(async move {
+ debug!("Starting server");
+
+ // kill any all process on port 3030
+ let _ = tokio::process::Command::new("pkill")
+ .arg("-f")
+ .arg("screenpipe")
+ .output()
+ .await;
+
+ // // print path
+ // debug!("Path: {:?}", std::env::var("PATH").unwrap());
+
+ // // set PATH to all stuf in ./*
+ // std::env::set_var(
+ // "PATH",
+ // format!("{:?}:{:?}", std::env::var("PATH").unwrap(), "."),
+ // );
+
+ // // also add /Applications/screenpipe.app/Contents/Resources
+ // std::env::set_var(
+ // "PATH",
+ // format!(
+ // "{:?}:{:?}",
+ // std::env::var("PATH").unwrap(),
+ // "/Applications/screenpipe.app/Contents/Resources/tesseract"
+ // ),
+ // );
+ // std::env::set_var(
+ // "PATH",
+ // format!(
+ // "{:?}:{:?}",
+ // std::env::var("PATH").unwrap(),
+ // "/Applications/screenpipe.app/Contents/Resources"
+ // ),
+ // );
+
+ // debug!("Path: {:?}", std::env::var("PATH").unwrap());
+
+ // list files ./
+ // debug!(
+ // "Files: {:?}",
+ // std::fs::read_dir(".").unwrap().collect::<Vec<_>>()
+ // );
+
+ let mut cmd =
+ tokio::process::Command::new(find_screenpipe::find_screenpipe_path().unwrap());
+ cmd.arg("--port").arg("3030");
+ cmd.arg("--debug");
let base_dir = get_base_dir(None).expect("Failed to ensure local data directory");
- let port = 3030;
- let fps = 1.0;
- let audio_chunk_duration = 30;
- let disable_audio = true; // TODO until manage to package libmp3 lame
- let memory_threshold = 80.0;
- let runtime_threshold = 3600;
-
- let db_dir = base_dir.join("data");
-
- let db = Arc::new(
- DatabaseManager::new(&format!("{}/db.sqlite", db_dir.to_string_lossy()))
- .await
- .unwrap(),
+ // cmd.arg("--data-dir").arg(base_dir);
+ // add tesseract to path from ./tesseract
+ // cmd.env(
+ // "PATH",
+ // format!(
+ // "{:?}:{:?}",
+ // std::env::var("PATH").unwrap(),
+ // "/Applications/screenpipe.app/Contents/Resources/tesseract"
+ // ),
+ // );
+ cmd.env(
+ "PATH",
+ format!(
+ "{:?}:{:?}",
+ std::env::var("PATH").unwrap(),
+ "/Applications/screenpipe.app/Contents/Resources"
+ ),
);
- app_handle.manage(db.clone());
-
- let path = Arc::new(db_dir.to_string_lossy().into_owned());
-
- setup_server_and_recording(
- app_handle,
- db,
- path,
- port,
- fps,
- audio_chunk_duration,
- disable_audio,
- memory_threshold,
- runtime_threshold,
- )
- .await;
+ cmd.stdout(std::process::Stdio::piped());
+ cmd.stderr(std::process::Stdio::piped());
+
+ let mut child = cmd.spawn().expect("Failed to spawn command");
+
+ let stdout = child.stdout.take().expect("Failed to capture stdout");
+ let stderr = child.stderr.take().expect("Failed to capture stderr");
+
+ let mut stdout_reader = BufReader::new(stdout).lines();
+ let mut stderr_reader = BufReader::new(stderr).lines();
+
+ tokio::spawn(async move {
+ while let Ok(Some(line)) = stdout_reader.next_line().await {
+ debug!("{}", line);
+ }
+ });
+
+ tokio::spawn(async move {
+ while let Ok(Some(line)) = stderr_reader.next_line().await {
+ debug!("{}", line);
+ }
+ });
+
+ let output = child
+ .wait_with_output()
+ .await
+ .expect("Failed to wait for child process");
+ debug!("Child process exited with output: {:?}", output);
+ if output.status.success() {
+ Ok(())
+ } else {
+ Err(anyhow::anyhow!(
+ "Child process exited with output: {:?}",
+ output
+ ))
+ }
});
+
+ // stop when rx is received
+ // let _ = rx.recv().await;
+ // t.abort();
+
+ Ok(())
}
diff --git a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
index 13282e008..c317c1b32 100644
--- a/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
+++ b/examples/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json
@@ -24,7 +24,9 @@
}
},
"resources": {
- "ffmpeg/bin/*": "./"
+ "ffmpeg/bin/*": "./",
+ "screenpipe": "./",
+ "tesseract": "./"
}
}
}
\ No newline at end of file
diff --git a/screenpipe-server/Cargo.toml b/screenpipe-server/Cargo.toml
index 3cfaa20c4..5572251a4 100644
--- a/screenpipe-server/Cargo.toml
+++ b/screenpipe-server/Cargo.toml
@@ -21,7 +21,8 @@ screenpipe-core = { path = "../screenpipe-core" }
image = "0.25.0"
# OCR
-rusty-tesseract = "1.1.10"
+# rusty-tesseract = "1.1.10"
+rusty-tesseract = { git = "https://github.com/louis030195/rusty-tesseract.git", branch = "main" }
# threadpool
threadpool = "1.8.1"
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index f71fcbe0d..de124a0ea 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -1,6 +1,6 @@
use std::{
collections::HashMap,
- fs,
+ fs::{self, File},
net::SocketAddr,
ops::Deref,
path::PathBuf,
@@ -17,8 +17,10 @@ use screenpipe_audio::{
default_input_device, default_output_device, list_audio_devices, parse_audio_device,
DeviceControl,
};
+use std::io::Write;
use screenpipe_core::find_ffmpeg_path;
+use screenpipe_server::logs::MultiWriter;
use screenpipe_server::{start_continuous_recording, DatabaseManager, ResourceMonitor, Server};
use tokio::sync::mpsc::channel;
@@ -101,7 +103,7 @@ fn get_base_dir(custom_path: Option<String>) -> anyhow::Result<PathBuf> {
let data_dir = base_dir.join("data");
fs::create_dir_all(&data_dir)?;
- Ok(data_dir)
+ Ok(base_dir)
}
#[tokio::main]
@@ -118,7 +120,7 @@ async fn main() -> anyhow::Result<()> {
builder
.filter(None, LevelFilter::Info)
.filter_module("tokenizers", LevelFilter::Error)
- .filter_module("rusty_tesseract", LevelFilter::Error)
+ // .filter_module("rusty_tesseract", LevelFilter::Error)
.filter_module("symphonia", LevelFilter::Error);
if cli.debug {
@@ -129,9 +131,23 @@ async fn main() -> anyhow::Result<()> {
debug!("Text files will be saved.");
}
- builder.init();
+ // builder.init();
// tokio-console
// console_subscriber::init();
+ let local_data_dir = get_base_dir(cli.data_dir)?;
+
+ let log_file = File::create(format!(
+ "{}/screenpipe.log",
+ local_data_dir.to_string_lossy()
+ ))
+ .unwrap();
+ let multi_writer = MultiWriter::new(vec![
+ Box::new(log_file) as Box<dyn Write + Send>,
+ Box::new(std::io::stdout()) as Box<dyn Write + Send>,
+ ]);
+
+ builder.target(env_logger::Target::Pipe(Box::new(multi_writer)));
+ builder.format_timestamp_secs().init();
// Add warning for Linux and Windows users
#[cfg(any(target_os = "linux", target_os = "windows"))]
@@ -238,11 +254,8 @@ async fn main() -> anyhow::Result<()> {
);
resource_monitor.start_monitoring(Duration::from_secs(10)); // Log every 10 seconds
- let local_data_dir = get_base_dir(cli.data_dir)?;
- let local_data_dir = Arc::new(local_data_dir.to_string_lossy().into_owned());
- let local_data_dir_record = local_data_dir.clone();
let db = Arc::new(
- DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir))
+ DatabaseManager::new(&format!("{}/db.sqlite", local_data_dir.to_string_lossy()))
.await
.map_err(|e| {
eprintln!("Failed to initialize database: {:?}", e);
@@ -251,7 +264,7 @@ async fn main() -> anyhow::Result<()> {
);
info!(
"Database initialized, will store files in {}",
- local_data_dir
+ local_data_dir.to_string_lossy()
);
let db_record = db.clone();
let db_server = db.clone();
@@ -269,7 +282,7 @@ async fn main() -> anyhow::Result<()> {
start_continuous_recording(
db_record,
- local_data_dir_record,
+ Arc::new(local_data_dir.join("data").to_string_lossy().into_owned()),
cli.fps,
audio_chunk_duration,
control_rx,
diff --git a/screenpipe-server/src/lib.rs b/screenpipe-server/src/lib.rs
index 4b5a143cf..30fb15325 100644
--- a/screenpipe-server/src/lib.rs
+++ b/screenpipe-server/src/lib.rs
@@ -4,9 +4,11 @@ mod plugin;
mod resource_monitor;
mod server;
mod video;
+pub mod logs;
pub use core::{start_continuous_recording, RecorderControl};
pub use db::{ContentType, DatabaseManager, SearchResult};
pub use resource_monitor::ResourceMonitor;
pub use server::Server;
pub use video::VideoCapture;
+pub use logs::MultiWriter;
diff --git a/screenpipe-server/src/logs.rs b/screenpipe-server/src/logs.rs
new file mode 100644
index 000000000..96aac57b6
--- /dev/null
+++ b/screenpipe-server/src/logs.rs
@@ -0,0 +1,26 @@
+use std::io::Write;
+pub struct MultiWriter {
+ writers: Vec<Box<dyn Write + Send>>,
+}
+
+impl MultiWriter {
+ pub fn new(writers: Vec<Box<dyn Write + Send>>) -> Self {
+ MultiWriter { writers }
+ }
+}
+
+impl Write for MultiWriter {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ for writer in &mut self.writers {
+ writer.write_all(buf)?;
+ }
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ for writer in &mut self.writers {
+ writer.flush()?;
+ }
+ Ok(())
+ }
+}
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index 6d147a5d1..3d5f45032 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -126,9 +126,16 @@ async fn save_frames_as_video(
if frame_count % frames_per_video == 0 || current_ffmpeg.is_none() {
debug!("Starting new FFmpeg process");
// Close previous FFmpeg process if exists
- if let Some(mut child) = current_ffmpeg.take() {
+ if let Some(child) = current_ffmpeg.take() {
drop(current_stdin.take()); // Ensure stdin is closed
- child.wait().await.expect("ffmpeg process failed");
+ let output = child
+ .wait_with_output()
+ .await
+ .expect("ffmpeg process failed");
+ debug!("FFmpeg process exited with status: {}", output.status);
+ if !output.status.success() {
+ error!("FFmpeg stderr: {}", String::from_utf8_lossy(&output.stderr));
+ }
}
// Wait for at least one frame before starting a new FFmpeg process
@@ -155,29 +162,46 @@ async fn save_frames_as_video(
// Call the callback with the new video chunk file path
new_chunk_callback(&output_file);
- let mut child = start_ffmpeg_process(&output_file, fps);
- let mut stdin = child.stdin.take().expect("Failed to open stdin");
- let stderr = child.stderr.take().expect("Failed to open stderr");
+ match start_ffmpeg_process(&output_file, fps).await {
+ Ok(mut child) => {
+ let mut stdin = child.stdin.take().expect("Failed to open stdin");
+ let stderr = child.stderr.take().expect("Failed to open stderr");
+ let stdout = child.stdout.take().expect("Failed to open stdout");
- // Write the first frame to FFmpeg
- stdin
- .write_all(&buffer)
- .await
- .expect("Failed to write first frame to ffmpeg");
- frame_count += 1;
+ // Write the first frame to FFmpeg
+ stdin
+ .write_all(&buffer)
+ .await
+ .expect("Failed to write first frame to ffmpeg");
+ frame_count += 1;
- // Spawn a task to log FFmpeg's stderr
- tokio::spawn(async move {
- let reader = BufReader::new(stderr);
- let mut lines = reader.lines();
- while let Ok(Some(line)) = lines.next_line().await {
- debug!("FFmpeg: {}", line);
- }
- });
+ // Spawn a task to log FFmpeg's stderr
+ tokio::spawn(async move {
+ let reader = BufReader::new(stderr);
+ let mut lines = reader.lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ debug!("FFmpeg: {}", line);
+ }
+ });
+
+ // Log FFmpeg's stdout
+ tokio::spawn(async move {
+ let reader = BufReader::new(stdout);
+ let mut lines = reader.lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ debug!("FFmpeg: {}", line);
+ }
+ });
- current_ffmpeg = Some(child);
- current_stdin = Some(stdin);
- debug!("New FFmpeg process started for file: {}", output_file);
+ current_ffmpeg = Some(child);
+ current_stdin = Some(stdin);
+ debug!("New FFmpeg process started for file: {}", output_file);
+ }
+ Err(e) => {
+ error!("Failed to start FFmpeg process: {}", e);
+ // Handle the error appropriately, maybe try to restart or exit
+ }
+ }
}
if let Some(result) = frame_queue.lock().await.pop_front() {
@@ -237,18 +261,19 @@ async fn save_frames_as_video(
}
}
-// TODO: use tokio::process::Command instead
-fn start_ffmpeg_process(output_file: &str, fps: f64) -> Child {
- // overrriding fps with max fps if over the max and warning user
- let mut fps = fps;
- if fps > MAX_FPS {
- warn!("Overriding FPS to {}", MAX_FPS);
- fps = MAX_FPS;
- }
+async fn start_ffmpeg_process(output_file: &str, fps: f64) -> Result<Child, anyhow::Error> {
+ // Overriding fps with max fps if over the max and warning user
+ let fps = if fps > MAX_FPS {
+ warn!("Overriding FPS from {} to {}", fps, MAX_FPS);
+ MAX_FPS
+ } else {
+ fps
+ };
info!("Starting FFmpeg process for file: {}", output_file);
- Command::new(find_ffmpeg_path().unwrap())
- .args([
+ let mut command = Command::new(find_ffmpeg_path().unwrap());
+ command
+ .args(&[
"-f",
"image2pipe",
"-vcodec",
@@ -268,7 +293,13 @@ fn start_ffmpeg_process(output_file: &str, fps: f64) -> Child {
output_file,
])
.stdin(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .expect("Failed to spawn ffmpeg process")
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+
+ debug!("FFmpeg command: {:?}", command);
+
+ let child = command.spawn()?;
+ debug!("FFmpeg process spawned");
+
+ Ok(child)
}
diff --git a/screenpipe-vision/Cargo.toml b/screenpipe-vision/Cargo.toml
index 3ee76580c..e4d6f26fe 100644
--- a/screenpipe-vision/Cargo.toml
+++ b/screenpipe-vision/Cargo.toml
@@ -28,7 +28,9 @@ tokio = { workspace = true }
image = "0.25.0"
# OCR
-rusty-tesseract = "1.1.10"
+# rusty-tesseract = "1.1.10"
+rusty-tesseract = { git = "https://github.com/louis030195/rusty-tesseract.git", branch = "main" }
+
# Dates
chrono = { version = "0.4.31", features = ["serde"] }