dongler-core 0.3.14

Rust-native PDF and document extraction core for Markdown, LaTeX, and JSON output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
pub mod archive;
pub mod csv;
pub mod engine;
pub mod error;
pub mod format;
pub mod image;
pub mod ir;
pub mod json;
pub mod openxml;
pub mod pdf;
pub mod render;
pub mod source;
pub mod textual;

use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

pub use archive::ArchiveEngine;
pub use csv::CsvEngine;
pub use engine::{ExtractionEngine, PlainTextEngine};
pub use error::{DonglerError, Result};
pub use format::{ExtractionStatus, InputFormat};
pub use image::ImageEngine;
pub use ir::{
    Asset, BBox, BatchResult, Block, BlockKind, Confidence, Document, ExtractOptions, FigureBlock,
    ImageObject, Line, Metadata, Page, Provenance, Route, SourceAnchor, Span, TableBlock, TableCell,
    TextBlock, TextSource, Warning,
};
pub use json::JsonEngine;
pub use openxml::OpenXmlEngine;
pub use pdf::PdfEngine;
pub use render::{JsonRenderer, LatexRenderer, MarkdownRenderer, Renderer};
pub use source::{
    FormatSourceLoader, ImageSourceLoader, PdfSourceLoader, Source, SourceLoader, TextSourceLoader,
};
pub use textual::{EmailEngine, HtmlEngine, XmlEngine};

impl Document {
    pub fn to_markdown(&self) -> Result<String> {
        MarkdownRenderer.render(self)
    }

    pub fn to_json(&self) -> Result<String> {
        JsonRenderer.render(self)
    }

    pub fn to_latex(&self) -> Result<String> {
        LatexRenderer.render(self)
    }
}

pub fn parse_text(text: &str) -> Result<Document> {
    PlainTextEngine.extract(&Source::from_text(text))
}

pub fn load_path(path: impl AsRef<Path>) -> Result<Document> {
    load_path_with_options(path, ExtractOptions::default())
}

pub fn load_path_with_options(path: impl AsRef<Path>, options: ExtractOptions) -> Result<Document> {
    let path = path.as_ref();
    let format = InputFormat::detect_path(path)?;
    if format.extraction_status() == ExtractionStatus::Planned {
        return Err(DonglerError::planned_format(format.as_str()));
    }

    let source = load_source(format, path)?;
    let mut document = engine_extract(format, &source)?;

    if ocr_fallback_enabled() {
        apply_ocr_fallback(&mut document);
    }
    apply_extract_options(&mut document, &options);
    Ok(document)
}

/// Read a source from disk using the loader appropriate for `format`.
fn load_source(format: InputFormat, path: &Path) -> Result<Source> {
    match format {
        InputFormat::Text => TextSourceLoader.load(path),
        InputFormat::Pdf => PdfSourceLoader.load(path),
        InputFormat::Image => ImageSourceLoader.load(path),
        _ => FormatSourceLoader::new(format).load(path),
    }
}

/// Dispatch an in-memory source to the engine for `format`.
///
/// This is the filesystem-free heart of extraction, shared by the path-based
/// loaders and the byte-based [`extract_bytes`] entry point used by wasm.
fn engine_extract(format: InputFormat, source: &Source) -> Result<Document> {
    match format {
        InputFormat::Text => PlainTextEngine.extract(source),
        InputFormat::Pdf => PdfEngine.extract(source),
        InputFormat::Image => ImageEngine.extract(source),
        InputFormat::Archive => ArchiveEngine.extract(source),
        InputFormat::Word
        | InputFormat::Excel
        | InputFormat::Presentation
        | InputFormat::OpenDocument => OpenXmlEngine.extract(source),
        InputFormat::Html => HtmlEngine.extract(source),
        InputFormat::Email => EmailEngine.extract(source),
        InputFormat::Xml => XmlEngine.extract(source),
        InputFormat::Json => JsonEngine.extract(source),
        InputFormat::Csv => CsvEngine.extract(source),
        InputFormat::LegacyWord
        | InputFormat::LegacyExcel
        | InputFormat::LegacyPresentation
        | InputFormat::LegacyEmail => Err(DonglerError::planned_format(format.as_str())),
    }
}

