A fast, helpful, and open-source document parser
add proper ocr download support
Logan Markewichc20feb1ccc51
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 18f9052..45e2457 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -80,6 +80,27 @@ jobs:./target/debug/lit --version./target/debug/lit parse demo/docs/apple-10k-2024.pdf --no-ocr --max-pages 1 -q | head -5+ - name: OCR smoke test (runtime tessdata download)+ shell: bash+ run: |+ # Wipe any tessdata that tesseract-rs/build.rs downloaded during+ # `cargo build`, so the parse exercises the runtime first-use+ # download path (the code path that npm/pip prebuilt users hit).+ rm -rf "$HOME/Library/Application Support/tesseract-rs" \+ "$HOME/.tesseract-rs" \+ "${APPDATA:-}/tesseract-rs" 2>/dev/null || true++ LIT=./target/debug/lit+ [ -f "$LIT.exe" ] && LIT="$LIT.exe"+ "$LIT" parse demo/docs/long_tiny_text.pdf --max-pages 1 -q -o ocr-out.txt++ # If OCR ran, page 1 has substantial text beyond just the+ # "--- Page 1 ---" header (~16 bytes). A tessdata-load failure+ # surfaces as systemic OCR failure and an empty/tiny output.+ size=$(wc -c < ocr-out.txt)+ echo "OCR output size: $size bytes"+ test "$size" -gt 200+# Test that docker buildsbuild-docker-image:runs-on: ubuntu-latestdiff --git a/crates/liteparse/src/ocr/tesseract.rs b/crates/liteparse/src/ocr/tesseract.rsindex dfcaff0..b1ee979 100644--- a/crates/liteparse/src/ocr/tesseract.rs+++ b/crates/liteparse/src/ocr/tesseract.rs@@ -1,8 +1,11 @@+use std::path::{Path, PathBuf};use std::pin::Pin;use super::{OcrEngine, OcrOptions, OcrResult};use tesseract_rs::{TessPageIteratorLevel, TesseractAPI};+const TESSDATA_BASE_URL: &str = "https://github.com/tesseract-ocr/tessdata_best/raw/main";+pub struct TesseractOcrEngine {tessdata_path: Option<String>,}@@ -63,15 +66,9 @@ impl OcrEngine for TesseractOcrEngine {.clone().or_else(|| std::env::var("TESSDATA_PREFIX").ok());- match &tessdata_path {- Some(path) => api.init(path, language)?,- None => {- // tesseract-rs with build-tesseract downloads eng.traineddata automatically- // and caches it; use its default path- let default_path = default_tessdata_dir();- api.init(&default_path, language)?;- }- }+ let resolved_path = tessdata_path.unwrap_or_else(default_tessdata_dir);+ ensure_traineddata(Path::new(&resolved_path), language).await?;+ api.init(&resolved_path, language)?;// Set image from raw RGB bytes (3 bytes per pixel)let bytes_per_pixel = 3;@@ -117,7 +114,9 @@ impl OcrEngine for TesseractOcrEngine {}}-/// Default tessdata directory used by tesseract-rs build-tesseract feature.+/// Default tessdata directory. Matches the locations used by tesseract-rs's+/// build-tesseract feature so any traineddata it downloaded at build time is+/// also picked up here.fn default_tessdata_dir() -> String {#[cfg(target_os = "macos")]{@@ -131,9 +130,66 @@ fn default_tessdata_dir() -> String {return format!("{}/.tesseract-rs/tessdata", home);}}+ #[cfg(target_os = "windows")]+ {+ if let Some(base) = std::env::var("APPDATA").ok().or_else(|| {+ std::env::var("USERPROFILE")+ .ok()+ .map(|p| format!("{}\\AppData\\Roaming", p))+ }) {+ return format!("{}\\tesseract-rs\\tessdata", base);+ }+ }"tessdata".to_string()}+/// Ensure `<lang>.traineddata` exists in `dir`. If missing, downloads it from+/// the upstream `tessdata_best` repo — mirroring tesseract.js's first-use+/// download behavior. Concurrent calls are safe via an atomic rename.+async fn ensure_traineddata(+ dir: &Path,+ language: &str,+) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ let filename = format!("{}.traineddata", language);+ let final_path: PathBuf = dir.join(&filename);+ if final_path.exists() {+ return Ok(());+ }++ tokio::fs::create_dir_all(dir).await?;++ let url = format!("{}/{}", TESSDATA_BASE_URL, filename);+ let response = reqwest::get(&url).await?;+ if !response.status().is_success() {+ return Err(format!(+ "failed to download tessdata for language \"{}\" from {}: HTTP {}",+ language,+ url,+ response.status()+ )+ .into());+ }+ let bytes = response.bytes().await?;++ // Write to a temp file in the same directory, then atomically rename.+ // This makes concurrent first-use safe: whichever rename lands last wins,+ // and partial files never appear at the final path.+ let tmp_path = dir.join(format!(+ "{}.traineddata.tmp.{}",+ language,+ std::process::id()+ ));+ tokio::fs::write(&tmp_path, &bytes).await?;+ if let Err(e) = tokio::fs::rename(&tmp_path, &final_path).await {+ // If another task beat us to it, the file exists — that's fine.+ let _ = tokio::fs::remove_file(&tmp_path).await;+ if !final_path.exists() {+ return Err(e.into());+ }+ }+ Ok(())+}+#[cfg(test)]mod tests {use super::*;@@ -171,4 +227,27 @@ mod tests {let d = default_tessdata_dir();assert!(!d.is_empty());}++ #[cfg(target_os = "windows")]+ #[test]+ fn test_default_tessdata_dir_windows_uses_appdata() {+ // Sanity check the Windows path uses backslashes and includes tesseract-rs/tessdata.+ let d = default_tessdata_dir();+ assert!(+ d.ends_with("\\tesseract-rs\\tessdata"),+ "unexpected default path on windows: {}",+ d+ );+ }++ #[tokio::test]+ async fn test_ensure_traineddata_skips_when_present() {+ let tmp = tempfile::tempdir().unwrap();+ let path = tmp.path().join("xyz.traineddata");+ std::fs::write(&path, b"stub").unwrap();+ // Should be a no-op (no network); language "xyz" doesn't exist upstream+ // so any actual download attempt would fail.+ ensure_traineddata(tmp.path(), "xyz").await.unwrap();+ assert_eq!(std::fs::read(&path).unwrap(), b"stub");+ }}diff --git a/demo/docs/long_tiny_text.pdf b/demo/docs/long_tiny_text.pdfnew file mode 100644index 0000000..b6845d6Binary files /dev/null and b/demo/docs/long_tiny_text.pdf differ