From 5cb15dab45e209bf82d8421744f77ee507d7e7fa Mon Sep 17 00:00:00 2001 From: Per Stark Date: Sun, 28 Sep 2025 20:53:35 +0200 Subject: [PATCH] feat: pdf support --- CHANGELOG.md | 36 + Cargo.lock | 203 ++++- common/src/storage/store.rs | 3 +- common/src/storage/types/file_info.rs | 9 +- common/src/utils/config.rs | 16 + ingestion-pipeline/Cargo.toml | 2 + ingestion-pipeline/src/types/mod.rs | 70 +- ingestion-pipeline/src/utils/mod.rs | 1 + ingestion-pipeline/src/utils/pdf_ingestion.rs | 795 ++++++++++++++++++ 9 files changed, 1105 insertions(+), 30 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 ingestion-pipeline/src/utils/pdf_ingestion.rs diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3b878c4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +## Version 0.2.1 (2025-09-24) +- Fixed API JSON responses so iOS Shortcuts integrations keep working. + +## Version 0.2.0 (2025-09-23) +- Revamped the UI with a neobrutalist theme, better dark mode, and a D3-based knowledge graph. +- Added pagination for entities and content plus new observability metrics on the dashboard. +- Enabled audio ingestion and merged the new storage backend. +- Improved performance, request filtering, and journalctl/systemd compatibility. + +## Version 0.1.4 (2025-07-01) +- Added image ingestion with configurable system settings and updated Docker Compose docs. +- Hardened admin flows by fixing concurrent API/database calls and normalizing task statuses. + +## Version 0.1.3 (2025-06-08) +- Added support for AI providers beyond OpenAI. +- Made the HTTP port configurable for deployments. +- Smoothed graph mapper failures, long content tiles, and refreshed project documentation. + +## Version 0.1.2 (2025-05-26) +- Introduced full-text search across indexed knowledge. +- Polished the UI with consistent titles, icon fallbacks, and improved markdown scrolling. +- Fixed search result links and SurrealDB vector formatting glitches. + +## Version 0.1.1 (2025-05-13) +- Added streaming feedback to ingestion tasks for clearer progress updates. +- Made the data storage path configurable. +- Improved release tooling with Chromium-enabled Nix flakes, Docker builds, and migration/template fixes. + +## Version 0.1.0 (2025-05-06) +- Initial release with a SurrealDB-backed ingestion pipeline, job queue, vector search, and knowledge graph storage. +- Delivered a chat experience featuring streaming responses, conversation history, markdown rendering, and customizable system prompts. +- Introduced an admin console with analytics, registration and timezone controls, and job monitoring. +- Shipped a Tailwind/daisyUI web UI with responsive layouts, modals, content viewers, and editing flows. +- Provided readability-based content ingestion, API/HTML ingress routes, and Docker/Docker Compose tooling. diff --git a/Cargo.lock b/Cargo.lock index 353ff07..8a8f8e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -36,6 +36,15 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" +[[package]] +name = "adobe-cmap-parser" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae8abfa9a4688de8fc9f42b3f013b6fffec18ed8a554f5f113577e0b9b3212a3" +dependencies = [ + "pom", +] + [[package]] name = "aead" version = "0.5.2" @@ -881,6 +890,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + [[package]] name = "blowfish" version = "0.9.1" @@ -963,6 +981,12 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + [[package]] name = "bytemuck" version = "1.23.0" @@ -993,6 +1017,15 @@ dependencies = [ "rustversion", ] +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.2.21" @@ -1061,6 +1094,12 @@ dependencies = [ "unicode-security", ] +[[package]] +name = "cff-parser" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31f5b6e9141c036f3ff4ce7b2f7e432b0f00dee416ddcd4f17741d189ddc2e9d" + [[package]] name = "cfg-if" version = "1.0.0" @@ -1840,6 +1879,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ecb" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a8bfa975b1aec2145850fcaa1c6fe269a16578c44705a532ae3edc92b8881c7" +dependencies = [ + "cipher", +] + [[package]] name = "either" version = "1.15.0" @@ -1892,6 +1940,15 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "euclid" +version = "0.20.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bb7ef65b3777a325d1eeefefab5b6d4959da54747e33bd6258e789640f307ad" +dependencies = [ + "num-traits", +] + [[package]] name = "event-listener" version = "5.4.0" @@ -2866,6 +2923,8 @@ dependencies = [ "dom_smoothie", "futures", "headless_chrome", + "lopdf 0.32.0", + "pdf-extract", "reqwest", "serde", "serde_json", @@ -2904,6 +2963,7 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ + "block-padding", "generic-array", ] @@ -3133,6 +3193,12 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + [[package]] name = "linux-raw-sys" version = "0.9.4" @@ -3161,6 +3227,51 @@ version = "0.4.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" +[[package]] +name = "lopdf" +version = "0.32.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e775e4ee264e8a87d50a9efef7b67b4aa988cf94e75630859875fc347e6c872b" +dependencies = [ + "chrono", + "encoding_rs", + "flate2", + "itoa", + "linked-hash-map", + "log", + "md5", + "nom 7.1.3", + "rayon", + "time", + "weezl", +] + +[[package]] +name = "lopdf" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59fa2559e99ba0f26a12458aabc754432c805bbb8cba516c427825a997af1fb7" +dependencies = [ + "aes", + "bitflags 2.9.0", + "cbc", + "ecb", + "encoding_rs", + "flate2", + "indexmap 2.9.0", + "itoa", + "log", + "md-5", + "nom 8.0.0", + "nom_locate", + "rand 0.9.1", + "rangemap", + "sha2", + "stringprep", + "thiserror 2.0.12", + "weezl", +] + [[package]] name = "lru" version = "0.12.5" @@ -3178,7 +3289,7 @@ checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" [[package]] name = "main" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anyhow", "api-router", @@ -3274,6 +3385,12 @@ dependencies = [ "digest", ] +[[package]] +name = "md5" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" + [[package]] name = "memchr" version = "2.7.4" @@ -3506,6 +3623,17 @@ dependencies = [ "memchr", ] +[[package]] +name = "nom_locate" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b577e2d69827c4740cba2b52efaad1c4cc7c73042860b199710b3575c68438d" +dependencies = [ + "bytecount", + "memchr", + "nom 8.0.0", +] + [[package]] name = "nonempty" version = "0.7.0" @@ -3828,6 +3956,23 @@ dependencies = [ "sha2", ] +[[package]] +name = "pdf-extract" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2f44c6c642e359e2fe7f662bf5438db3811b6b4be60afc6de04b619ce51e1a" +dependencies = [ + "adobe-cmap-parser", + "cff-parser", + "encoding_rs", + "euclid", + "log", + "lopdf 0.36.0", + "postscript", + "type1-encoding-parser", + "unicode-normalization", +] + [[package]] name = "pem" version = "3.0.5" @@ -4019,6 +4164,18 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "pom" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60f6ce597ecdcc9a098e7fddacb1065093a3d66446fa16c675e7e71d1b5c28e6" + +[[package]] +name = "postscript" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78451badbdaebaf17f053fd9152b3ffb33b516104eacb45e7864aaa9c712f306" + [[package]] name = "powerfmt" version = "0.2.0" @@ -4284,6 +4441,12 @@ dependencies = [ "getrandom 0.3.2", ] +[[package]] +name = "rangemap" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f93e7e49bb0bf967717f7bd674458b3d6b0c5f48ec7e3038166026a69fc22223" + [[package]] name = "rawpointer" version = "0.2.1" @@ -5276,6 +5439,17 @@ dependencies = [ "quote", ] +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "strsim" version = "0.11.1" @@ -6108,6 +6282,15 @@ dependencies = [ "utf-8", ] +[[package]] +name = "type1-encoding-parser" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3d6cc09e1a99c7e01f2afe4953789311a1c50baebbdac5b477ecf78e2e92a5b" +dependencies = [ + "pom", +] + [[package]] name = "typenum" version = "1.18.0" @@ -6143,6 +6326,12 @@ version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.18" @@ -6158,6 +6347,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-properties" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" + [[package]] name = "unicode-script" version = "0.5.7" @@ -6487,6 +6682,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "weezl" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a751b3277700db47d3e574514de2eced5e54dc8a5436a3bf7a0b248b2cee16f3" + [[package]] name = "which" version = "7.0.3" diff --git a/common/src/storage/store.rs b/common/src/storage/store.rs index ade12c0..db0292f 100644 --- a/common/src/storage/store.rs +++ b/common/src/storage/store.rs @@ -196,7 +196,7 @@ pub fn split_object_path(path: &str) -> AnyResult<(String, String)> { #[cfg(test)] mod tests { use super::*; - use crate::utils::config::StorageKind; + use crate::utils::config::{PdfIngestMode::LlmFirst, StorageKind}; use bytes::Bytes; use futures::TryStreamExt; use uuid::Uuid; @@ -213,6 +213,7 @@ mod tests { http_port: 0, openai_base_url: "..".into(), storage: StorageKind::Local, + pdf_ingest_mode: LlmFirst, } } diff --git a/common/src/storage/types/file_info.rs b/common/src/storage/types/file_info.rs index 1ce2b83..4558827 100644 --- a/common/src/storage/types/file_info.rs +++ b/common/src/storage/types/file_info.rs @@ -277,7 +277,7 @@ impl FileInfo { #[cfg(test)] mod tests { use super::*; - use crate::utils::config::StorageKind; + use crate::utils::config::{PdfIngestMode::LlmFirst, StorageKind}; use axum::http::HeaderMap; use axum_typed_multipart::FieldMetadata; use std::io::Write; @@ -332,6 +332,7 @@ mod tests { http_port: 3000, openai_base_url: "..".to_string(), storage: StorageKind::Local, + pdf_ingest_mode: LlmFirst, }; // Test file creation @@ -392,6 +393,7 @@ mod tests { http_port: 3000, openai_base_url: "..".to_string(), storage: StorageKind::Local, + pdf_ingest_mode: LlmFirst, }; // Store the original file @@ -448,6 +450,7 @@ mod tests { http_port: 3000, openai_base_url: "..".to_string(), storage: StorageKind::Local, + pdf_ingest_mode: LlmFirst, }; let file_info = FileInfo::new(field_data, &db, user_id, &config).await; @@ -505,6 +508,7 @@ mod tests { http_port: 3000, openai_base_url: "..".to_string(), storage: StorageKind::Local, + pdf_ingest_mode: LlmFirst, }; let field_data1 = create_test_file(content, file_name); @@ -669,6 +673,7 @@ mod tests { http_port: 0, openai_base_url: "".to_string(), storage: crate::utils::config::StorageKind::Local, + pdf_ingest_mode: LlmFirst, }; let temp = create_test_file(b"test content", "test_file.txt"); let file_info = FileInfo::new(temp, &db, user_id, &cfg) @@ -723,6 +728,7 @@ mod tests { http_port: 0, openai_base_url: "".to_string(), storage: crate::utils::config::StorageKind::Local, + pdf_ingest_mode: LlmFirst, }, ) .await; @@ -831,6 +837,7 @@ mod tests { http_port: 3000, openai_base_url: "..".to_string(), storage: StorageKind::Local, + pdf_ingest_mode: LlmFirst, }; // Test file creation diff --git a/common/src/utils/config.rs b/common/src/utils/config.rs index bd4b36e..6b3dd65 100644 --- a/common/src/utils/config.rs +++ b/common/src/utils/config.rs @@ -11,6 +11,20 @@ fn default_storage_kind() -> StorageKind { StorageKind::Local } +/// Selects the strategy used for PDF ingestion. +#[derive(Clone, Deserialize, Debug)] +#[serde(rename_all = "kebab-case")] +pub enum PdfIngestMode { + /// Only rely on classic text extraction (no LLM fallbacks). + Classic, + /// Prefer fast text extraction, but fall back to the LLM rendering path when needed. + LlmFirst, +} + +fn default_pdf_ingest_mode() -> PdfIngestMode { + PdfIngestMode::LlmFirst +} + #[derive(Clone, Deserialize, Debug)] pub struct AppConfig { pub openai_api_key: String, @@ -26,6 +40,8 @@ pub struct AppConfig { pub openai_base_url: String, #[serde(default = "default_storage_kind")] pub storage: StorageKind, + #[serde(default = "default_pdf_ingest_mode")] + pub pdf_ingest_mode: PdfIngestMode, } fn default_data_dir() -> String { diff --git a/ingestion-pipeline/Cargo.toml b/ingestion-pipeline/Cargo.toml index d2cacb2..3ba2831 100644 --- a/ingestion-pipeline/Cargo.toml +++ b/ingestion-pipeline/Cargo.toml @@ -23,6 +23,8 @@ url = { workspace = true } uuid = { workspace = true } headless_chrome = { workspace = true } base64 = { workspace = true } +pdf-extract = "0.9" +lopdf = "0.32" common = { path = "../common" } composite-retrieval = { path = "../composite-retrieval" } diff --git a/ingestion-pipeline/src/types/mod.rs b/ingestion-pipeline/src/types/mod.rs index 129872c..6df7322 100644 --- a/ingestion-pipeline/src/types/mod.rs +++ b/ingestion-pipeline/src/types/mod.rs @@ -9,10 +9,13 @@ use chrono::Utc; use common::storage::db::SurrealDbClient; use common::{ error::AppError, - storage::types::{ - file_info::FileInfo, - ingestion_payload::IngestionPayload, - text_content::{TextContent, UrlInfo}, + storage::{ + store, + types::{ + file_info::FileInfo, + ingestion_payload::IngestionPayload, + text_content::{TextContent, UrlInfo}, + }, }, utils::config::AppConfig, }; @@ -24,6 +27,7 @@ use tracing::{error, info}; use crate::utils::{ audio_transcription::transcribe_audio_file, image_parsing::extract_text_from_image, + pdf_ingestion::extract_pdf_content, }; pub async fn to_text_content( @@ -72,7 +76,7 @@ pub async fn to_text_content( category, user_id, } => { - let text = extract_text_from_file(&file_info, db, openai_client).await?; + let text = extract_text_from_file(&file_info, db, openai_client, config).await?; Ok(TextContent::new( text, Some(context), @@ -199,43 +203,55 @@ async fn fetch_article_from_url( Ok((article, file_info)) } -/// Extracts text from a file based on its MIME type. +/// Extracts text from a stored file by MIME type. async fn extract_text_from_file( file_info: &FileInfo, db_client: &SurrealDbClient, openai_client: &async_openai::Client, + config: &AppConfig, ) -> Result { + let base_path = store::resolve_base_dir(config); + let absolute_path = base_path.join(&file_info.path); + match file_info.mime_type.as_str() { - "text/plain" => { - // Read the file and return its content - let content = tokio::fs::read_to_string(&file_info.path).await?; - Ok(content) - } - "text/markdown" => { - // Read the file and return its content - let content = tokio::fs::read_to_string(&file_info.path).await?; + "text/plain" | "text/markdown" | "application/octet-stream" | "text/x-rust" => { + let content = tokio::fs::read_to_string(&absolute_path).await?; Ok(content) } "application/pdf" => { - // TODO: Implement PDF text extraction using a crate like `pdf-extract` or `lopdf` - Err(AppError::NotFound(file_info.mime_type.clone())) + extract_pdf_content( + &absolute_path, + db_client, + openai_client, + &config.pdf_ingest_mode, + ) + .await } "image/png" | "image/jpeg" => { - let content = - extract_text_from_image(&file_info.path, db_client, openai_client).await?; - Ok(content) - } - "application/octet-stream" => { - let content = tokio::fs::read_to_string(&file_info.path).await?; - Ok(content) - } - "text/x-rust" => { - let content = tokio::fs::read_to_string(&file_info.path).await?; + let path_str = absolute_path + .to_str() + .ok_or_else(|| { + AppError::Processing(format!( + "Encountered a non-UTF8 path while reading image {}", + file_info.id + )) + })? + .to_string(); + let content = extract_text_from_image(&path_str, db_client, openai_client).await?; Ok(content) } "audio/mpeg" | "audio/mp3" | "audio/wav" | "audio/x-wav" | "audio/webm" | "audio/mp4" | "audio/ogg" | "audio/flac" => { - transcribe_audio_file(&file_info.path, db_client, openai_client).await + let path_str = absolute_path + .to_str() + .ok_or_else(|| { + AppError::Processing(format!( + "Encountered a non-UTF8 path while reading audio {}", + file_info.id + )) + })? + .to_string(); + transcribe_audio_file(&path_str, db_client, openai_client).await } // Handle other MIME types as needed _ => Err(AppError::NotFound(file_info.mime_type.clone())), diff --git a/ingestion-pipeline/src/utils/mod.rs b/ingestion-pipeline/src/utils/mod.rs index 462b334..0559323 100644 --- a/ingestion-pipeline/src/utils/mod.rs +++ b/ingestion-pipeline/src/utils/mod.rs @@ -1,6 +1,7 @@ pub mod audio_transcription; pub mod image_parsing; pub mod llm_instructions; +pub mod pdf_ingestion; use common::error::AppError; use std::collections::HashMap; diff --git a/ingestion-pipeline/src/utils/pdf_ingestion.rs b/ingestion-pipeline/src/utils/pdf_ingestion.rs new file mode 100644 index 0000000..62d8b57 --- /dev/null +++ b/ingestion-pipeline/src/utils/pdf_ingestion.rs @@ -0,0 +1,795 @@ +use std::{ + path::{Path, PathBuf}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use async_openai::types::{ + ChatCompletionRequestMessageContentPartImageArgs, + ChatCompletionRequestMessageContentPartTextArgs, ChatCompletionRequestUserMessageArgs, + CreateChatCompletionRequestArgs, ImageDetail, ImageUrlArgs, +}; +use base64::{engine::general_purpose::STANDARD, Engine as _}; +use headless_chrome::{ + protocol::cdp::{Emulation, Page, DOM}, + Browser, +}; +use lopdf::Document; +use serde_json::Value; +use tokio::time::sleep; +use tracing::{debug, warn}; + +use common::{ + error::AppError, + storage::{db::SurrealDbClient, types::system_settings::SystemSettings}, + utils::config::PdfIngestMode, +}; + +const FAST_PATH_MIN_LEN: usize = 150; +const FAST_PATH_MIN_ASCII_RATIO: f64 = 0.7; +const MAX_VISION_PAGES: usize = 50; +const PAGES_PER_VISION_CHUNK: usize = 4; +const MAX_VISION_ATTEMPTS: usize = 2; +const PDF_MARKDOWN_PROMPT: &str = "Convert these PDF pages to clean Markdown. Preserve headings, lists, tables, blockquotes, code fences, and inline formatting. Keep the original reading order, avoid commentary, and do NOT wrap the entire response in a Markdown code block."; +const PDF_MARKDOWN_PROMPT_RETRY: &str = "You must transcribe the provided PDF page images into accurate Markdown. The images are already supplied, so do not respond that you cannot view them. Extract all visible text, tables, and structure, and do NOT wrap the overall response in a Markdown code block."; +const NAVIGATION_RETRY_INTERVAL_MS: u64 = 120; +const NAVIGATION_RETRY_ATTEMPTS: usize = 10; +const MIN_PAGE_IMAGE_BYTES: usize = 1_024; +const DEFAULT_VIEWPORT_WIDTH: u32 = 1_248; // generous width to reduce horizontal clipping +const DEFAULT_VIEWPORT_HEIGHT: u32 = 1_800; // tall enough to capture full page at fit-to-width scale +const DEFAULT_DEVICE_SCALE_FACTOR: f64 = 1.0; +const CANVAS_VIEWPORT_ATTEMPTS: usize = 12; +const CANVAS_VIEWPORT_WAIT_MS: u64 = 200; +const DEBUG_IMAGE_ENV_VAR: &str = "MINNE_PDF_DEBUG_DIR"; + +/// Attempts to extract PDF content, using a fast text layer first and falling back to +/// rendering the document for a vision-enabled LLM when needed. +pub async fn extract_pdf_content( + file_path: &Path, + db: &SurrealDbClient, + client: &async_openai::Client, + mode: &PdfIngestMode, +) -> Result { + let pdf_bytes = tokio::fs::read(file_path).await?; + + if let Some(candidate) = try_fast_path(pdf_bytes.clone()).await? { + return Ok(candidate); + } + + if matches!(mode, PdfIngestMode::Classic) { + return Err(AppError::Processing( + "PDF text extraction failed and LLM-first mode is disabled".into(), + )); + } + + let page_numbers = load_page_numbers(pdf_bytes.clone()).await?; + if page_numbers.is_empty() { + return Err(AppError::Processing("PDF appears to have no pages".into())); + } + + if page_numbers.len() > MAX_VISION_PAGES { + return Err(AppError::Processing(format!( + "PDF has {} pages which exceeds the configured vision processing limit of {}", + page_numbers.len(), + MAX_VISION_PAGES + ))); + } + + let rendered_pages = render_pdf_pages(file_path, &page_numbers).await?; + let combined_markdown = vision_markdown(rendered_pages, db, client).await?; + + Ok(post_process(&combined_markdown)) +} + +/// Runs `pdf-extract` on the PDF bytes and validates the result with simple heuristics. +/// Returns `Ok(None)` when the text layer is missing or too noisy. +async fn try_fast_path(pdf_bytes: Vec) -> Result, AppError> { + let extraction = tokio::task::spawn_blocking(move || { + pdf_extract::extract_text_from_mem(&pdf_bytes).map(|s| s.trim().to_string()) + }) + .await? + .map_err(|err| AppError::Processing(format!("Failed to extract text from PDF: {err}")))?; + + if extraction.is_empty() { + return Ok(None); + } + + if !looks_good_enough(&extraction) { + return Ok(None); + } + + Ok(Some(normalize_fast_text(&extraction))) +} + +/// Parses the PDF structure to discover the available page numbers while keeping work off +/// the async executor. +async fn load_page_numbers(pdf_bytes: Vec) -> Result, AppError> { + let pages = tokio::task::spawn_blocking(move || -> Result, AppError> { + let document = Document::load_mem(&pdf_bytes) + .map_err(|err| AppError::Processing(format!("Failed to parse PDF: {err}")))?; + let mut page_numbers: Vec = document.get_pages().keys().copied().collect(); + page_numbers.sort_unstable(); + Ok(page_numbers) + }) + .await??; + + Ok(pages) +} + +/// Uses the existing headless Chrome dependency to rasterize the requested PDF pages into PNGs. +async fn render_pdf_pages(file_path: &Path, pages: &[u32]) -> Result>, AppError> { + let file_url = url::Url::from_file_path(file_path) + .map_err(|_| AppError::Processing("Unable to construct PDF file URL".into()))?; + + let browser = create_browser()?; + let tab = browser + .new_tab() + .map_err(|err| AppError::Processing(format!("Failed to create Chrome tab: {err}")))?; + + tab.set_default_timeout(Duration::from_secs(10)); + configure_tab(&tab)?; + set_pdf_viewport(&tab)?; + + let mut captures = Vec::with_capacity(pages.len()); + + for (idx, page) in pages.iter().enumerate() { + let target = format!( + "{}#page={}&toolbar=0&statusbar=0&zoom=page-fit", + file_url, page + ); + tab.navigate_to(&target) + .map_err(|err| AppError::Processing(format!("Failed to navigate to PDF page: {err}")))? + .wait_until_navigated() + .map_err(|err| AppError::Processing(format!("Navigation to PDF page failed: {err}")))?; + + let mut loaded = false; + for attempt in 0..NAVIGATION_RETRY_ATTEMPTS { + if tab + .wait_for_element("embed, canvas, body") + .map(|_| ()) + .is_ok() + { + loaded = true; + break; + } + if attempt + 1 < NAVIGATION_RETRY_ATTEMPTS { + sleep(Duration::from_millis(NAVIGATION_RETRY_INTERVAL_MS)).await; + } + } + + if !loaded { + return Err(AppError::Processing( + "Timed out waiting for Chrome to render PDF page".into(), + )); + } + + wait_for_pdf_ready(&tab, *page)?; + tokio::time::sleep(Duration::from_millis(350)).await; + + prepare_pdf_viewer(&tab, *page); + + let mut viewport: Option = None; + for attempt in 0..CANVAS_VIEWPORT_ATTEMPTS { + match canvas_viewport_for_page(&tab, *page) { + Ok(Some(vp)) => { + viewport = Some(vp); + break; + } + Ok(None) => { + if attempt + 1 < CANVAS_VIEWPORT_ATTEMPTS { + tokio::time::sleep(Duration::from_millis(CANVAS_VIEWPORT_WAIT_MS)).await; + } + } + Err(err) => { + warn!(page = *page, error = %err, "Failed to derive canvas viewport"); + break; + } + } + } + + let png = if let Some(clip) = viewport { + match tab.call_method(Page::CaptureScreenshot { + format: Some(Page::CaptureScreenshotFormatOption::Png), + quality: None, + clip: Some(clip), + from_surface: Some(true), + capture_beyond_viewport: Some(true), + optimize_for_speed: Some(false), + }) { + Ok(data) => match STANDARD.decode(data.data) { + Ok(bytes) => bytes, + Err(err) => { + warn!(error = %err, page = *page, "Failed to decode clipped screenshot; falling back to full page capture"); + capture_full_page_png(&tab)? + } + }, + Err(err) => { + warn!(error = %err, page = *page, "Clipped screenshot failed; falling back to full page capture"); + capture_full_page_png(&tab)? + } + } + } else { + warn!( + page = *page, + "Unable to determine canvas viewport; capturing full page" + ); + capture_full_page_png(&tab)? + }; + + debug!( + page = *page, + bytes = png.len(), + page_index = idx, + "Captured PDF page screenshot" + ); + + if is_suspicious_image(png.len()) { + warn!( + page = *page, + bytes = png.len(), + "Screenshot size below threshold; check rendering output" + ); + } + + if let Err(err) = maybe_dump_debug_image(*page, &png).await { + warn!( + page = *page, + error = %err, + "Failed to write debug screenshot to disk" + ); + } + + captures.push(png); + } + + Ok(captures) +} + +/// Launches a headless Chrome instance that respects the existing feature flags. +fn create_browser() -> Result { + #[cfg(feature = "docker")] + { + let options = headless_chrome::LaunchOptionsBuilder::default() + .sandbox(false) + .build() + .map_err(|err| AppError::Processing(format!("Failed to launch Chrome: {err}")))?; + Browser::new(options) + .map_err(|err| AppError::Processing(format!("Failed to start Chrome: {err}"))) + } + #[cfg(not(feature = "docker"))] + { + Browser::default() + .map_err(|err| AppError::Processing(format!("Failed to start Chrome: {err}"))) + } +} + +/// Sends one or more rendered pages to the configured multimodal model and stitches the resulting Markdown chunks together. +async fn vision_markdown( + rendered_pages: Vec>, + db: &SurrealDbClient, + client: &async_openai::Client, +) -> Result { + let settings = SystemSettings::get_current(db).await?; + let prompt = PDF_MARKDOWN_PROMPT; + + debug!( + pages = rendered_pages.len(), + "Preparing vision batches for PDF conversion" + ); + + let mut markdown_sections = Vec::with_capacity(rendered_pages.len()); + + for (batch_idx, chunk) in rendered_pages.chunks(PAGES_PER_VISION_CHUNK).enumerate() { + let total_image_bytes: usize = chunk.iter().map(|bytes| bytes.len()).sum(); + debug!( + batch = batch_idx, + pages = chunk.len(), + bytes = total_image_bytes, + "Encoding PDF images for vision batch" + ); + + let encoded_images: Vec = chunk + .iter() + .enumerate() + .map(|(idx, png_bytes)| { + let encoded = STANDARD.encode(png_bytes); + if encoded.len() < 80 { + warn!( + batch = batch_idx, + page_index = idx, + encoded_bytes = encoded.len(), + "Encoded PDF image payload unusually small" + ); + } + encoded + }) + .collect(); + + let mut batch_markdown: Option = None; + + for attempt in 0..MAX_VISION_ATTEMPTS { + let prompt_text = prompt_for_attempt(attempt, prompt); + + let mut content_parts = Vec::with_capacity(encoded_images.len() + 1); + content_parts.push( + ChatCompletionRequestMessageContentPartTextArgs::default() + .text(prompt_text) + .build()? + .into(), + ); + + for encoded in &encoded_images { + let image_url = format!("data:image/png;base64,{}", encoded); + content_parts.push( + ChatCompletionRequestMessageContentPartImageArgs::default() + .image_url( + ImageUrlArgs::default() + .url(image_url) + .detail(ImageDetail::High) + .build()?, + ) + .build()? + .into(), + ); + } + + let request = CreateChatCompletionRequestArgs::default() + .model(settings.image_processing_model.clone()) + .temperature(0.0) + .messages([ChatCompletionRequestUserMessageArgs::default() + .content(content_parts) + .build()? + .into()]) + .max_tokens(16400_u32) + .build()?; + + let response = client.chat().create(request).await?; + let Some(choice) = response.choices.first() else { + warn!( + batch = batch_idx, + attempt, "Vision response contained zero choices" + ); + continue; + }; + + let Some(content) = choice.message.content.as_ref() else { + warn!( + batch = batch_idx, + attempt, "Vision response missing content field" + ); + continue; + }; + + debug!( + batch = batch_idx, + attempt, + response_chars = content.len(), + "Received Markdown response for PDF batch" + ); + + let preview: String = if content.len() > 500 { + let mut snippet = content.chars().take(500).collect::(); + snippet.push('…'); + snippet + } else { + content.clone() + }; + debug!(batch = batch_idx, attempt, preview = %preview, "Vision response content preview"); + + if is_low_quality_response(content) { + warn!( + batch = batch_idx, + attempt, "Vision model returned low quality response" + ); + if attempt + 1 == MAX_VISION_ATTEMPTS { + return Err(AppError::Processing( + "Vision model failed to transcribe PDF page contents".into(), + )); + } + continue; + } + + batch_markdown = Some(content.trim().to_string()); + break; + } + + if let Some(markdown) = batch_markdown { + markdown_sections.push(markdown); + } else { + return Err(AppError::Processing( + "Vision model did not return usable Markdown".into(), + )); + } + } + + Ok(markdown_sections.join("\n\n")) +} + +/// Heuristic that determines whether the fast-path text looks like well-formed prose. +fn looks_good_enough(text: &str) -> bool { + if text.len() < FAST_PATH_MIN_LEN { + return false; + } + + let total_chars = text.chars().count() as f64; + if total_chars == 0.0 { + return false; + } + + let ascii_chars = text.chars().filter(|c| c.is_ascii()).count() as f64; + let ascii_ratio = ascii_chars / total_chars; + if ascii_ratio < FAST_PATH_MIN_ASCII_RATIO { + return false; + } + + let letters = text.chars().filter(|c| c.is_alphabetic()).count() as f64; + let letter_ratio = letters / total_chars; + letter_ratio > 0.3 +} + +/// Normalizes fast-path output so downstream consumers see consistent Markdown. +fn normalize_fast_text(text: &str) -> String { + reflow_markdown(text) +} + +/// Cleans, trims, and reflows Markdown created by the LLM path. +fn post_process(markdown: &str) -> String { + let cleaned = markdown.replace('\r', ""); + let trimmed = cleaned.trim(); + reflow_markdown(trimmed) +} + +/// Joins hard-wrapped paragraph text while preserving structural Markdown lines. +fn reflow_markdown(input: &str) -> String { + let mut paragraphs = Vec::new(); + let mut buffer: Vec = Vec::new(); + + for line in input.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() { + if !buffer.is_empty() { + paragraphs.push(buffer.join(" ")); + buffer.clear(); + } + continue; + } + + if is_structural_line(trimmed) { + if !buffer.is_empty() { + paragraphs.push(buffer.join(" ")); + buffer.clear(); + } + paragraphs.push(trimmed.to_string()); + continue; + } + + buffer.push(trimmed.to_string()); + } + + if !buffer.is_empty() { + paragraphs.push(buffer.join(" ")); + } + + paragraphs.join("\n\n") +} + +/// Detects whether a line is structural Markdown that should remain on its own. +fn is_structural_line(line: &str) -> bool { + let lowered = line.to_ascii_lowercase(); + line.starts_with('#') + || line.starts_with('-') + || line.starts_with('*') + || line.starts_with('>') + || line.starts_with("```") + || line.starts_with('~') + || line.starts_with("| ") + || line.starts_with("+-") + || lowered + .chars() + .next() + .map(|c| c.is_ascii_digit()) + .unwrap_or(false) + && lowered.contains('.') +} + +fn debug_dump_directory() -> Option { + std::env::var(DEBUG_IMAGE_ENV_VAR) + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + .map(PathBuf::from) +} + +fn configure_tab(tab: &headless_chrome::Tab) -> Result<(), AppError> { + tab.call_method(Emulation::SetDefaultBackgroundColorOverride { + color: Some(DOM::RGBA { + r: 255, + g: 255, + b: 255, + a: Some(1.0), + }), + }) + .map_err(|err| { + AppError::Processing(format!("Failed to configure Chrome page background: {err}")) + })?; + + Ok(()) +} + +fn set_pdf_viewport(tab: &headless_chrome::Tab) -> Result<(), AppError> { + tab.call_method(Emulation::SetDeviceMetricsOverride { + width: DEFAULT_VIEWPORT_WIDTH, + height: DEFAULT_VIEWPORT_HEIGHT, + device_scale_factor: DEFAULT_DEVICE_SCALE_FACTOR, + mobile: false, + scale: None, + screen_width: Some(DEFAULT_VIEWPORT_WIDTH), + screen_height: Some(DEFAULT_VIEWPORT_HEIGHT), + position_x: None, + position_y: None, + dont_set_visible_size: Some(false), + screen_orientation: None, + viewport: None, + display_feature: None, + device_posture: None, + }) + .map_err(|err| AppError::Processing(format!("Failed to configure Chrome viewport: {err}")))?; + + tab.call_method(Emulation::SetVisibleSize { + width: DEFAULT_VIEWPORT_WIDTH, + height: DEFAULT_VIEWPORT_HEIGHT, + }) + .map_err(|err| AppError::Processing(format!("Failed to apply Chrome visible size: {err}")))?; + + Ok(()) +} + +fn wait_for_pdf_ready( + tab: &headless_chrome::Tab, + page_number: u32, +) -> Result, AppError> { + let embed_selector = "embed[type='application/pdf']"; + let element = tab + .wait_for_element_with_custom_timeout(embed_selector, Duration::from_secs(8)) + .or_else(|_| tab.wait_for_element_with_custom_timeout("embed", Duration::from_secs(8))) + .map_err(|err| AppError::Processing(format!("Timed out waiting for PDF content: {err}")))?; + + if let Err(err) = element.scroll_into_view() { + debug!("Failed to scroll PDF element into view: {err}"); + } + + debug!(page = page_number, "PDF viewer element located"); + + Ok(element) +} + +fn prepare_pdf_viewer(tab: &headless_chrome::Tab, page_number: u32) { + let script = format!( + r#"(function() {{ + const embed = document.querySelector('embed[type="application/pdf"]') || document.querySelector('embed'); + if (!embed || !embed.shadowRoot) return false; + const viewer = embed.shadowRoot.querySelector('pdf-viewer'); + if (!viewer || !viewer.shadowRoot) return false; + const app = viewer.shadowRoot.querySelector('viewer-app'); + if (app && app.shadowRoot) {{ + const toolbar = app.shadowRoot.querySelector('#toolbar'); + if (toolbar) {{ toolbar.style.display = 'none'; }} + }} + const page = viewer.shadowRoot.querySelector('viewer-page:nth-of-type({page})'); + if (page && page.scrollIntoView) {{ + page.scrollIntoView({{ block: 'start', inline: 'center' }}); + }} + const canvas = viewer.shadowRoot.querySelector('canvas[aria-label="Page {page}"]'); + return !!canvas; + }})()"#, + page = page_number + ); + + match tab.evaluate(&script, false) { + Ok(result) => { + let ready = result + .value + .as_ref() + .and_then(Value::as_bool) + .unwrap_or(false); + debug!(page = page_number, ready, "Prepared PDF viewer page"); + } + Err(err) => { + debug!(page = page_number, error = %err, "Unable to run PDF viewer preparation script"); + } + } +} + +fn canvas_viewport_for_page( + tab: &headless_chrome::Tab, + page_number: u32, +) -> Result, AppError> { + let script = format!( + r#"(function() {{ + const embed = document.querySelector('embed[type="application/pdf"]') || document.querySelector('embed'); + if (!embed || !embed.shadowRoot) return null; + const viewer = embed.shadowRoot.querySelector('pdf-viewer'); + if (!viewer || !viewer.shadowRoot) return null; + const canvas = viewer.shadowRoot.querySelector('canvas[aria-label="Page {page}"]'); + if (!canvas) return null; + const rect = canvas.getBoundingClientRect(); + return {{ x: rect.x, y: rect.y, width: rect.width, height: rect.height }}; + }})()"#, + page = page_number + ); + + let result = tab + .evaluate(&script, false) + .map_err(|err| AppError::Processing(format!("Failed to inspect PDF canvas: {err}")))?; + + let Some(value) = result.value else { + return Ok(None); + }; + + if value.is_null() { + return Ok(None); + } + + let x = value + .get("x") + .and_then(Value::as_f64) + .unwrap_or_default() + .max(0.0); + let y = value + .get("y") + .and_then(Value::as_f64) + .unwrap_or_default() + .max(0.0); + let width = value + .get("width") + .and_then(Value::as_f64) + .unwrap_or_default(); + let height = value + .get("height") + .and_then(Value::as_f64) + .unwrap_or_default(); + + if width <= 0.0 || height <= 0.0 { + return Ok(None); + } + + debug!( + page = page_number, + x, y, width, height, "Derived canvas viewport" + ); + + Ok(Some(Page::Viewport { + x, + y, + width, + height, + scale: 1.0, + })) +} + +fn capture_full_page_png(tab: &headless_chrome::Tab) -> Result, AppError> { + let screenshot = tab + .call_method(Page::CaptureScreenshot { + format: Some(Page::CaptureScreenshotFormatOption::Png), + quality: None, + clip: None, + from_surface: Some(true), + capture_beyond_viewport: Some(true), + optimize_for_speed: Some(false), + }) + .map_err(|err| { + AppError::Processing(format!("Failed to capture PDF page (fallback): {err}")) + })?; + + STANDARD.decode(screenshot.data).map_err(|err| { + AppError::Processing(format!("Failed to decode PDF screenshot (fallback): {err}")) + }) +} + +fn is_suspicious_image(len: usize) -> bool { + len < MIN_PAGE_IMAGE_BYTES +} + +async fn maybe_dump_debug_image(page_index: u32, bytes: &[u8]) -> Result<(), AppError> { + if let Some(dir) = debug_dump_directory() { + tokio::fs::create_dir_all(&dir).await?; + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis(); + let file_path = dir.join(format!("page-{page_index:04}-{timestamp}.png")); + tokio::fs::write(&file_path, bytes).await?; + debug!(?file_path, size = bytes.len(), "Wrote PDF debug screenshot"); + } + Ok(()) +} + +fn is_low_quality_response(content: &str) -> bool { + let trimmed = content.trim(); + if trimmed.is_empty() { + return true; + } + let lowered = trimmed.to_ascii_lowercase(); + lowered.contains("unable to") || lowered.contains("cannot") +} + +fn prompt_for_attempt(attempt: usize, base_prompt: &str) -> &str { + if attempt == 0 { + base_prompt + } else { + PDF_MARKDOWN_PROMPT_RETRY + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_looks_good_enough_short_text() { + assert!(!looks_good_enough("too short")); + } + + #[test] + fn test_looks_good_enough_ascii_text() { + let text = "This is a reasonably long ASCII text that should pass the heuristic. \ + It contains multiple sentences and a decent amount of letters to satisfy the threshold."; + assert!(looks_good_enough(text)); + } + + #[test] + fn test_reflow_markdown_preserves_lists() { + let input = "Item one\nItem two\n\n- Bullet\n- Another"; + let output = reflow_markdown(input); + assert!(output.contains("Item one Item two")); + assert!(output.contains("- Bullet")); + } + + #[test] + fn test_debug_dump_directory_env_var() { + std::env::remove_var(DEBUG_IMAGE_ENV_VAR); + assert!(debug_dump_directory().is_none()); + + std::env::set_var(DEBUG_IMAGE_ENV_VAR, "/tmp/minne_pdf_debug"); + let dir = debug_dump_directory().expect("expected debug directory"); + assert_eq!(dir, PathBuf::from("/tmp/minne_pdf_debug")); + + std::env::remove_var(DEBUG_IMAGE_ENV_VAR); + } + + #[test] + fn test_is_suspicious_image_threshold() { + assert!(is_suspicious_image(0)); + assert!(is_suspicious_image(MIN_PAGE_IMAGE_BYTES - 1)); + assert!(!is_suspicious_image(MIN_PAGE_IMAGE_BYTES + 1)); + } + + #[test] + fn test_is_low_quality_response_detection() { + assert!(is_low_quality_response("")); + assert!(is_low_quality_response("I'm unable to help.")); + assert!(is_low_quality_response("I cannot read this.")); + assert!(!is_low_quality_response("# Heading\nValid content")); + } + + #[test] + fn test_prompt_for_attempt_variants() { + assert_eq!( + prompt_for_attempt(0, PDF_MARKDOWN_PROMPT), + PDF_MARKDOWN_PROMPT + ); + assert_eq!( + prompt_for_attempt(1, PDF_MARKDOWN_PROMPT), + PDF_MARKDOWN_PROMPT_RETRY + ); + assert_eq!( + prompt_for_attempt(5, PDF_MARKDOWN_PROMPT), + PDF_MARKDOWN_PROMPT_RETRY + ); + } + + #[test] + fn test_markdown_prompts_discourage_code_blocks() { + assert!(!PDF_MARKDOWN_PROMPT.contains("```")); + assert!(!PDF_MARKDOWN_PROMPT_RETRY.contains("```")); + } +}