/// Extract a document from in-memory bytes, detecting the format from
/// `filename` (its extension only — the file is never read from disk).
///
/// This is the primary entry point for environments without a filesystem,
/// such as WebAssembly. OCR fallback is intentionally not applied here because
/// it relies on spawning external processes.
pub fn extract_bytes(bytes: &[u8], filename: &str) -> Result<Document> {
    extract_bytes_with_options(bytes, filename, ExtractOptions::default())
}

pub fn extract_bytes_with_options(
    bytes: &[u8],
    filename: &str,
    options: ExtractOptions,
) -> Result<Document> {
    let format = InputFormat::detect_path(filename)?;
    if format.extraction_status() == ExtractionStatus::Planned {
        return Err(DonglerError::planned_format(format.as_str()));
    }

    let source = Source::from_bytes_for_format(bytes, filename, format)?;
    let mut document = engine_extract(format, &source)?;
    apply_extract_options(&mut document, &options);
    Ok(document)
}

#[derive(Debug, Clone)]
struct OcrFallbackConfig {
    renderer: String,
    engine: String,
    temp_dir: PathBuf,
}

fn ocr_fallback_enabled() -> bool {
    matches!(
        std::env::var("DONGLER_OCR_FALLBACK")
            .unwrap_or_default()
            .to_ascii_lowercase()
            .as_str(),
        "1" | "true" | "yes" | "on"
    )
}

fn apply_ocr_fallback(document: &mut Document) {
    if document.metadata.format != "pdf" {
        return;
    }
    let Some(source_path) = document.metadata.source.as_deref().map(PathBuf::from) else {
        return;
    };
    if !source_path.exists() {
        return;
    }
    let config = ocr_fallback_config();
    let mut changed = false;

    for page in &mut document.pages {
        if !page_needs_ocr_fallback(page) {
            continue;
        }

        match ocr_pdf_page(&source_path, page.number, &config) {
            Ok(Some(text)) => {
                insert_ocr_text_block(page, text);
                changed = true;
            }
            Ok(None) => {}
            Err(message) => page.warnings.push(Warning {
                code: "ocr.fallback".to_owned(),
                severity: "warning".to_owned(),
                message,
                source_anchor: Some(SourceAnchor {
                    page_number: page.number,
                    pdf_object_ids: Vec::new(),
                    bbox: page.bbox,
                    extraction_method: "ocr_fallback".to_owned(),
                }),
            }),
        }
    }

    if changed {
        refresh_document_counts(document);
    }
}

fn ocr_fallback_config() -> OcrFallbackConfig {
    OcrFallbackConfig {
        renderer: std::env::var("DONGLER_PDF_RENDERER").unwrap_or_else(|_| "pdftoppm".to_owned()),
        engine: std::env::var("DONGLER_OCR_ENGINE").unwrap_or_else(|_| "tesseract".to_owned()),
        temp_dir: std::env::var("DONGLER_OCR_TEMP_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                std::env::current_dir()
                    .unwrap_or_else(|_| std::env::temp_dir())
                    .join("target")
                    .join("dongler-ocr")
            }),
    }
}

fn page_needs_ocr_fallback(page: &Page) -> bool {
    !page.images.is_empty()
        && !page.blocks.iter().any(|block| match block {
            Block::Text(text) => !text.text.trim().is_empty(),
            Block::Table(table) => {
                table.headers.iter().any(|value| !value.trim().is_empty())
                    || table
                        .rows
                        .iter()
                        .flatten()
                        .any(|value| !value.trim().is_empty())
            }
            Block::Figure(_) => false,
        })
}

