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

fix all warnings, tests

Ezra Ellette26a1618b4edb
diff --git a/rust-toolchain.toml b/rust-toolchain.toml
new file mode 100644
index 000000000..725f99f56
--- /dev/null
+++ b/rust-toolchain.toml
@@ -0,0 +1,3 @@
+[toolchain]
+channel = "stable"
+versioned = "1.84.0"
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.toml b/screenpipe-app-tauri/src-tauri/Cargo.toml
index 137f0e6b4..7ad112a13 100644
--- a/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -7,7 +7,7 @@ license = ""
repository = ""
default-run = "screenpipe-app"
edition = "2021"
-rust-version = "1.75"
+rust-version = "1.84"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -15,7 +15,8 @@ rust-version = "1.75"
tauri-build = { version = "=2.0.3", features = [] }
[dependencies]
-tauri = { version = "=2.1.1", features = [ "protocol-asset",
+tauri = { version = "=2.1.1", features = [
+ "protocol-asset",
"macos-private-api",
"tray-icon",
"devtools",
@@ -60,8 +61,6 @@ tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
tracing-appender = "0.2.3"
-
-
anyhow = "1.0.71"
# System information
@@ -71,7 +70,7 @@ sysinfo = "=0.29.0"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
# server
-axum = "0.6.0" # or your current version
+axum = "0.6.0" # or your current version
dirs = "5.0.1"
@@ -119,6 +118,7 @@ cudart = []
metal = []
mkl = []
llm = []
+cargo-clippy = []
default = ["custom-protocol"]
# DO NOT REMOVE!!
diff --git a/screenpipe-app-tauri/src-tauri/src/disk_usage.rs b/screenpipe-app-tauri/src-tauri/src/disk_usage.rs
index a7c32a522..1c3634a0b 100644
--- a/screenpipe-app-tauri/src-tauri/src/disk_usage.rs
+++ b/screenpipe-app-tauri/src-tauri/src/disk_usage.rs
@@ -1,9 +1,9 @@
+use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
-use tracing::info;
use std::path::{Path, PathBuf};
-use serde::{Deserialize, Serialize};
-use sysinfo::{System, SystemExt, DiskExt};
+use sysinfo::{DiskExt, System, SystemExt};
+use tracing::info;
#[derive(Debug, Serialize, Deserialize)]
pub struct DiskUsage {
@@ -79,12 +79,15 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, S
let path = entry.path();
if path.is_dir() {
let size = directory_size(&path).map_err(|e| e.to_string())?;
- pipes.push((path.file_name().unwrap().to_string_lossy().to_string(), readable(size)));
+ pipes.push((
+ path.file_name().unwrap().to_string_lossy().to_string(),
+ readable(size),
+ ));
}
}
- let total_data_size = directory_size(&screenpipe_dir).map_err(|e| e.to_string())?;
- let total_media_size= directory_size(&data_dir).map_err(|e| e.to_string())?;
+ let total_data_size = directory_size(screenpipe_dir).map_err(|e| e.to_string())?;
+ let total_media_size = directory_size(&data_dir).map_err(|e| e.to_string())?;
let total_pipes_size = directory_size(&pipes_dir).map_err(|e| e.to_string())?;
let total_cache_size = directory_size(&cache_dir).map_err(|e| e.to_string())?;
@@ -124,7 +127,7 @@ pub async fn disk_usage(screenpipe_dir: &PathBuf) -> Result<Option<DiskUsage>, S
total_media_size: readable(total_media_size),
},
total_data_size: readable(total_data_size + total_cache_size),
- total_cache_size: readable(total_cache_size),
+ total_cache_size: readable(total_cache_size),
avaiable_space: readable(avaiable_space),
};
diff --git a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs
index 58777a1e5..806409ace 100644
--- a/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs
+++ b/screenpipe-app-tauri/src-tauri/src/llm_sidecar.rs
@@ -50,10 +50,10 @@ impl LLMSidecar {
info!("Starting Ollama serve command...");
let mut serve_command = app.shell().sidecar("ollama").unwrap();
serve_command = serve_command
- .args(&["serve"])
+ .args(["serve"])
.env(
"OLLAMA_HOST",
- &format!("http://localhost:{}", self.settings.port),
+ format!("http://localhost:{}", self.settings.port),
)
.env("CUDA_PATH", &new_cuda_path);
@@ -74,7 +74,7 @@ impl LLMSidecar {
info!("Starting Ollama model...");
let mut model_command = app.shell().sidecar("ollama").unwrap();
model_command = model_command
- .args(&["run", &self.settings.model])
+ .args(["run", &self.settings.model])
.env("CUDA_PATH", &new_cuda_path);
#[cfg(target_os = "windows")]
@@ -172,7 +172,7 @@ impl LLMSidecar {
async fn attempt_model_test(&self) -> Result<String> {
let client = reqwest::Client::new();
let response = client
- .post(&format!(
+ .post(format!(
"http://localhost:{}/v1/chat/completions",
self.settings.port
))
@@ -212,7 +212,7 @@ impl LLMSidecar {
{
app.shell()
.command("taskkill")
- .args(&["/F", "/IM", "ollama.exe"])
+ .args(["/F", "/IM", "ollama.exe"])
.spawn()
.unwrap();
}
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index 031445849..0cd400272 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -39,6 +39,7 @@ mod icons;
use crate::analytics::start_analytics;
mod commands;
+mod disk_usage;
mod llm_sidecar;
mod permissions;
mod server;
@@ -46,7 +47,6 @@ mod sidecar;
mod store;
mod tray;
mod updates;
-mod disk_usage;
pub use commands::reset_all_pipes;
pub use commands::set_tray_health_icon;
pub use commands::set_tray_unhealth_icon;
@@ -96,7 +96,7 @@ impl ShortcutConfig {
.into_iter()
.filter_map(|profile| {
profiles_store
- .get(&format!("shortcuts.{}", profile))
+ .get(format!("shortcuts.{}", profile))
.and_then(|v| v.as_str().map(String::from))
.map(|shortcut| (profile, shortcut))
})
@@ -179,13 +179,14 @@ async fn register_shortcut(
.on_shortcut(shortcut, move |app, _shortcut, event| {
// Only trigger on key press, not release
if matches!(event.state, ShortcutState::Pressed) {
- handler(&app);
+ handler(app);
}
})
.map_err(|e| e.to_string())
}
#[tauri::command]
+#[allow(clippy::too_many_arguments)]
async fn update_global_shortcuts(
app: AppHandle,
show_shortcut: String,
@@ -288,7 +289,7 @@ async fn apply_shortcuts(app: &AppHandle, config: &ShortcutConfig) -> Result<(),
},
)
.await?;
-
+
// Register stop audio shortcut
register_shortcut(
app,
@@ -366,13 +367,12 @@ async fn list_pipes() -> anyhow::Result<Value> {
Ok(response)
}
-
fn get_base_dir(app: &tauri::AppHandle, custom_path: Option<String>) -> anyhow::Result<PathBuf> {
let default_path = app.path().local_data_dir().unwrap().join("screenpipe");
let local_data_dir = custom_path.map(PathBuf::from).unwrap_or(default_path);
- fs::create_dir_all(&local_data_dir.join("data"))?;
+ fs::create_dir_all(local_data_dir.join("data"))?;
Ok(local_data_dir)
}
@@ -387,10 +387,12 @@ pub struct LogFile {
async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
let data_dir = get_data_dir(&app).map_err(|e| e.to_string())?;
let mut log_files = Vec::new();
-
+
// Collect all entries first
let mut entries = Vec::new();
- let mut dir = tokio::fs::read_dir(&data_dir).await.map_err(|e| e.to_string())?;
+ let mut dir = tokio::fs::read_dir(&data_dir)
+ .await
+ .map_err(|e| e.to_string())?;
while let Some(entry) = dir.next_entry().await.map_err(|e| e.to_string())? {
// Get metadata immediately for each entry
if let Ok(metadata) = entry.metadata().await {
@@ -406,7 +408,7 @@ async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
.ok()
.and_then(|m| m.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
- .unwrap_or(0)
+ .unwrap_or(0),
)
});
@@ -438,7 +440,6 @@ async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
Ok(log_files)
}
-
fn send_recording_notification(
app_handle: &tauri::AppHandle,
success: bool,
@@ -681,7 +682,7 @@ async fn main() {
// Logging setup
let app_handle = app.handle();
let base_dir =
- get_base_dir(&app_handle, None).expect("Failed to ensure local data directory");
+ get_base_dir(app_handle, None).expect("Failed to ensure local data directory");
// Set up rolling file appender
let file_appender = RollingFileAppender::builder()
@@ -690,7 +691,7 @@ async fn main() {
.filename_suffix("log")
.max_log_files(5)
.build(
- &get_data_dir(&app.handle())
+ get_data_dir(app.handle())
.unwrap_or_else(|_| dirs::home_dir().unwrap().join(".screenpipe")),
)?;
@@ -793,7 +794,7 @@ async fn main() {
if pipe["enabled"].as_bool().unwrap_or(false) {
if let Some(id) = pipe["id"].as_str() {
let _ = reqwest::Client::new()
- .post(format!("http://localhost:3030/pipes/disable"))
+ .post("http://localhost:3030/pipes/disable")
.json(&serde_json::json!({
"pipe_id": id
}))
@@ -804,10 +805,12 @@ async fn main() {
}
}
}
-
+
// Stop any running recordings
let state = app_handle_clone.state::<SidecarState>();
- if let Err(e) = kill_all_sreenpipes(state, app_handle_clone.clone()).await {
+ if let Err(e) =
+ kill_all_sreenpipes(state, app_handle_clone.clone()).await
+ {
error!("Error stopping recordings during quit: {}", e);
}
});
@@ -909,7 +912,7 @@ async fn main() {
let _ = window.show();
let _ = window.set_focus();
} else {
- show_main_window(&app, true);
+ show_main_window(app, true);
}
}
}
@@ -922,7 +925,8 @@ async fn main() {
.build()
.unwrap();
- if store.keys().len() == 0 {
+ // TODO: proper lookup of keys rather than assuming they exist
+ if store.is_empty() {
store.set("analyticsEnabled".to_string(), Value::Bool(true));
store.set(
"config".to_string(),
@@ -1000,10 +1004,7 @@ async fn main() {
info!("use_dev_mode: {}", use_dev_mode);
- info!(
- "will start sidecar: {}",
- !use_dev_mode && has_files
- );
+ info!("will start sidecar: {}", !use_dev_mode && has_files);
// if non dev mode and previously started sidecar, start sidecar
if !use_dev_mode && has_files {
@@ -1087,7 +1088,7 @@ async fn main() {
// Add this to shut down the server
if let Some(server_shutdown_tx) = app_handle.try_state::<mpsc::Sender<()>>() {
- let _ = server_shutdown_tx.send(());
+ drop(server_shutdown_tx.send(()));
}
}
tauri::RunEvent::WindowEvent {
@@ -1107,7 +1108,7 @@ async fn main() {
..
} => {
if !has_visible_windows {
- show_main_window(&app_handle, false);
+ show_main_window(app_handle, false);
}
}
_ => {}
diff --git a/screenpipe-app-tauri/src-tauri/src/permissions.rs b/screenpipe-app-tauri/src-tauri/src/permissions.rs
index efe72cd17..72b1256a2 100644
--- a/screenpipe-app-tauri/src-tauri/src/permissions.rs
+++ b/screenpipe-app-tauri/src-tauri/src/permissions.rs
@@ -24,31 +24,27 @@ pub fn open_permission_settings(permission: OSPermission) {
use std::process::Command;
match permission {
- OSPermission::ScreenRecording => {
- Command::new("open")
- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
- .spawn()
- .expect("Failed to open Screen Recording settings");
- }
- OSPermission::Camera => {
- Command::new("open")
- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")
- .spawn()
- .expect("Failed to open Camera settings");
- }
- OSPermission::Microphone => {
- Command::new("open")
- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
- .spawn()
- .expect("Failed to open Microphone settings");
- }
- OSPermission::Accessibility => {
- Command::new("open")
- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
- .spawn()
- .expect("Failed to open Accessibility settings");
- }
- }
+ OSPermission::ScreenRecording => Command::new("open")
+ .arg(
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
+ )
+ .spawn()
+ .expect("Failed to open Screen Recording settings"),
+ OSPermission::Camera => Command::new("open")
+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")
+ .spawn()
+ .expect("Failed to open Camera settings"),
+ OSPermission::Microphone => Command::new("open")
+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")
+ .spawn()
+ .expect("Failed to open Microphone settings"),
+ OSPermission::Accessibility => Command::new("open")
+ .arg(
+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
+ )
+ .spawn()
+ .expect("Failed to open Accessibility settings"),
+ };
}
}
@@ -97,10 +93,7 @@ pub enum OSPermissionStatus {
impl OSPermissionStatus {
pub fn permitted(&self) -> bool {
- match self {
- Self::NotNeeded | Self::Granted => true,
- _ => false,
- }
+ matches!(self, Self::NotNeeded | Self::Granted)
}
}
diff --git a/screenpipe-app-tauri/src-tauri/src/sidecar.rs b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
index e2f54b0f6..9024645f4 100644
--- a/screenpipe-app-tauri/src-tauri/src/sidecar.rs
+++ b/screenpipe-app-tauri/src-tauri/src/sidecar.rs
@@ -367,7 +367,7 @@ fn spawn_sidecar(app: &tauri::AppHandle) -> Result<CommandChild, String> {
args.push("--enable-ui-monitoring");
}
- if data_dir != "default" && data_dir != "" {
+ if data_dir != "default" && !data_dir.is_empty() {
args.push("--data-dir");
args.push(data_dir.as_str());
}
diff --git a/screenpipe-app-tauri/src-tauri/src/store.rs b/screenpipe-app-tauri/src-tauri/src/store.rs
index 4139dcf34..fdccd6617 100644
--- a/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -2,8 +2,7 @@ use super::get_base_dir;
use std::sync::Arc;
use tauri::AppHandle;
use tauri_plugin_store::StoreBuilder;
-use tracing::{info};
-
+use tracing::info;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProfilesConfig {
@@ -59,8 +58,7 @@ pub fn get_store(
};
// Build and return the store wrapped in Arc
- Ok(StoreBuilder::new(app, store_path)
+ StoreBuilder::new(app, store_path)
.build()
- .map_err(|e| anyhow::anyhow!(e))?)
+ .map_err(|e| anyhow::anyhow!(e))
}
-
diff --git a/screenpipe-audio/src/audio_processing.rs b/screenpipe-audio/src/audio_processing.rs
index 4a55be50c..5f243033e 100644
--- a/screenpipe-audio/src/audio_processing.rs
+++ b/screenpipe-audio/src/audio_processing.rs
@@ -156,7 +156,7 @@ pub fn write_audio_to_file(
bytemuck::cast_slice(audio),
sample_rate,
1,
- &file_path.into(),
+ &PathBuf::from(file_path),
)?;
}
Ok(file_path_clone)
diff --git a/screenpipe-audio/src/core.rs b/screenpipe-audio/src/core.rs
index 02059d3ef..1d33ac988 100644
--- a/screenpipe-audio/src/core.rs
+++ b/screenpipe-audio/src/core.rs
@@ -23,11 +23,12 @@ lazy_static! {
);
}
-#[derive(Clone, Debug, PartialEq)]
+#[derive(Clone, Debug, PartialEq, Default)]
pub enum AudioTranscriptionEngine {
Deepgram,
WhisperTiny,
WhisperDistilLargeV3,
+ #[default]
WhisperLargeV3Turbo,
WhisperLargeV3,
}
@@ -44,12 +45,6 @@ impl fmt::Display for AudioTranscriptionEngine {
}
}
-impl Default for AudioTranscriptionEngine {
- fn default() -> Self {
- AudioTranscriptionEngine::WhisperLargeV3Turbo
- }
-}
-
#[derive(Clone, Debug)]
pub struct DeviceControl {
pub is_running: bool,
@@ -400,7 +395,7 @@ pub fn default_output_device() -> Result<AudioDevice> {
let device = host
.default_output_device()
.ok_or_else(|| anyhow!("No default output device found"))?;
- return Ok(AudioDevice::new(device.name()?, DeviceType::Output));
+ Ok(AudioDevice::new(device.name()?, DeviceType::Output))
}
#[cfg(not(target_os = "macos"))]
diff --git a/screenpipe-audio/src/encode.rs b/screenpipe-audio/src/encode.rs
index 67e73cdf3..6e397f9b7 100644
--- a/screenpipe-audio/src/encode.rs
+++ b/screenpipe-audio/src/encode.rs
@@ -1,7 +1,7 @@
use screenpipe_core::find_ffmpeg_path;
use std::io::Write;
use std::{
- path::PathBuf,
+ path::Path,
process::{Command, Stdio},
};
use tracing::{debug, error};
@@ -10,7 +10,7 @@ pub fn encode_single_audio(
data: &[u8],
sample_rate: u32,
channels: u16,
- output_path: &PathBuf,
+ output_path: &Path,
) -> anyhow::Result<()> {
debug!("Starting FFmpeg process");
diff --git a/screenpipe-audio/src/stt.rs b/screenpipe-audio/src/stt.rs
index 0a6712382..077e5bfd2 100644
--- a/screenpipe-audio/src/stt.rs
+++ b/screenpipe-audio/src/stt.rs
@@ -2,7 +2,6 @@ use crate::audio_processing::write_audio_to_file;
use crate::deepgram::transcribe_with_deepgram;
use crate::pyannote::models::{get_or_download_model, PyannoteModel};
use crate::pyannote::segment::SpeechSegment;
-use crate::{resample, DeviceControl};
pub use crate::segments::prepare_segments;
use crate::{
pyannote::{embedding::EmbeddingExtractor, identify::EmbeddingManager},
@@ -10,21 +9,22 @@ use crate::{
whisper::{process_with_whisper, WhisperModel},
AudioDevice, AudioTranscriptionEngine,
};
+use crate::{resample, DeviceControl};
use anyhow::{anyhow, Result};
use candle_transformers::models::whisper as m;
+use dashmap::DashMap;
use log::{debug, error, info};
#[cfg(target_os = "macos")]
use objc::rc::autoreleasepool;
use screenpipe_core::Language;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{
- path::PathBuf,
+ path::Path,
sync::Arc,
sync::Mutex as StdMutex,
time::{SystemTime, UNIX_EPOCH},
};
use tokio::sync::Mutex;
-use dashmap::DashMap;
pub fn stt_sync(
audio: &[f32],
@@ -153,7 +153,7 @@ pub async fn create_whisper_channel(
audio_transcription_engine: Arc<AudioTranscriptionEngine>,
vad_engine: VadEngineEnum,
deepgram_api_key: Option<String>,
- output_path: &PathBuf,
+ output_path: &Path,
vad_sensitivity: VadSensitivity,
languages: Vec<Language>,
audio_devices_control: Option<Arc<DashMap<AudioDevice, DeviceControl>>>,
@@ -179,7 +179,7 @@ pub async fn create_whisper_channel(
let vad_engine = Arc::new(Mutex::new(vad_engine));
let shutdown_flag = Arc::new(AtomicBool::new(false));
let shutdown_flag_clone = shutdown_flag.clone();
- let output_path = output_path.clone();
+ let output_path = output_path.to_path_buf();
let embedding_model_path = get_or_download_model(PyannoteModel::Embedding).await?;
let segmentation_model_path = get_or_download_model(PyannoteModel::Segmentation).await?;
diff --git a/screenpipe-audio/src/vad_engine.rs b/screenpipe-audio/src/vad_engine.rs
index 8b3251db8..0b774dd9b 100644
--- a/screenpipe-audio/src/vad_engine.rs
+++ b/screenpipe-audio/src/vad_engine.rs
@@ -9,9 +9,10 @@ use tokio::sync::Mutex;
use tracing::info;
use vad_rs::{Vad, VadStatus};
-#[derive(Clone, Copy, Debug)]
+#[derive(Clone, Copy, Debug, Default)]
pub enum VadSensitivity {
Low,
+ #[default]
Medium,
High,
}
@@ -38,6 +39,7 @@ pub trait VadEngine: Send {
fn get_min_speech_ratio(&self) -> f32;
}
+#[derive(Default)]
pub struct WebRtcVad {
vad: webrtc_vad::Vad,
sensitivity: VadSensitivity,
diff --git a/screenpipe-audio/tests/core_tests.rs b/screenpipe-audio/tests/core_tests.rs
index 765e6a62d..ac698fefb 100644
--- a/screenpipe-audio/tests/core_tests.rs
+++ b/screenpipe-audio/tests/core_tests.rs
@@ -14,7 +14,7 @@ mod tests {
};
use screenpipe_audio::{parse_audio_device, record_and_transcribe};
use screenpipe_core::Language;
- use std::path::PathBuf;
+ use std::path::{Path, PathBuf};
use std::process::Command;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -172,7 +172,7 @@ mod tests {
}
// Helper function to get audio duration (you'll need to implement this)
- fn get_audio_duration(path: &PathBuf) -> Result<Duration, Box<dyn std::error::Error>> {
+ fn get_audio_duration(path: &Path) -> Result<Duration, Box<dyn std::error::Error>> {
let output = Command::new("ffprobe")
.args([
"-v",
diff --git a/screenpipe-core/src/google.rs b/screenpipe-core/src/google.rs
index 078d074b6..5c75dff4d 100644
--- a/screenpipe-core/src/google.rs
+++ b/screenpipe-core/src/google.rs
@@ -1,3 +1,4 @@
+#![allow(clippy::all, dead_code, unused_variables, unused_mut)]
mod google_module {
use anyhow::{Error as E, Result};
diff --git a/screenpipe-core/src/llama.rs b/screenpipe-core/src/llama.rs
index b7e5e0ae0..cfcba0911 100644
--- a/screenpipe-core/src/llama.rs
+++ b/screenpipe-core/src/llama.rs
@@ -287,7 +287,7 @@ mod llm_module {
completion_tokens: token_generated,
total_tokens: token_generated,
completion_tokens_details: serde_json::Value::Null,
- tokens_per_second: tokens_per_second,
+ tokens_per_second,
},
})
}
diff --git a/screenpipe-core/src/mistral.rs b/screenpipe-core/src/mistral.rs
index 501f34fe1..683e1d222 100644
--- a/screenpipe-core/src/mistral.rs
+++ b/screenpipe-core/src/mistral.rs
@@ -1,3 +1,4 @@
+#![allow(clippy::all, dead_code, unused_variables, unused_mut)]
#[cfg(feature = "llm")]
mod llm_module {
diff --git a/screenpipe-core/src/network.rs b/screenpipe-core/src/network.rs
index 0a4718d8f..e2cba530f 100644
--- a/screenpipe-core/src/network.rs
+++ b/screenpipe-core/src/network.rs
@@ -52,7 +52,7 @@ mod tests {
let port = pick_unused_port();
assert!(port.is_some());
let port = port.unwrap();
- assert!(port >= 15000 && port < 65535);
+ assert!((15000..65535).contains(&port));
assert!(is_port_available(port));
}
}
diff --git a/screenpipe-core/src/phi.rs b/screenpipe-core/src/phi.rs
index 9d7d1bab1..463296801 100755
--- a/screenpipe-core/src/phi.rs
+++ b/screenpipe-core/src/phi.rs
@@ -66,6 +66,7 @@ mod llm_module {
Ok((model, tokenizer))
}
+ #[allow(clippy::too_many_arguments)]
pub fn generate_text_streaming<F>(
model: &mut Phi3,
tokenizer: &Tokenizer,
@@ -93,8 +94,7 @@ mod llm_module {
None => anyhow::bail!("cannot find the endoftext token"),
};
- let mut pos = 0;
- for _ in 0..max_tokens {
+ for pos in 0..max_tokens {
let context_size = if pos > 0 { 1 } else { tokens.len() };
let ctxt = &tokens[tokens.len().saturating_sub(context_size)..];
let input = Tensor::new(ctxt, device)?.unsqueeze(0)?;
@@ -127,7 +127,6 @@ mod llm_module {
if let Ok(t) = tokenizer.decode(&[next_token], false) {
callback(t)?;
}
- pos += 1;
}
Ok(())
diff --git a/screenpipe-core/src/pipes.rs b/screenpipe-core/src/pipes.rs
index 174e8e182..2605df32f 100644
--- a/screenpipe-core/src/pipes.rs
+++ b/screenpipe-core/src/pipes.rs
@@ -686,7 +686,7 @@ mod pipes {
];
ignore_list.iter().any(|ignored| file_name == *ignored)
- || file_name.to_str().map_or(false, |s| s.starts_with('.'))
+ || file_name.to_str().is_some_and(|s| s.starts_with('.'))
}
fn download_github_folder(
@@ -1077,7 +1077,7 @@ mod pipes {
_ = tokio::time::sleep(duration) => {
debug!("executing cron job for pipe {} at path {}", pipe, path);
match client
- .get(&format!("{}{}", base_url, path))
+ .get(format!("{}{}", base_url, path))
.headers(headers.clone())
.send()
.await
diff --git a/screenpipe-core/tests/pipes_test.rs b/screenpipe-core/tests/pipes_test.rs
index 1023152a2..c3647a11f 100644
--- a/screenpipe-core/tests/pipes_test.rs
+++ b/screenpipe-core/tests/pipes_test.rs
@@ -2,7 +2,6 @@
#[cfg(test)]
mod tests {
use chrono::{TimeZone, Utc};
- use reqwest;
use screenpipe_core::{download_pipe, get_last_cron_execution, run_pipe, save_cron_execution};
use serde_json::json;
use std::sync::Arc;
@@ -50,7 +49,7 @@ mod tests {
let pipe_dir = setup_test_pipe(&temp_dir, "simple_pipe", code).await;
- let result = run_pipe(&pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir).await;
assert!(result.is_ok());
}
@@ -68,7 +67,7 @@ mod tests {
let pipe_dir = setup_test_pipe(&temp_dir, "http_pipe", code).await;
- let result = run_pipe(&pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir).await;
assert!(result.is_ok());
}
@@ -85,7 +84,7 @@ mod tests {
let pipe_dir = setup_test_pipe(&temp_dir, "error_pipe", code).await;
- let result = run_pipe(&pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir).await;
assert!(result.is_err());
}
@@ -104,7 +103,7 @@ mod tests {
let pipe_dir = setup_test_pipe(&temp_dir, "file_pipe", code).await;
- let result = run_pipe(&pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir).await;
assert!(result.is_ok());
// Verify that the file was created and contains the expected content
@@ -224,16 +223,12 @@ mod tests {
let pipe_dir = setup_test_pipe(&temp_dir, "email_test_pipe_plain", &plain_text_code).await;
std::env::set_current_dir(&pipe_dir).unwrap();
- let result = run_pipe(
- &pipe_dir.to_string_lossy().to_string(),
- screenpipe_dir.clone(),
- )
- .await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir.clone()).await;
assert!(result.is_ok(), "Plain text email test failed: {:?}", result);
let pipe_dir = setup_test_pipe(&temp_dir, "email_test_pipe_html", &html_code).await;
std::env::set_current_dir(&pipe_dir).unwrap();
- let result = run_pipe(&pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir).await;
assert!(result.is_ok(), "HTML email test failed: {:?}", result);
}
@@ -284,7 +279,7 @@ mod tests {
// Change the working directory to the pipe directory
std::env::set_current_dir(&pipe_dir).unwrap();
- let result = run_pipe(&pipe_dir.to_string_lossy().to_string(), screenpipe_dir).await;
+ let result = run_pipe(&pipe_dir.to_string_lossy(), screenpipe_dir).await;
assert!(result.is_ok(), "Pipe execution failed: {:?}", result);
// Additional checks
@@ -437,7 +432,7 @@ mod tests {
for _ in 0..12 {
// Advance time by 5 minutes
let mut now = mock_now.lock().await;
- *now = *now + chrono::Duration::minutes(5);
+ *now += chrono::Duration::minutes(5);
// Record the request
requests.lock().await.push(*now);
@@ -495,7 +490,7 @@ mod tests {
.unwrap()
.as_secs();
assert!(
- time_diff >= 300 && time_diff <= 301,
+ (300..=301).contains(&time_diff),
"Unexpected time difference: {}",
time_diff
);
diff --git a/screenpipe-integrations/src/unstructured_ocr.rs b/screenpipe-integrations/src/unstructured_ocr.rs
index af960efd2..d67b4bdee 100644
--- a/screenpipe-integrations/src/unstructured_ocr.rs
+++ b/screenpipe-integrations/src/unstructured_ocr.rs
@@ -55,7 +55,7 @@ pub async fn perform_ocr_cloud(
TESSERACT_LANGUAGES
.iter()
.filter_map(|(key, val)| {
- if let Some(_) = languages.iter().find(|l| l == &val) {
+ if languages.iter().any(|l| l == val) {
Some(key.to_string())
} else {
None
@@ -104,7 +104,7 @@ pub async fn perform_ocr_cloud(
Ok((text, json_output, Some(overall_confidence)))
}
-fn calculate_overall_confidence(parsed_response: &Vec<HashMap<String, serde_json::Value>>) -> f64 {
+fn calculate_overall_confidence(parsed_response: &[HashMap<String, serde_json::Value>]) -> f64 {
let confidence_sum: f64 = parsed_response
.iter()
.filter_map(|item| item.get("confidence").and_then(|v| v.as_f64()))
@@ -152,11 +152,9 @@ pub async fn unstructured_chunking(text: &str) -> Result<Vec<String>> {
.essence_str()
.to_owned();
- let part = Part::bytes(bytes)
+ Part::bytes(bytes)
.file_name(file_name)
- .mime_str(&mime_type)?;
-
- part
+ .mime_str(&mime_type)?
})
.text("chunking_strategy", "by_similarity")
.text("similarity_threshold", "0.5")
diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-server/benches/db_benchmarks.rs
index fe223df8b..9c7d391d3 100644
--- a/screenpipe-server/benches/db_benchmarks.rs
+++ b/screenpipe-server/benches/db_benchmarks.rs
@@ -85,6 +85,7 @@ fn bench_search(c: &mut Criterion) {
None,
None,
None,
+ None,
)
.await
.unwrap()
diff --git a/screenpipe-server/src/add.rs b/screenpipe-server/src/add.rs
index 4e8838ae3..3a15ca795 100644
--- a/screenpipe-server/src/add.rs
+++ b/screenpipe-server/src/add.rs
@@ -29,6 +29,7 @@ use crate::{
DatabaseManager,
};
+#[allow(clippy::too_many_arguments)]
pub async fn handle_index_command(
screenpipe_dir: PathBuf,
path: String,
@@ -82,11 +83,8 @@ pub async fn handle_index_command(
// Setup channel for OCR results
// At the start of handle_index_command, if JSON output is selected, print the stream start
- match output_format {
- crate::cli::OutputFormat::Json => {
- println!("{{\"version\":1,\"stream\":["); // Start of JSON stream
- }
- _ => {}
+ if output_format == crate::cli::OutputFormat::Json {
+ println!("{{\"version\":1,\"stream\":["); // Start of JSON stream
}
for video_path in video_files {
@@ -148,7 +146,7 @@ pub async fn handle_index_command(
for (idx, frame) in frames.iter().enumerate() {
// Compare with previous frame to skip similar ones
let current_average = if let Some(prev) = &previous_image {
- compare_with_previous_image(Some(prev), &frame, &mut None, idx as u64, &mut 0.0)
+ compare_with_previous_image(Some(prev), frame, &mut None, idx as u64, &mut 0.0)
.await?
} else {
1.0
@@ -185,7 +183,7 @@ pub async fn handle_index_command(
// Do OCR processing directly
let (text, _, confidence): (String, String, Option<f64>) = match engine.clone() {
#[cfg(target_os = "macos")]
- OcrEngine::AppleNative => perform_ocr_apple(&frame, &[]),
+ OcrEngine::AppleNative => perform_ocr_apple(frame, &[]),
#[cfg(target_os = "windows")]
OcrEngine::WindowsNative => perform_ocr_windows(&frame).await.unwrap(),
_ => {
@@ -306,7 +304,7 @@ pub async fn handle_index_command(
fn find_video_files(root: &str, pattern: Option<&str>) -> Result<Vec<PathBuf>> {
let mut video_files = Vec::new();
- let regex = pattern.map(|p| Regex::new(p)).transpose()?;
+ let regex = pattern.map(Regex::new).transpose()?;
for entry in WalkDir::new(root)
.follow_links(true)
diff --git a/screenpipe-server/src/auto_destruct.rs b/screenpipe-server/src/auto_destruct.rs
index 553f9c82b..0ac856264 100644
--- a/screenpipe-server/src/auto_destruct.rs
+++ b/screenpipe-server/src/auto_destruct.rs
@@ -77,7 +77,7 @@ pub async fn watch_pid(pid: u32) -> bool {
#[cfg(not(target_os = "windows"))]
{
let output = Command::new("ps")
- .args(&["-p", &pid.to_string()])
+ .args(["-p", &pid.to_string()])
.output()
.expect("failed to execute process check command");
diff --git a/screenpipe-server/src/bin/screenpipe-server.rs b/screenpipe-server/src/bin/screenpipe-server.rs
index c65ebcf84..b60c55b6a 100644
--- a/screenpipe-server/src/bin/screenpipe-server.rs
+++ b/screenpipe-server/src/bin/screenpipe-server.rs
@@ -20,7 +20,6 @@ use screenpipe_server::{
use screenpipe_vision::monitor::list_monitors;
#[cfg(target_os = "macos")]
use screenpipe_vision::run_ui;
-use sentry;
use serde_json::{json, Value};
use std::{
collections::HashMap,
@@ -261,7 +260,7 @@ async fn main() -> anyhow::Result<()> {
Err(e) => {
warn!("ffmpeg check failed: {}", e);
warn!("please ensure ffmpeg is installed correctly and is in your PATH");
- return Err(e.into());
+ return Err(e);
}
}
@@ -585,7 +584,7 @@ async fn main() -> anyhow::Result<()> {
debug!("LLM initializing");
#[cfg(feature = "llm")]
- let llm = {
+ let _llm = {
match cli.enable_llm {
true => Some(screenpipe_core::LLM::new(
screenpipe_core::ModelName::Llama,
@@ -644,7 +643,7 @@ async fn main() -> anyhow::Result<()> {
) -> anyhow::Result<()> {
match list_audio_devices().await {
Ok(available_devices) => {
- if !available_devices.contains(&device) {
+ if !available_devices.contains(device) {
return Err(anyhow::anyhow!(
"attempted to control non-existent device: {}",
device.name
@@ -1061,7 +1060,7 @@ async fn handle_pipe_command(
PipeCommand::List { output, port } => {
let server_url = format!("{}:{}", server_url, port);
let pipes = match client
- .get(&format!("{}/pipes/list", server_url))
+ .get(format!("{}/pipes/list", server_url))
.send()
.await
{
@@ -1107,7 +1106,7 @@ async fn handle_pipe_command(
PipeCommand::Download { url, output, port }
| PipeCommand::Install { url, output, port } => {
match client
- .post(&format!("{}:{}/pipes/download", server_url, port))
+ .post(format!("{}:{}/pipes/download", server_url, port))
.json(&json!({ "url": url }))
.send()
.await
@@ -1157,7 +1156,7 @@ async fn handle_pipe_command(
PipeCommand::Info { id, output, port } => {
let info = match client
- .get(&format!("{}:{}/pipes/info/{}", server_url, port, id))
+ .get(format!("{}:{}/pipes/info/{}", server_url, port, id))
.send()
.await
{
@@ -1178,7 +1177,7 @@ async fn handle_pipe_command(
}
PipeCommand::Enable { id, port } => {
match client
- .post(&format!("{}:{}/pipes/enable", server_url, port))
+ .post(format!("{}:{}/pipes/enable", server_url, port))
.json(&json!({ "pipe_id": id }))
.send()
.await
@@ -1197,7 +1196,7 @@ async fn handle_pipe_command(
PipeCommand::Disable { id, port } => {
match client
- .post(&format!("{}:{}/pipes/disable", server_url, port))
+ .post(format!("{}:{}/pipes/disable", server_url, port))
.json(&json!({ "pipe_id": id }))
.send()
.await
@@ -1219,7 +1218,7 @@ async fn handle_pipe_command(
.map_err(|e| anyhow::anyhow!("invalid json: {}", e))?;
match client
- .post(&format!("{}:{}/pipes/update", server_url, port))
+ .post(format!("{}:{}/pipes/update", server_url, port))
.json(&json!({
"pipe_id": id,
"config": config
@@ -1250,7 +1249,7 @@ async fn handle_pipe_command(
}
match client
- .delete(&format!("{}:{}/pipes/delete/{}", server_url, port, id))
+ .delete(format!("{}:{}/pipes/delete/{}", server_url, port, id))
.send()
.await
{
@@ -1277,7 +1276,7 @@ async fn handle_pipe_command(
}
match client
- .post(&format!("{}:{}/pipes/purge", server_url, port))
+ .post(format!("{}:{}/pipes/purge", server_url, port))
.send()
.await
{
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index 7cb4d5bee..60f71c50c 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -80,9 +80,7 @@ impl DatabaseManager {
let db_manager = DatabaseManager { pool };
// Run migrations after establishing the connection
- if let Err(e) = Self::run_migrations(&db_manager.pool).await {
- return Err(e);
- }
+ Self::run_migrations(&db_manager.pool).await?;
Ok(db_manager)
}
@@ -124,6 +122,7 @@ impl DatabaseManager {
Ok(id)
}
+ #[allow(clippy::too_many_arguments)]
pub async fn insert_audio_transcription(
&self,
audio_chunk_id: i64,
@@ -343,6 +342,7 @@ impl DatabaseManager {
Ok(id)
}
+ #[allow(clippy::too_many_arguments)]
pub async fn insert_ocr_text(
&self,
frame_id: i64,
@@ -408,6 +408,7 @@ impl DatabaseManager {
Err(sqlx::Error::PoolTimedOut)
}
+ #[allow(clippy::too_many_arguments)]
async fn insert_ocr_text_old(
&self,
frame_id: i64,
@@ -451,6 +452,7 @@ impl DatabaseManager {
Ok(())
}
+ #[allow(clippy::too_many_arguments)]
pub async fn search(
&self,
query: &str,
@@ -705,6 +707,7 @@ impl DatabaseManager {
Ok(results)
}
+ #[allow(clippy::too_many_arguments)]
async fn search_ocr(
&self,
query: &str,
@@ -800,6 +803,7 @@ impl DatabaseManager {
.collect())
}
+ #[allow(clippy::too_many_arguments)]
pub async fn search_audio(
&self,
query: &str,
@@ -1463,6 +1467,7 @@ impl DatabaseManager {
})
}
+ #[allow(clippy::too_many_arguments)]
pub async fn search_ui_monitoring(
&self,
query: &str,
diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rs
index 064361df8..42d095e56 100644
--- a/screenpipe-server/src/db_types.rs
+++ b/screenpipe-server/src/db_types.rs
@@ -3,7 +3,7 @@ use screenpipe_audio::DeviceType;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use std::error::Error as StdError;
-use std::fmt;
+use std::fmt::{self, Display};
#[derive(Debug)]
pub struct DatabaseError(pub String);
@@ -173,11 +173,11 @@ pub enum ContentSource {
Audio,
}
-impl ToString for ContentSource {
- fn to_string(&self) -> String {
+impl Display for ContentSource {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
- ContentSource::Screen => "screen".to_string(),
- ContentSource::Audio => "audio".to_string(),
+ ContentSource::Screen => write!(f, "screen"),
+ ContentSource::Audio => write!(f, "audio"),
}
}
}
diff --git a/screenpipe-server/src/highlight.rs b/screenpipe-server/src/highlight.rs
index c2c290861..e5743ce59 100644
--- a/screenpipe-server/src/highlight.rs
+++ b/screenpipe-server/src/highlight.rs
@@ -1,6 +1,4 @@
-use std::{
- borrow::Cow, error::Error,sync::Arc, time::Duration
-};
+use std::{borrow::Cow, error::Error, sync::Arc, time::Duration};
pub use opentelemetry::trace::Span as SpanTrait;
use opentelemetry::{
@@ -8,9 +6,7 @@ use opentelemetry::{
trace::{Status, TraceContextExt, Tracer as _},
KeyValue,
};
-use opentelemetry_otlp::{
- OtlpTracePipeline, SpanExporterBuilder, WithExportConfig,
-};
+use opentelemetry_otlp::{OtlpTracePipeline, SpanExporterBuilder, WithExportConfig};
use opentelemetry_sdk::{
propagation::TraceContextPropagator,
resource::Resource,
@@ -37,19 +33,17 @@ pub enum HighlightError {
Trace(TraceError),
}
-
-
impl From<TraceError> for HighlightError {
fn from(value: TraceError) -> Self {
HighlightError::Trace(value)
}
}
-
pub mod otel {
pub use opentelemetry::KeyValue;
}
+#[derive(Default)]
pub struct HighlightConfig {
/// Your highlight.io Project ID
pub project_id: String,
@@ -59,17 +53,6 @@ pub struct HighlightConfig {
/// The version of your app. We recommend setting this to the most recent deploy SHA of your app.
pub service_version: Option<String>,
-
-}
-
-impl Default for HighlightConfig {
- fn default() -> Self {
- Self {
- project_id: Default::default(),
- service_name: Default::default(),
- service_version: Default::default(),
- }
- }
}
struct HighlightInner {
@@ -84,9 +67,7 @@ impl Highlight {
fn install_pipelines(
tracing: OtlpTracePipeline<SpanExporterBuilder>,
) -> Result<Tracer, HighlightError> {
- Ok(
- tracing.install_batch(opentelemetry_sdk::runtime::Tokio)?,
- )
+ Ok(tracing.install_batch(opentelemetry_sdk::runtime::Tokio)?)
}
fn get_default_resource(config: &HighlightConfig) -> Resource {
@@ -107,9 +88,7 @@ impl Highlight {
Resource::new(attrs)
}
- fn make_install_pipelines(
- config: &HighlightConfig,
- ) -> Result<Tracer, HighlightError> {
+ fn make_install_pipelines(config: &HighlightConfig) -> Result<Tracer, HighlightError> {
let tracing = opentelemetry_otlp::new_pipeline()
.tracing()
.with_trace_config(
@@ -142,14 +121,10 @@ impl Highlight {
global::set_text_map_propagator(TraceContextPropagator::new());
let tracer = Self::make_install_pipelines(&config)?;
- let h = Highlight(Arc::new(HighlightInner {
- config,
- tracer,
- }));
+ let h = Highlight(Arc::new(HighlightInner { config, tracer }));
Ok(h)
}
-
/// Capture an error with session info
///
@@ -181,10 +156,7 @@ impl Highlight {
///
/// Explicitly captures any type with trait Error and sends it to Highlight.
pub fn capture_error(&self, err: &str) {
- let e = std::io::Error::new(
- std::io::ErrorKind::Other,
- err
- );
+ let e = std::io::Error::new(std::io::ErrorKind::Other, err);
self.capture_error_with_session(&e, None, None);
}
@@ -207,4 +179,3 @@ impl Highlight {
global::shutdown_tracer_provider();
}
}
-
diff --git a/screenpipe-server/src/pipe_manager.rs b/screenpipe-server/src/pipe_manager.rs
index 330c0bf70..90d59897a 100644
--- a/screenpipe-server/src/pipe_manager.rs
+++ b/screenpipe-server/src/pipe_manager.rs
@@ -146,7 +146,7 @@ impl PipeManager {
let config = tokio::fs::read_to_string(&config_path)
.await
.and_then(|s| serde_json::from_str::<Value>(&s).map_err(Into::into))
- .unwrap_or_else(|_| Value::Null);
+ .unwrap_or(Value::Null);
PipeInfo {
id: pipe_id,
diff --git a/screenpipe-server/src/resource_monitor.rs b/screenpipe-server/src/resource_monitor.rs
index f68d79d67..e9672c1a7 100644
--- a/screenpipe-server/src/resource_monitor.rs
+++ b/screenpipe-server/src/resource_monitor.rs
@@ -64,7 +64,7 @@ impl ResourceMonitor {
total_cpu += process.cpu_usage();
// Iterate through all processes to find children
- for (_child_pid, child_process) in sys.processes() {
+ for child_process in sys.processes().values() {
if child_process.parent() == Some(sysinfo::Pid::from_u32(pid)) {
total_memory += child_process.memory() as f64;
total_cpu += child_process.cpu_usage();
@@ -161,7 +161,7 @@ impl ResourceMonitor {
#[cfg(target_os = "macos")]
fn get_npu_usage(&self) -> Option<f32> {
let output = Command::new("ioreg")
- .args(&["-r", "-c", "AppleARMIODevice", "-n", "ane0"])
+ .args(["-r", "-c", "AppleARMIODevice", "-n", "ane0"])
.output()
.ok()?;
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index 0bd9e521f..42f0ed419 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -1160,7 +1160,7 @@ pub(crate) async fn add_to_database(
let output_dir = state.screenpipe_dir.join("data");
let time = Utc::now();
let formatted_time = time.format("%Y-%m-%d_%H-%M-%S").to_string();
- let video_file_path = PathBuf::from(output_dir)
+ let video_file_path = output_dir
.join(format!("{}_{}.mp4", device_name, formatted_time))
.to_str()
.expect("Failed to create valid path")
@@ -1816,7 +1816,10 @@ async fn semantic_search_handler(
let limit = query.limit.unwrap_or(10);
let threshold = query.threshold.unwrap_or(0.3);
- debug!("semantic search for '{}' with limit {} and threshold {}", query.text, limit, threshold);
+ debug!(
+ "semantic search for '{}' with limit {} and threshold {}",
+ query.text, limit, threshold
+ );
// Generate embedding for search text
let embedding = match generate_embedding(&query.text, 0).await {
@@ -1831,7 +1834,11 @@ async fn semantic_search_handler(
};
// Search database for similar embeddings
- match state.db.search_similar_embeddings(embedding, limit, threshold).await {
+ match state
+ .db
+ .search_similar_embeddings(embedding, limit, threshold)
+ .await
+ {
Ok(results) => {
debug!("found {} similar results", results.len());
Ok(JsonResponse(results))
@@ -1928,7 +1935,7 @@ async fn stream_frames_handler(
};
// Calculate duration in minutes between start and end time
- let duration_minutes = (request.end_time - request.start_time).num_minutes().max(1) as i64;
+ let duration_minutes = (request.end_time - request.start_time).num_minutes().max(1);
// Calculate center timestamp
let center_timestamp = request.start_time + (request.end_time - request.start_time) / 2;
@@ -2244,4 +2251,3 @@ MERGED_VIDEO_PATH=$(echo "$MERGE_RESPONSE" | jq -r '.video_path')
echo "Merged Video Path: $MERGED_VIDEO_PATH"
*/
-
diff --git a/screenpipe-server/src/video.rs b/screenpipe-server/src/video.rs
index ab61fb7f9..24fe68e54 100644
--- a/screenpipe-server/src/video.rs
+++ b/screenpipe-server/src/video.rs
@@ -28,6 +28,7 @@ pub struct VideoCapture {
}
impl VideoCapture {
+ #[allow(clippy::too_many_arguments)]
pub fn new(
output_path: &str,
fps: f64,
diff --git a/screenpipe-server/src/video_cache.rs b/screenpipe-server/src/video_cache.rs
index 963fff297..7b127c3fd 100644
--- a/screenpipe-server/src/video_cache.rs
+++ b/screenpipe-server/src/video_cache.rs
@@ -65,6 +65,9 @@ pub struct FrameMetadata {
pub ocr_text: String,
}
+type GetFrameResponse =
+ oneshot::Sender<Result<Option<(Vec<u8>, FrameMetadata, (DateTime<Utc>, String))>>>;
+
#[derive(Debug)]
enum CacheMessage {
Store {
@@ -76,8 +79,7 @@ enum CacheMessage {
},
Get {
cache_key: String,
- response:
- oneshot::Sender<Result<Option<(Vec<u8>, FrameMetadata, (DateTime<Utc>, String))>>>,
+ response: GetFrameResponse,
},
}
@@ -218,7 +220,7 @@ impl FrameDiskCache {
let timestamp = parse_timestamp(timestamp_str)?;
- let frame_path = self.get_frame_path(&timestamp.into(), device_id);
+ let frame_path = self.get_frame_path(&timestamp, device_id);
if let Some(parent) = frame_path.parent() {
fs::create_dir_all(parent).await?;
@@ -229,7 +231,7 @@ impl FrameDiskCache {
let checksum = format!("{:x}", hasher.finalize());
let cached_frame = CachedFrame {
- timestamp: timestamp.into(),
+ timestamp,
device_id: device_id.to_string(),
checksum,
metadata: FrameMetadata {
@@ -255,7 +257,7 @@ impl FrameDiskCache {
fs::write(&frame_path, frame_data).await?;
self.entries.insert(
- (timestamp.into(), device_id.to_string()),
+ (timestamp, device_id.to_string()),
CacheEntry {
frame: cached_frame,
path: frame_path,
@@ -289,7 +291,7 @@ impl FrameDiskCache {
};
// First check if we have the entry before reading the file
- if let Some(entry) = self.entries.get(&(timestamp.into(), device_id.to_string())) {
+ if let Some(entry) = self.entries.get(&(timestamp, device_id.to_string())) {
let frame_path = &entry.path;
// Only verify checksum periodically (e.g., every 100th access) or if file size changed
@@ -316,7 +318,7 @@ impl FrameDiskCache {
Ok(Some((
frame_data,
entry.frame.metadata.clone(),
- (timestamp.into(), device_id.to_string()),
+ (timestamp, device_id.to_string()),
)))
} else {
// Fast path - skip checksum verification
@@ -324,7 +326,7 @@ impl FrameDiskCache {
Ok(Some((
frame_data,
entry.frame.metadata.clone(),
- (timestamp.into(), device_id.to_string()),
+ (timestamp, device_id.to_string()),
)))
}
} else {
@@ -353,7 +355,7 @@ impl FrameDiskCache {
let mut frames_to_remove = Vec::new();
// Identify frames to remove based on age and total size
- for (&(timestamp, ref device_id), _entry) in &self.entries {
+ for &(timestamp, ref device_id) in self.entries.keys() {
if timestamp < retention_cutoff {
frames_to_remove.push((timestamp, device_id.clone()));
continue;
@@ -567,8 +569,7 @@ impl FrameCache {
let (extract_tx, mut extract_rx) = mpsc::channel(100);
- let mut streamer =
- OrderedFrameStreamer::new(frame_tx, Duration::seconds(60 * 1), descending);
+ let mut streamer = OrderedFrameStreamer::new(frame_tx, Duration::seconds(60), descending);
// Spawn extraction task
let mut extraction_handle = {
@@ -671,7 +672,7 @@ async fn extract_frame(
.iter()
.filter_map(|(frame, _)| {
// Only select frames that align with our target FPS
- if frame.offset_index as i64 % frame_interval == 0 {
+ if frame.offset_index % frame_interval == 0 {
Some(frame.offset_index.to_string())
} else {
None
@@ -814,8 +815,8 @@ async fn is_video_file_complete(ffmpeg_path: &PathBuf, file_path: &str) -> Resul
}
}
- match Command::new(&ffmpeg_path)
- .args(&["-v", "error", "-i", file_path, "-f", "null", "-"])
+ match Command::new(ffmpeg_path)
+ .args(["-v", "error", "-i", file_path, "-f", "null", "-"])
.output()
.await
{
diff --git a/screenpipe-server/src/video_utils.rs b/screenpipe-server/src/video_utils.rs
index a8a7eef68..fddeb0ab8 100644
--- a/screenpipe-server/src/video_utils.rs
+++ b/screenpipe-server/src/video_utils.rs
@@ -47,7 +47,7 @@ pub async fn extract_frame(file_path: &str, offset_index: i64) -> Result<String>
let mut command = Command::new(ffmpeg_path);
command
- .args(&[
+ .args([
"-ss",
&offset_str,
"-i",
@@ -111,7 +111,7 @@ pub async fn validate_media(file_path: &str) -> Result<()> {
let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
let status = Command::new(ffmpeg_path)
- .args(&["-v", "error", "-i", file_path, "-f", "null", "-"])
+ .args(["-v", "error", "-i", file_path, "-f", "null", "-"])
.output()
.await?;
@@ -159,7 +159,7 @@ pub async fn merge_videos(
let ffmpeg_path = find_ffmpeg_path().expect("failed to find ffmpeg path");
let status = Command::new(ffmpeg_path)
- .args(&[
+ .args([
"-f",
"concat",
"-safe",
@@ -244,7 +244,7 @@ pub async fn extract_frames_from_video(
// Extract frames using ffmpeg
let status = Command::new(&ffmpeg_path)
- .args(&[
+ .args([
"-i",
video_path.to_str().unwrap(),
"-vf",
@@ -303,7 +303,7 @@ pub async fn extract_frames_from_video(
async fn get_video_fps(ffmpeg_path: &PathBuf, video_path: &str) -> Result<f64> {
let output = Command::new(ffmpeg_path)
- .args(&["-i", video_path])
+ .args(["-i", video_path])
.output()
.await?;
@@ -349,7 +349,7 @@ pub async fn get_video_metadata(video_path: &str) -> Result<VideoMetadata> {
// Try ffprobe first
let creation_time = match Command::new(&ffprobe_path)
- .args(&[
+ .args([
"-v",
"quiet",
"-print_format",
@@ -418,7 +418,7 @@ pub async fn get_video_metadata(video_path: &str) -> Result<VideoMetadata> {
// Helper function to get fps and duration
async fn get_video_technical_metadata(ffprobe_path: &Path, video_path: &str) -> Result<(f64, f64)> {
let output = Command::new(ffprobe_path)
- .args(&[
+ .args([
"-v",
"quiet",
"-print_format",
diff --git a/screenpipe-server/tests/audio_vision_integration_test.rs b/screenpipe-server/tests/audio_vision_integration_test.rs
index 5c12c04bd..688c7f4d6 100644
--- a/screenpipe-server/tests/audio_vision_integration_test.rs
+++ b/screenpipe-server/tests/audio_vision_integration_test.rs
@@ -1,4 +1,3 @@
-use reqwest;
use serde_json::Value;
use std::time::{Duration, Instant};
@@ -56,7 +55,7 @@ async fn test_screen_capture_to_api_delay() {
// Mac M3 max: Time elapsed: 33.516971916s
// Mac M3 max: Time elapsed: 153.62804525s
-
+
// You can add assertions here if needed
// assert!(elapsed_time < Duration::from_secs(30), "Test took too long");
}
diff --git a/screenpipe-server/tests/db.rs b/screenpipe-server/tests/db.rs
index 9a6fc0e54..9e96eae47 100644
--- a/screenpipe-server/tests/db.rs
+++ b/screenpipe-server/tests/db.rs
@@ -11,9 +11,7 @@ mod tests {
use screenpipe_vision::OcrEngine;
async fn setup_test_db() -> DatabaseManager {
- let db = DatabaseManager::new("sqlite::memory:").await.unwrap();
-
- db
+ DatabaseManager::new("sqlite::memory:").await.unwrap()
}
#[tokio::test]
diff --git a/screenpipe-server/tests/endpoint_test.rs b/screenpipe-server/tests/endpoint_test.rs
index 041d76e28..63f064e91 100644
--- a/screenpipe-server/tests/endpoint_test.rs
+++ b/screenpipe-server/tests/endpoint_test.rs
@@ -6,7 +6,6 @@ mod tests {
use axum::Router;
use chrono::DateTime;
use chrono::{Duration, Utc};
- use crossbeam::queue::SegQueue;
use screenpipe_audio::{AudioDevice, DeviceType};
use screenpipe_server::db_types::ContentType;
use screenpipe_server::db_types::SearchResult;
@@ -177,30 +176,28 @@ mod tests {
.unwrap();
let frame_id1 = db.insert_frame("test_device", None).await.unwrap();
let frame_id2 = db.insert_frame("test_device", None).await.unwrap();
- let _ = db
- .insert_ocr_text(
- frame_id1,
- "This is a test OCR text", // 21 chars
- "",
- "TestApp",
- "TestWindow",
- Arc::new(OcrEngine::Tesseract),
- false,
- )
- .await
- .unwrap();
- let _ = db
- .insert_ocr_text(
- frame_id2,
- "Another OCR text for testing that should be longer than thirty characters", // >30 chars
- "",
- "TestApp2",
- "TestWindow2",
- Arc::new(OcrEngine::Tesseract),
- false,
- )
- .await
- .unwrap();
+ db.insert_ocr_text(
+ frame_id1,
+ "This is a test OCR text", // 21 chars
+ "",
+ "TestApp",
+ "TestWindow",
+ Arc::new(OcrEngine::Tesseract),
+ false,
+ )
+ .await
+ .unwrap();
+ db.insert_ocr_text(
+ frame_id2,
+ "Another OCR text for testing that should be longer than thirty characters", // >30 chars
+ "",
+ "TestApp2",
+ "TestWindow2",
+ Arc::new(OcrEngine::Tesseract),
+ false,
+ )
+ .await
+ .unwrap();
let audio_chunk_id1 = db.insert_audio_chunk("test_audio1.wav").await.unwrap();
let audio_chunk_id2 = db.insert_audio_chunk("test_audio2.wav").await.unwrap();
@@ -243,6 +240,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -260,6 +258,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -277,6 +276,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -294,6 +294,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -311,6 +312,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -328,6 +330,7 @@ mod tests {
Some(30),
None,
None,
+ None,
)
.await
.unwrap();
@@ -345,6 +348,7 @@ mod tests {
None,
Some(25),
None,
+ None,
)
.await
.unwrap();
@@ -378,18 +382,17 @@ mod tests {
.unwrap();
// insert ocr and audio data
- let _ = db
- .insert_ocr_text(
- frame_id1,
- "old ocr text",
- "",
- "testapp",
- "testwindow",
- Arc::new(OcrEngine::Tesseract),
- false,
- )
- .await
- .unwrap();
+ db.insert_ocr_text(
+ frame_id1,
+ "old ocr text",
+ "",
+ "testapp",
+ "testwindow",
+ Arc::new(OcrEngine::Tesseract),
+ false,
+ )
+ .await
+ .unwrap();
let audio_transcription_id1 = db
.insert_audio_transcription(
@@ -425,6 +428,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -443,6 +447,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -462,6 +467,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -485,6 +491,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -507,6 +514,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -523,6 +531,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -568,31 +577,29 @@ mod tests {
.await
.unwrap();
- let _ = db
- .insert_ocr_text(
- old_frame_id,
- "old task: write documentation",
- "",
- "vscode",
- "tasks.md",
- Arc::new(OcrEngine::Tesseract),
- false,
- )
- .await
- .unwrap();
-
- let _ = db
- .insert_ocr_text(
- recent_frame_id,
- "current task: fix bug #123",
- "",
- "vscode",
- "tasks.md",
- Arc::new(OcrEngine::Tesseract),
- false,
- )
- .await
- .unwrap();
+ db.insert_ocr_text(
+ old_frame_id,
+ "old task: write documentation",
+ "",
+ "vscode",
+ "tasks.md",
+ Arc::new(OcrEngine::Tesseract),
+ false,
+ )
+ .await
+ .unwrap();
+
+ db.insert_ocr_text(
+ recent_frame_id,
+ "current task: fix bug #123",
+ "",
+ "vscode",
+ "tasks.md",
+ Arc::new(OcrEngine::Tesseract),
+ false,
+ )
+ .await
+ .unwrap();
// Search with 30-second window
let results = db
@@ -608,6 +615,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -635,6 +643,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -677,6 +686,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -697,6 +707,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
diff --git a/screenpipe-server/tests/index_test.rs b/screenpipe-server/tests/index_test.rs
index 6418d8e76..a6a5522b7 100644
--- a/screenpipe-server/tests/index_test.rs
+++ b/screenpipe-server/tests/index_test.rs
@@ -67,10 +67,15 @@ async fn test_index_command_with_sql() -> Result<()> {
// Run indexing
handle_index_command(
- temp_dir.path().to_string_lossy().to_string(),
+ temp_dir.path().into(),
+ video_path.to_str().unwrap().to_string(),
None,
db.clone(),
OutputFormat::Text,
+ None,
+ None,
+ false,
+ false,
)
.await?;
diff --git a/screenpipe-server/tests/tags_test.rs b/screenpipe-server/tests/tags_test.rs
index e36854389..57bca9a7b 100644
--- a/screenpipe-server/tests/tags_test.rs
+++ b/screenpipe-server/tests/tags_test.rs
@@ -4,7 +4,6 @@ use axum::{
Router,
};
use chrono::Utc;
-use crossbeam::queue::SegQueue;
use screenpipe_audio::{AudioDevice, DeviceType};
use screenpipe_vision::OcrEngine;
use serde_json::json;
@@ -155,7 +154,7 @@ async fn test_add_tags_and_search() {
assert!(audio.tags.contains(&"audio".to_string()));
}
ContentItem::UI(_) => {
- assert!(false);
+ unreachable!()
}
}
}
diff --git a/screenpipe-server/tests/video_utils_test.rs b/screenpipe-server/tests/video_utils_test.rs
index 169757ecf..b33db5b3a 100644
--- a/screenpipe-server/tests/video_utils_test.rs
+++ b/screenpipe-server/tests/video_utils_test.rs
@@ -53,7 +53,7 @@ async fn test_extract_frames() -> Result<()> {
println!("testing with write_to_disk = {}", write_to_disk);
let output_path = if write_to_disk {
- Some(PathBuf::from(home_dir().unwrap()).join("Downloads"))
+ Some(home_dir().unwrap().join("Downloads"))
} else {
None
};
@@ -112,11 +112,8 @@ async fn test_extract_frames_and_ocr() -> Result<()> {
);
// extract frames
- let frames = extract_frames_from_video(
- &video_path,
- Some(PathBuf::from(home_dir().unwrap()).join("Downloads")),
- )
- .await?;
+ let frames =
+ extract_frames_from_video(&video_path, Some(home_dir().unwrap().join("Downloads"))).await?;
// verify we got frames
assert!(!frames.is_empty(), "should extract at least one frame");
@@ -133,7 +130,7 @@ async fn test_extract_frames_and_ocr() -> Result<()> {
};
// perform ocr using apple native (macos only)
- let (text, _, confidence) = perform_ocr_apple(&captured_window.image, &vec![Language::English]);
+ let (text, _, confidence) = perform_ocr_apple(&captured_window.image, &[Language::English]);
println!("ocr confidence: {}", confidence.unwrap_or(0.0));
println!("extracted text: {}", text);
diff --git a/screenpipe-vision/benches/apple_leak_bench.rs b/screenpipe-vision/benches/apple_leak_bench.rs
index e9bff5d04..e618f5716 100644
--- a/screenpipe-vision/benches/apple_leak_bench.rs
+++ b/screenpipe-vision/benches/apple_leak_bench.rs
@@ -1,4 +1,3 @@
-use cidre::ns;
use criterion::{criterion_group, criterion_main, Criterion};
use image::GenericImageView;
use memory_stats::memory_stats;
@@ -39,8 +38,7 @@ fn apple_ocr_benchmark(c: &mut Criterion) {
}
}
- let result =
- perform_ocr_apple(&image, &ns::ArrayMut::<ns::String>::with_capacity(0));
+ let result = perform_ocr_apple(&image, &[]);
assert!(
result.0.contains("receiver_count"),
"OCR failed: {:?}",
diff --git a/screenpipe-vision/benches/ocr_benchmark.rs b/screenpipe-vision/benches/ocr_benchmark.rs
index 1b15fa677..cbb0b9d1e 100644
--- a/screenpipe-vision/benches/ocr_benchmark.rs
+++ b/screenpipe-vision/benches/ocr_benchmark.rs
@@ -75,8 +75,6 @@ fn load_test_image() -> image::DynamicImage {
// Apple Vision OCR benchmark (macOS only)
#[cfg(target_os = "macos")]
fn bench_apple_vision_ocr(c: &mut Criterion) {
- use cidre::ns;
-
let image = load_test_image();
let mut group = c.benchmark_group("Apple Vision OCR");
group.sample_size(10);
@@ -84,10 +82,7 @@ fn bench_apple_vision_ocr(c: &mut Criterion) {
group.bench_function(BenchmarkId::new("Performance", ""), |b| {
b.iter(|| {
- let result = perform_ocr_apple(
- black_box(&image),
- &ns::ArrayMut::<ns::String>::with_capacity(0),
- );
+ let result = perform_ocr_apple(black_box(&image), &[]);
assert!(!result.0.is_empty(), "OCR failed");
})
});
@@ -97,8 +92,6 @@ fn bench_apple_vision_ocr(c: &mut Criterion) {
#[cfg(target_os = "macos")]
fn bench_apple_vision_ocr_with_accuracy(c: &mut Criterion) {
- use cidre::ns;
-
let image = load_test_image();
let mut group = c.benchmark_group("Apple Vision OCR with Accuracy");
group.sample_size(10);
@@ -111,13 +104,10 @@ fn bench_apple_vision_ocr_with_accuracy(c: &mut Criterion) {
for _ in 0..iters {
let start = std::time::Instant::now();
- let result = perform_ocr_apple(
- black_box(&image),
- &ns::ArrayMut::<ns::String>::with_capacity(0),
- );
+ let result = perform_ocr_apple(black_box(&image), &[]);
total_duration += start.elapsed();
- let accuracy = calculate_accuracy(&result.0.as_str(), EXPECTED_KEYWORDS);
+ let accuracy = calculate_accuracy(&result.0, EXPECTED_KEYWORDS);
total_accuracy += accuracy;
}
diff --git a/screenpipe-vision/bin/ui_monitor b/screenpipe-vision/bin/ui_monitor
index 602bde837..c18230ba8 100755
Binary files a/screenpipe-vision/bin/ui_monitor and b/screenpipe-vision/bin/ui_monitor differ
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
index 602bde837..c18230ba8 100755
Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differ
diff --git a/screenpipe-vision/src/capture_screenshot_by_window.rs b/screenpipe-vision/src/capture_screenshot_by_window.rs
index a65d00e13..a87248219 100644
--- a/screenpipe-vision/src/capture_screenshot_by_window.rs
+++ b/screenpipe-vision/src/capture_screenshot_by_window.rs
@@ -227,8 +227,8 @@ pub async fn capture_all_visible_windows(
Ok(buffer) => {
let image = DynamicImage::ImageRgba8(
image::ImageBuffer::from_raw(
- buffer.width() as u32,
- buffer.height() as u32,
+ buffer.width(),
+ buffer.height(),
buffer.into_raw(),
)
.unwrap(),
diff --git a/screenpipe-vision/src/monitor.rs b/screenpipe-vision/src/monitor.rs
index 142c6c49a..c48f07a48 100644
--- a/screenpipe-vision/src/monitor.rs
+++ b/screenpipe-vision/src/monitor.rs
@@ -5,16 +5,13 @@ use xcap_macos::Monitor;
use xcap::Monitor;
pub async fn list_monitors() -> Vec<Monitor> {
- let monitors = Monitor::all().unwrap();
- return monitors.iter().map(|m| m.clone()).collect();
+ Monitor::all().unwrap().to_vec()
}
pub async fn get_default_monitor() -> Monitor {
- let monitors = list_monitors().await;
- return monitors.first().unwrap().clone();
+ list_monitors().await.first().unwrap().clone()
}
pub async fn get_monitor_by_id(id: u32) -> Option<Monitor> {
- let monitors = list_monitors().await;
- monitors.iter().find(|m| m.id() == id).cloned()
+ list_monitors().await.iter().find(|m| m.id() == id).cloned()
}
diff --git a/screenpipe-vision/src/tesseract.rs b/screenpipe-vision/src/tesseract.rs
index 7cc59ac37..1c1c518ae 100644
--- a/screenpipe-vision/src/tesseract.rs
+++ b/screenpipe-vision/src/tesseract.rs
@@ -12,7 +12,7 @@ pub fn perform_ocr_tesseract(
_ => TESSERACT_LANGUAGES
.iter()
.filter_map(|(key, val)| {
- if let Some(_) = languages.iter().find(|l| l == &val) {
+ if languages.iter().any(|l| l == val) {
Some(key.to_string())
} else {
None
@@ -65,28 +65,26 @@ fn data_output_to_json(data_output: &DataOutput) -> String {
let mut last_word_num = 0;
for record in &data_output.data {
- if record.word_num == 0 {
- if !current_line.is_empty() {
- let avg_conf = current_conf / word_count as f32;
- let mut line_data = HashMap::new();
- line_data.insert("text".to_string(), current_line.clone());
- line_data.insert("confidence".to_string(), format!("{:.2}", avg_conf));
- line_data.insert(
- "line_position".to_string(),
- format!(
- "level{}page_num{}block_num{}par_num{}line_num{}",
- record.level,
- record.page_num,
- record.block_num,
- record.par_num,
- record.line_num
- ),
- );
- lines.push(line_data);
- current_line.clear();
- current_conf = 0.0;
- word_count = 0;
- }
+ if record.word_num == 0 && !current_line.is_empty() {
+ let avg_conf = current_conf / word_count as f32;
+ let mut line_data = HashMap::new();
+ line_data.insert("text".to_string(), current_line.clone());
+ line_data.insert("confidence".to_string(), format!("{:.2}", avg_conf));
+ line_data.insert(
+ "line_position".to_string(),
+ format!(
+ "level{}page_num{}block_num{}par_num{}line_num{}",
+ record.level,
+ record.page_num,
+ record.block_num,
+ record.par_num,
+ record.line_num
+ ),
+ );
+ lines.push(line_data);
+ current_line.clear();
+ current_conf = 0.0;
+ word_count = 0;
}
if record.word_num > last_word_num {
if !current_line.is_empty() {
diff --git a/screenpipe-vision/src/utils.rs b/screenpipe-vision/src/utils.rs
index c22c64400..28a8f2349 100644
--- a/screenpipe-vision/src/utils.rs
+++ b/screenpipe-vision/src/utils.rs
@@ -15,20 +15,16 @@ use xcap_macos::Monitor;
#[cfg(not(target_os = "macos"))]
use xcap::Monitor;
-#[derive(Clone, Debug)]
+#[derive(Clone, Debug, Default)]
pub enum OcrEngine {
Unstructured,
+ #[default]
Tesseract,
WindowsNative,
AppleNative,
Custom(CustomOcrConfig),
}
-impl Default for OcrEngine {
- fn default() -> Self {
- OcrEngine::Tesseract
- }
-}
pub fn calculate_hash(image: &DynamicImage) -> u64 {
let mut hasher = DefaultHasher::new();
image.as_bytes().hash(&mut hasher);