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

feat: mp4 + api + doc update

Louis Beaumont140b026b987f
diff --git a/README.md b/README.md
index 6ca1f521f..506411435 100644
--- a/README.md
+++ b/README.md
@@ -47,56 +47,47 @@ export async function onTick() {
## Status
-Alpha: runs on my computer (`Macbook pro m3 32 GB ram`). Capture things and do things.
+Alpha: runs on my computer (`Macbook pro m3 32 GB ram`). Record your screen 24/7 into mp4 and extract the text from every frame.
## Usage
-Keep in mind that it's still experimental but got a working prototype, see the [Related projects](#related-projects) section.
+Keep in mind that it's still experimental.
-To try the current version, which capture your screen, extract the text, and do some LLM magic, run:
+To try the current version, which capture your screen and extract the text, do:
+
+1. Install [ffmpeg](https://www.ffmpeg.org/download.html).
+2. Clone the repo:
```bash
git clone https://github.com/louis030195/screen-pipe
-cd screen-pipe
+cd screen-pipe/screenpipe
```
-Then, in one terminal run the OCR API [(just a temporary hack until something cleaner)](https://github.com/louis030195/screen-pipe/issues/7):
+3. Run the API (make sure to install [Rust](https://www.rust-lang.org/tools/install)):
```bash
-virtualenv env
-source env/bin/activate
-pip install fastapi uvicorn pytesseract pillow
-uvicorn main:app --reload
+cargo run
```
-In another terminal run [ollama](https://github.com/ollama/ollama):
+Get today's context (all the text you've seen):
```bash
-ollama run llama3
+curl "http://localhost:3030/texts?date=$(date +%Y-%m-%d%%20%H:%M:%S)"
```
-And (you need Rust + Cargo installed) the Rust CLI:
+Or search for a specific text:
```bash
-cargo install --path screenpipe
-screenpipe
+curl "http://localhost:3030/frames?limit=10&offset=0&search='louis'"
```
-Check the `target/screenshots` directory now :)
-
-<details>
- <summary>Sample file</summary>
-
- Basically ends up with bunch of image + JSON pairs with the OCR:
-
- ```json
-{"text":"{\"text\":\"e P& screen-pipe Ow 33\\nOo Pe Av @ Cargo.toml M ® main.rs MX {} ® main.py 1, U cay\\n\\\\Y OPEN EDITORS screenpipe > src > ® main.rs > @ process_image\\n© Cargo.tom! screenpipe M async fn call_ocr_api(image_path: &str) — Result<String, reqwest::Error> {\\nX ® main.rs screenpipe/src M let text = response.text().await?;\\n{} Ok( text)\\n@ main.py 1,U }\\n\\\\ SCREEN-PIPE\\n> __pycache_ async fn process_image(filename: String) {\\n> .github // Example async post-processing function\\n> cy // Perform tasks like extracting text or making API calls here\\nMrecicervine println!(\\\"Processing image asynchronously: {}\\\", filename);\\nv ste // Simulate async work Lr\\n. j // tokio:: time :: sleep(Duration:: from_secs(1)).await;\\n® main.rs M y , . .\\n. y let text = call_ocr_api( &filename).await.unwrap();\\ny println!(\\\"OCR result: {}\\\", text);\\n80,\\n Cargo.toml M y // Create a JSON object\\n¥ y let json = serde_json::json!({ \\\"text\\\": text });\\n> y let new_filename = filename.replace( \\\"\\\\png\\\", \\\",json\\\");\\n> y let mut file = File::create( new_filename).unwrap();\\n> y file.write_all( json.to_string().as_bytes()).unwrap();\\n> ¥\\n>\\n> fn screenpipe(path: &Sstr, interval: f32, running: Arc<AtomicBool>) {\\n{} // delete and recreate the directory\\nPROBLEMS 9 OUTPUT DEBUGCONSOLE TERMINAL PORTS tu we A xX\\n® .gitignore Found 1 monitors | (9 screenpipe A\\nScreenshots will be saved to target/screenshots =\\nInterval: @ seconds (g bash A\\n Cargo.toml Press Ctrl+C to stop I @ Python A\\n® Cross.toml\\n$ install.sh TN TN TN TN JN /_/\\\\ TIN TN TW\\nf{ LICENSE.md J f:/_ / /:/ VEEN J f:/_ J f:/_ \\\\OA\\\\:\\\\ J /::\\\\ 1 IN I PS I Pl.\\nnr . ar wn ee a eee ee ee ee VAN J L:1\\\\:\\\\1 131 J 1:1\\\\:\\\\7_ 1:7 /N\\n> CET PS? 11U 1 i ee ee ee ee ee A 9 hod? ee ee 9 ey ee 2 —--\\\\--\\\\:\\\\ J f:/~1:1__12\\\\ ee shed et ee\\n@ README.md 7 Aa AY ee ee A 9 a ® ® ® a ® \\\\ JA 1 121N\\\\_NIN?\\\\_S S31 121131 1:1 /N\\nNONE /e7N ONIN ZN NM ttt NEE NO NAA IN \\\\i\\\\ee\\\\e\\\\/ \\\\A\\\\HW:/ NONE AINA 27\\nNONE 722 NNN LSD NX Nit/eere NONE DD NONE Lt NONI ee \\\\ \\\\is/ \\\\Ne/\\\\ N\\\\esZ NO NitZ /:/\\nVW Jf NNN NNN VON: NONE NNN \\\\O\\\\N\\\\ J_S:/ \\\\ \\\\:\\\\ XN NINA:/\\n/_/:/ \\\\ \\\\is/ VAN \\\\ \\\\is/ \\\\ \\\\sa/ \\\\O\\\\N\\\\ \\\\O\\\\N\\\\ \\\\_V \\\\ Vt \\\\ \\\\s2/\\n\\\\__V \\\\__V \\\\__V \\\\__V \\\\__V \\\\__V \\\\__V \\\\__V \\\\__V\\n* Update Cursor? I\\n> BRILLIANT Ai. .--.-. --- eee eee\\n\\n& mains 2 @©®1A1@7_ rust-analyzer Ln80,Col1 Rust Copilot++ &\\n\"}"}
- ```
-
-And the idea is to feed this to an LLM that do rest of the work
-</details>
-
+Now pipe this into a LLM to build:
+- memory extension apps
+- automatic summaries
+- automatic action triggers (say every time you see a dog, send a tweet)
+- automatic CRM (fill salesforce while you spam ppl on linkedin)
+We are working toward [making it easier to try](https://github.com/louis030195/screen-pipe/issues/6), feel free to help!
https://github.com/louis030195/screen-pipe/assets/25003283/bdce0793-3db4-4233-a276-65c3e4f8a333
@@ -135,3 +126,5 @@ The code in this project is licensed under MIT license. See the [LICENSE](LICENS
This is a very quick & dirty example of the end goal that works in a few lines of python:
https://github.com/louis030195/screen-to-crm
+
+Very thankful for https://github.com/jasonjmcghee/xrem which was helpful. Although screenpipe is going in a different direction.
diff --git a/screenpipe/Cargo.toml b/screenpipe/Cargo.toml
index 5a58a24cd..9abc0aa27 100644
--- a/screenpipe/Cargo.toml
+++ b/screenpipe/Cargo.toml
@@ -10,18 +10,15 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
# Cross-platform screen capture
-# screenshots = "0.8.10" # todo xcap
xcap = "0.0.10"
# threadpool
threadpool = "1.8.1"
# Image processing
-# image = "0.24.7"
image = "0.25.0"
# OCR
-# rusty-tesseract = "1.1.9"
rusty-tesseract = "1.1.10"
# Dates
@@ -30,7 +27,6 @@ chrono = "0.4.31"
rusqlite = { version = "0.30.0", features = ["chrono", "bundled", "array"] }
# FFmpeg bindings
-# ffmpeg-next = "6.1.0"
ffmpeg-next = "7.0.2"
# Embeddings
diff --git a/screenpipe/binaries/ffmpeg b/screenpipe/binaries/ffmpeg
deleted file mode 100755
index 39be00942..000000000
Binary files a/screenpipe/binaries/ffmpeg and /dev/null differ
diff --git a/screenpipe/src/core/core.rs b/screenpipe/src/core/core.rs
index e6642d2f9..d6b1e7370 100644
--- a/screenpipe/src/core/core.rs
+++ b/screenpipe/src/core/core.rs
@@ -27,7 +27,7 @@ enum ControlMessage {
}
pub struct CaptureHandles {
- // pub capture_handle: thread::JoinHandle<()>,
+ pub capture_handle: thread::JoinHandle<()>,
pub stream_handle: thread::JoinHandle<()>,
pub control_sender: mpsc::Sender<ControlMessage>,
}
@@ -100,7 +100,7 @@ pub fn start_recording(
});
return CaptureHandles {
- // capture_handle,
+ capture_handle,
stream_handle,
control_sender,
};
@@ -198,7 +198,7 @@ fn perform_ocr(dynamic_image: &DynamicImage) -> Result<String, Box<dyn std::erro
// OCR
let text = image_to_string(&image, &args)?;
- println!("OCR: {}", text);
+ // println!("OCR: {}", text);
Ok(text)
}
@@ -230,7 +230,8 @@ fn stream_to_ffmpeg(
"-pix_fmt",
"yuv420p",
"-crf",
- "25",
+ // "25",
+ "18",
&output_name,
])
.stdin(Stdio::piped())
diff --git a/screenpipe/src/core/db.rs b/screenpipe/src/core/db.rs
index 2b5da2b82..3b83a4fd3 100644
--- a/screenpipe/src/core/db.rs
+++ b/screenpipe/src/core/db.rs
@@ -49,6 +49,12 @@ pub struct DatabaseManager {
fps: i32,
}
+#[derive(Debug)]
+pub struct TextWithTimestamp {
+ pub text: String,
+ pub timestamp: NaiveDateTime,
+}
+
impl DatabaseManager {
// Initialize a new DatabaseManager instance
pub fn new(database_path: &str) -> Result<DatabaseManager> {
@@ -170,6 +176,7 @@ impl DatabaseManager {
// Method to insert a frame and return its ID
pub fn insert_frame(&mut self, active_application_name: Option<String>) -> Result<i64> {
+ // println!("inserting frame... {:?}", Utc::now().naive_utc());
let frame_id = self.conn.execute(
"INSERT INTO frames (chunk_id, offset_index, timestamp, active_application_name)
VALUES (?1, ?2, ?3, ?4)",
@@ -225,18 +232,21 @@ impl DatabaseManager {
}
// Method to get a frame by index
- pub fn get_frame(&self, index: i64) -> Result<Option<(i64, String)>> {
+ pub fn get_frame(&self, index: i64) -> Result<Option<(i64, String, Option<String>)>> {
let mut stmt = self.conn.prepare(
- "SELECT f.offset_index, vc.file_path FROM frames f
- JOIN video_chunks vc ON f.chunk_id = vc.id
- WHERE f.id = ?1",
+ "SELECT f.offset_index, vc.file_path, at.text
+ FROM frames f
+ JOIN video_chunks vc ON f.chunk_id = vc.id
+ LEFT JOIN all_text at ON f.id = at.frame_id
+ WHERE f.id = ?1",
)?;
let mut rows = stmt.query(params![index])?;
if let Some(row) = rows.next()? {
let offset_index: i64 = row.get(0)?;
let file_path: String = row.get(1)?;
- Ok(Some((offset_index, file_path)))
+ let text: Option<String> = row.get(2)?;
+ Ok(Some((offset_index, file_path, text)))
} else {
Ok(None)
}
@@ -346,9 +356,10 @@ impl DatabaseManager {
selected_filter_app: Option<&str>,
) -> Result<Vec<SearchResult>> {
let mut query = String::from(
- "SELECT f.id, NULL, f.active_application_name, f.timestamp, vc.file_path, f.offset_index
+ "SELECT f.id, at.text, f.active_application_name, f.timestamp, vc.file_path, f.offset_index
FROM frames f
- JOIN video_chunks vc ON f.chunk_id = vc.id ",
+ JOIN video_chunks vc ON f.chunk_id = vc.id
+ LEFT JOIN all_text at ON f.id = at.frame_id ",
);
let mut params: Vec<rusqlite::types::Value> = Vec::new();
@@ -360,7 +371,6 @@ impl DatabaseManager {
format!("WHERE uan.active_application_name LIKE ?{} ", params_count).as_str(),
);
params.push(String::from(app_name).into());
- // Added a param
params_count = params.len() + 1;
}
@@ -372,10 +382,10 @@ impl DatabaseManager {
)
.as_str(),
);
- params.push(String::from(limit.to_string()).into());
- params.push(String::from(offset.to_string()).into());
- // Update params count
- params_count = params.len() + 1;
+ params.push(limit.into());
+ params.push(offset.into());
+
+ println!("Query: {}", query); // Debug: Print the query
let mut stmt = self.conn.prepare(&query)?;
let final_params = params_from_iter(params);
@@ -383,7 +393,7 @@ impl DatabaseManager {
.query_map(final_params, |row| {
Ok(SearchResult {
frame_id: row.get(0)?,
- full_text: None, // Since the full text is not being fetched here
+ full_text: row.get(1)?,
application_name: row.get(2)?,
timestamp: row.get(3)?,
file_path: row.get(4)?,
@@ -394,15 +404,23 @@ impl DatabaseManager {
Ok(results)
}
-
// Method to get recent text context
- pub fn get_recent_text_context(&self) -> Result<Vec<String>> {
- let mut stmt = self
- .conn
- .prepare("SELECT text FROM all_text ORDER BY frame_id DESC LIMIT ?1")?;
+ pub fn get_recent_text_context(&self, date: NaiveDateTime) -> Result<Vec<TextWithTimestamp>> {
+ let mut stmt = self.conn.prepare(
+ "SELECT at.text, f.timestamp
+ FROM all_text at
+ JOIN frames f ON at.frame_id = f.id
+ WHERE DATE(f.timestamp) = DATE(?1)
+ ORDER BY f.id DESC",
+ )?;
let texts = stmt
- .query_map(params![self.recent_frames_threshold], |row| Ok(row.get(0)?))?
- .collect::<Result<Vec<String>, rusqlite::Error>>()?;
+ .query_map(params![date], |row| {
+ Ok(TextWithTimestamp {
+ text: row.get(0)?,
+ timestamp: row.get(1)?,
+ })
+ })?
+ .collect::<Result<Vec<TextWithTimestamp>, rusqlite::Error>>()?;
Ok(texts)
}
diff --git a/screenpipe/src/core/video.rs b/screenpipe/src/core/video.rs
index e44bceafb..11534d0db 100644
--- a/screenpipe/src/core/video.rs
+++ b/screenpipe/src/core/video.rs
@@ -30,6 +30,7 @@ pub fn extract_frames_from_video(
decoder.width(),
decoder.height(),
scaling::Flags::BILINEAR,
+ // scaling::Flags::LANCZOS,
)?;
let mut sorted_frame_numbers: BTreeSet<_> = frame_numbers.iter().copied().collect();
diff --git a/screenpipe/src/server.rs b/screenpipe/src/server.rs
index 429254a63..aeca2c5f2 100644
--- a/screenpipe/src/server.rs
+++ b/screenpipe/src/server.rs
@@ -1,3 +1,4 @@
+use std::collections::HashMap;
use std::sync::Mutex;
use std::{io::Cursor, sync::Arc};
@@ -9,7 +10,7 @@ use axum::{
routing::get,
Json, Router,
};
-use chrono::Utc;
+use chrono::{NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::oneshot;
@@ -40,6 +41,12 @@ struct ImageParams {
thumbnail: Option<bool>,
}
+#[derive(Serialize)]
+struct TextWithTimestampResponse {
+ text: String,
+ timestamp: String, // Use String to serialize NaiveDateTime easily
+}
+
// TODO: Optimize this to do chunk loading, instead of starting from scratch with the
// frame every single time
// TODO: Also, cache the frames in memory using an LRU cache
@@ -57,7 +64,8 @@ async fn get_frame_handler(
.get_frame(frame_number)
.expect("Failed to get frame")
};
- if let Some((offset_index, video_path)) = maybe_video_path {
+ if let Some((offset_index, video_path, _)) = maybe_video_path {
+ println!("video path: {:?}", video_path);
match extract_frames_from_video(&video_path, &[offset_index]) {
Ok(frames) => {
if let Some(frame) = frames.into_iter().next() {
@@ -68,15 +76,27 @@ async fn get_frame_handler(
.write_to(&mut cursor, image::ImageFormat::Png)
.is_ok()
{
+ println!("Thumbnail generated successfully");
return (StatusCode::OK, Bytes::from(cursor.into_inner()));
+ } else {
+ println!("Failed to generate thumbnail");
}
} else if frame.write_to(&mut cursor, image::ImageFormat::Png).is_ok() {
+ println!("Frame generated successfully");
return (StatusCode::OK, Bytes::from(cursor.into_inner()));
+ } else {
+ println!("Failed to generate frame");
}
+ } else {
+ println!("No frames found");
}
}
- _ => {}
+ Err(e) => {
+ println!("Error extracting frames: {:?}", e);
+ }
}
+ } else {
+ println!("No video path found for frame number: {}", frame_number);
}
(StatusCode::NOT_FOUND, Bytes::new())
}
@@ -98,6 +118,7 @@ async fn get_max_frame_handler(State(state): State<Arc<AppState>>) -> Json<Frame
struct Frame {
frame_number: i64,
timestamp: i64,
+ text: Option<String>,
}
#[derive(Serialize)]
@@ -135,11 +156,41 @@ async fn search_frames_handler(
data.push(Frame {
frame_number,
timestamp: timestamp.timestamp_millis(),
+ text: frame.full_text,
});
}
Json(PaginatedFrames { data })
}
+async fn get_texts_by_date_handler(
+ Query(query): Query<HashMap<String, String>>,
+ State(state): State<Arc<AppState>>,
+) -> Result<Json<Vec<TextWithTimestampResponse>>, StatusCode> {
+ let date_str = query.get("date").ok_or(StatusCode::BAD_REQUEST)?;
+ let date = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S")
+ .map_err(|_| StatusCode::BAD_REQUEST)?;
+
+ let db_video_ref = state.db.clone();
+ let texts_with_timestamps = {
+ let mut db_clone = db_video_ref.lock().unwrap();
+ db_clone
+ .as_mut()
+ .unwrap()
+ .get_recent_text_context(date)
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
+ };
+
+ let response: Vec<TextWithTimestampResponse> = texts_with_timestamps
+ .into_iter()
+ .map(|item| TextWithTimestampResponse {
+ text: item.text,
+ timestamp: item.timestamp.to_string(),
+ })
+ .collect();
+
+ Ok(Json(response))
+}
+
pub async fn start_frame_server(
tx: oneshot::Sender<()>,
local_data_dir: String,
@@ -151,6 +202,7 @@ pub async fn start_frame_server(
.route("/frames", get(search_frames_handler))
.route("/frames/max", get(get_max_frame_handler))
.route("/frames/:frame_number", get(get_frame_handler))
+ .route("/texts", get(get_texts_by_date_handler))
.layer(CorsLayer::permissive())
.with_state(state);