fn ocr_pdf_page(
    source_path: &Path,
    page_number: usize,
    config: &OcrFallbackConfig,
) -> std::result::Result<Option<String>, String> {
    fs::create_dir_all(&config.temp_dir).map_err(|error| {
        format!(
            "could not create OCR temp dir {}: {error}",
            config.temp_dir.display()
        )
    })?;
    let prefix = config.temp_dir.join(format!(
        "page-{}-{}-{}",
        std::process::id(),
        page_number,
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or_default()
    ));
    let image_path = prefix.with_extension("png");
    let page = page_number.to_string();
    let render_output = Command::new(&config.renderer)
        .args([
            "-f",
            page.as_str(),
            "-l",
            page.as_str(),
            "-r",
            "200",
            "-png",
            "-singlefile",
        ])
        .arg(source_path)
        .arg(&prefix)
        .output()
        .map_err(|error| format!("could not run PDF renderer {}: {error}", config.renderer))?;

    if !render_output.status.success() {
        let stderr = String::from_utf8_lossy(&render_output.stderr);
        return Err(format!(
            "PDF renderer {} failed: {}",
            config.renderer,
            stderr.trim()
        ));
    }

    let ocr_output = Command::new(&config.engine)
        .arg(&image_path)
        .arg("stdout")
        .args(["--psm", "6"])
        .output()
        .map_err(|error| format!("could not run OCR engine {}: {error}", config.engine));
    let _ = fs::remove_file(&image_path);

    let ocr_output = ocr_output?;
    if !ocr_output.status.success() {
        let stderr = String::from_utf8_lossy(&ocr_output.stderr);
        return Err(format!(
            "OCR engine {} failed: {}",
            config.engine,
            stderr.trim()
        ));
    }

    let text = normalize_ocr_text(&String::from_utf8_lossy(&ocr_output.stdout));
    Ok((!text.is_empty()).then_some(text))
}

fn normalize_ocr_text(text: &str) -> String {
    text.lines()
        .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

fn insert_ocr_text_block(page: &mut Page, text: String) {
    let bbox = page.bbox;
    page.blocks.insert(
        0,
        Block::Text(TextBlock {
            text: text.clone(),
            kind: "ocr_text".to_owned(),
            bbox,
            lines: vec![Line {
                text: text.clone(),
                bbox,
                spans: vec![Span {
                    text,
                    bbox,
                    font: None,
                    size: None,
                    bold: false,
                    italic: false,
                }],
            }],
            source_anchors: vec![SourceAnchor {
                page_number: page.number,
                pdf_object_ids: Vec::new(),
                bbox,
                extraction_method: "ocr_fallback".to_owned(),
            }],
            confidence: Some(Confidence {
                score: 0.55,
                calibrated: false,
            }), ..Default::default()
        }),
    );
}

fn apply_extract_options(document: &mut Document, options: &ExtractOptions) {
    if options.suppress_headers_footers {
        suppress_repeated_headers_footers(document);
    }

    if !options.include_geometry {
        for page in &mut document.pages {
            page.bbox = None;
            page.width = None;
            page.height = None;
            for block in &mut page.blocks {
                match block {
                    Block::Text(text) => {
                        text.bbox = None;
                        text.lines.clear();
                        for anchor in &mut text.source_anchors {
                            anchor.bbox = None;
                        }
                    }
                    Block::Table(table) => {
                        table.bbox = None;
                        for cell in &mut table.cells {
                            cell.bbox = None;
                        }
                        for anchor in &mut table.source_anchors {
                            anchor.bbox = None;
                        }
                    }
                    Block::Figure(figure) => {
                        figure.bbox = None;
                        for anchor in &mut figure.source_anchors {
                            anchor.bbox = None;
                        }
                    }
                }
            }
            for image in &mut page.images {
                image.bbox = None;
            }
            for asset in &mut page.assets {
                asset.bbox = None;
            }
        }
    }

    if !options.include_assets {
        document.assets.clear();
        for page in &mut document.pages {
            page.assets.clear();
            page.images.clear();
        }
    }
}

fn suppress_repeated_headers_footers(document: &mut Document) {
    if document.pages.len() < 2 {
        return;
    }

    let mut occurrences = HashMap::new();
    for page in &document.pages {
        let mut seen_on_page = HashSet::new();
        for block in &page.blocks {
            if let Some(key) = header_footer_key(page.height, block) {
                seen_on_page.insert(key);
            }
        }
        for key in seen_on_page {
            *occurrences.entry(key).or_insert(0usize) += 1;
        }
    }

    let minimum_pages = 2.max((document.pages.len() + 1) / 2);
    let repeated = occurrences
        .into_iter()
        .filter_map(|(key, count)| (count >= minimum_pages).then_some(key))
        .collect::<HashSet<_>>();
    if repeated.is_empty() {
        return;
    }

    for page in &mut document.pages {
        let page_height = page.height;
        page.blocks.retain(|block| {
            header_footer_key(page_height, block)
                .map(|key| !repeated.contains(&key))
                .unwrap_or(true)
        });
    }
    refresh_document_counts(document);
}

fn header_footer_key(page_height: Option<f32>, block: &Block) -> Option<String> {
    let height = page_height?;
    if height <= 0.0 {
        return None;
    }

    let bbox = block_bbox(block)?;
    let center_y = bbox.y + bbox.height / 2.0;
    let margin = (height * 0.12).max(48.0);
    let band = if center_y >= height - margin {
        "top"
    } else if center_y <= margin {
        "bottom"
    } else {
        return None;
    };

    let text = normalize_repeated_margin_text(&block_text(block));
    (!text.is_empty()).then(|| format!("{band}:{text}"))
}

fn block_bbox(block: &Block) -> Option<BBox> {
    match block {
        Block::Text(text) => text.bbox,
        Block::Table(table) => table.bbox,
        Block::Figure(figure) => figure.bbox,
    }
}

fn normalize_repeated_margin_text(text: &str) -> String {
    let mut output = String::new();
    let mut last_was_space = true;
    for character in text.chars().flat_map(char::to_lowercase) {
        if character.is_ascii_digit() {
            if !output.ends_with('#') {
                output.push('#');
            }
            last_was_space = false;
        } else if character.is_whitespace() {
            if !last_was_space {
                output.push(' ');
                last_was_space = true;
            }
        } else {
            output.push(character);
            last_was_space = false;
        }
    }
    output.trim().to_owned()
}

fn refresh_document_counts(document: &mut Document) {
    let mut character_count = 0;
    let mut word_count = 0;
    let mut block_count = 0;

    for page in &document.pages {
        for block in &page.blocks {
            let text = block_text(block);
            character_count += text.chars().count();
            word_count += text.split_whitespace().count();
            block_count += 1;
        }
    }

    document.metadata.character_count = character_count;
    document.metadata.word_count = word_count;
    document.metadata.block_count = block_count;
}

fn block_text(block: &Block) -> String {
    match block {
        Block::Text(text) => text.text.clone(),
        Block::Table(table) => {
            let mut rows = Vec::new();
            if !table.headers.is_empty() {
                rows.push(table.headers.join(" "));
            }
            rows.extend(table.rows.iter().map(|row| row.join(" ")));
            rows.join("\n")
        }
        Block::Figure(figure) => figure.caption.clone().unwrap_or_default(),
    }
}

pub fn load_many<I, P>(paths: I) -> Vec<BatchResult>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    paths
        .into_iter()
        .map(|path| {
            let path = path.as_ref();
            let path_string = path.display().to_string();

            match load_path(path) {
                Ok(document) => BatchResult {
                    path: path_string,
                    ok: true,
                    document: Some(document),
                    error: None,
                },
                Err(error) => BatchResult {
                    path: path_string,
                    ok: false,
                    document: None,
                    error: Some(error.to_string()),
                },
            }
        })
        .collect()
}

pub fn to_markdown(text: &str) -> Result<String> {
    let document = parse_text(text)?;
    document.to_markdown()
}

pub fn to_json(text: &str) -> Result<String> {
    let document = parse_text(text)?;
    document.to_json()
}

pub fn to_latex(text: &str) -> Result<String> {
    let document = parse_text(text)?;
    document.to_latex()
}

pub fn detect_format(path: &str) -> Result<String> {
    Ok(InputFormat::detect_path(path)?.as_str().to_owned())
}