pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
//! `pdfsift blocks`: debug view of the layout stages (characters → words → lines → blocks).

use std::path::Path;

use anyhow::{Context, Result};
use pdfium_render::prelude::*;

use crate::layout::furniture::Reason;
use crate::layout::{self, Block, Char, CharKind, Region, extract};
use crate::{engine, tags};

pub struct Options {
    /// 0-based page indices; None = all.
    pub pages: Option<Vec<PdfPageIndex>>,
    /// Also print every line with its words and gaps.
    pub words: bool,
    /// Print the raw characters instead of blocks.
    pub chars: bool,
}

pub fn run(file: &Path, opts: &Options) -> Result<()> {
    let pdfium = engine::load()?;
    let doc = pdfium
        .load_pdf_from_file(file, None)
        .with_context(|| format!("cannot open {}", file.display()))?;
    // Second, raw handle for marked content (tags.rs); without it chars carry no marks.
    let raw_doc = tags::RawDoc::open(doc.bindings(), &file.to_string_lossy());
    outln!("== document: {}", file.display());
    let indices: Vec<PdfPageIndex> = match &opts.pages {
        Some(p) => p.clone(),
        None => (0..doc.pages().len()).collect(),
    };
    // Furniture detection compares pages, so the whole document is analysed even when
    // only some pages are printed.
    let analyzed = if opts.chars {
        Vec::new()
    } else {
        layout::analyze_document(&doc, raw_doc.as_ref())
    };
    for idx in indices {
        let Ok(page) = doc.pages().get(idx) else {
            outln!(
                "
== page {} does not exist",
                idx + 1
            );
            continue;
        };
        let (w, h) = (page.width().value, page.height().value);
        outln!(
            "
== page {} ({w:.0} x {h:.0} pt)",
            idx + 1
        );
        if opts.chars {
            let raw = raw_doc.as_ref().and_then(|d| d.page(idx));
            print_chars(&extract::page_chars(&page, raw.as_ref()));
            continue;
        }
        let Some(p) = usize::try_from(idx).ok().and_then(|i| analyzed.get(i)) else {
            continue;
        };
        let mut n = 0;
        let mut prev_base = None;
        let mut region = None;
        for b in &p.blocks {
            // Blocks are in reading order, region by region: announce each region.
            if region != Some(b.region) {
                region = Some(b.region);
                if let Some(r) = p.regions.get(b.region) {
                    print_region(b.region, r);
                }
                prev_base = None;
            }
            print_block(n, b, opts.words, &mut prev_base, None);
            n += 1;
        }
        if !p.furniture.is_empty() {
            outln!("-- furniture (out of the reading order)");
            prev_base = None;
            for f in &p.furniture {
                print_block(n, &f.block, opts.words, &mut prev_base, Some(f.reason));
                n += 1;
            }
        }
    }
    Ok(())
}

fn print_chars(chars: &[Char]) {
    for c in chars {
        outln!(
            "{:?}{} x={:.1}..{:.1} y={:.1}..{:.1} base={:.1} {:.1}pt {} {}{}",
            c.ch,
            if c.generated { " (gen)" } else { "" },
            c.bbox.left,
            c.bbox.right,
            c.bbox.top,
            c.bbox.bottom,
            c.baseline,
            c.size,
            c.style.label(),
            c.font,
            char_signals(c)
        );
    }
}

/// ` | kind=line-end-hyphen obj=97 mcid=60 at="-" …`: the extraction signals of a char
/// (achado 009), empty when there are none. Strings are Debug-quoted (`"\u{ad}"`).
fn char_signals(c: &Char) -> String {
    let s = &c.source;
    let mut parts = Vec::new();
    match c.kind {
        CharKind::Text => {}
        CharKind::LineEndHyphen => parts.push("kind=line-end-hyphen".to_string()),
        CharKind::SoftHyphen => parts.push("kind=soft-hyphen".to_string()),
    }
    if let Some(o) = s.object {
        parts.push(format!("obj={o}"));
    }
    if let Some(m) = s.mcid {
        parts.push(format!("mcid={m}"));
    }
    if let Some(t) = &s.actual_text {
        parts.push(format!("at={t:?}"));
    }
    if let Some(t) = &s.struct_actual_text {
        parts.push(format!("struct_at={t:?}"));
    }
    if let Some(a) = &s.artifact {
        let sub = a.subtype.as_deref().unwrap_or("?");
        let params = if a.has_params { "+params" } else { "" };
        let pagination = if a.pagination { "+pagination" } else { "" };
        parts.push(format!("artifact={sub}{params}{pagination}"));
    }
    if let Some(t) = &s.hidden_text_before {
        parts.push(format!("hidden_before={t:?}"));
    }
    if parts.is_empty() {
        String::new()
    } else {
        format!(" | {}", parts.join(" "))
    }
}

/// `-- region 2: band 1, column 1/2  x=… y=… w=… h=…` (reading order is the order of
/// the regions: bands top to bottom, columns left to right).
fn print_region(i: usize, r: &Region) {
    outln!(
        "-- region {i}: band {}, column {}/{}  x={:.1} y={:.1} w={:.1} h={:.1}",
        r.band,
        r.column + 1,
        r.columns,
        r.rect.left,
        r.rect.top,
        r.rect.width(),
        r.rect.height()
    );
}

fn print_block(
    i: usize,
    b: &Block,
    words: bool,
    prev_base: &mut Option<f32>,
    furniture: Option<Reason>,
) {
    let r = &b.bbox;
    outln!(
        "[{i:>3}] x={:>5.1} y={:>5.1} w={:>5.1} h={:>5.1}  {} line{}  {:.1}pt {}{}",
        r.left,
        r.top,
        r.width(),
        r.height(),
        b.lines.len(),
        if b.lines.len() == 1 { "" } else { "s" },
        b.size,
        b.style.label(),
        furniture.map_or(String::new(), |r| format!("  [furniture: {}]", r.label()))
    );
    let text: Vec<String> = b.lines.iter().map(|l| l.text()).collect();
    outln!("      {}", text.join(" ⏎ "));
    if words {
        for l in &b.lines {
            let parts: Vec<String> = l
                .words
                .iter()
                .map(|w| {
                    format!(
                        "{}{:?}@{:.1}{}",
                        if w.glued { "+" } else { "" },
                        w.text,
                        w.bbox.left,
                        if w.style == l.style && (w.size - l.size).abs() < 0.1 {
                            String::new()
                        } else {
                            format!("[{:.1}pt {}]", w.size, w.style.label())
                        }
                    )
                })
                .collect();
            // Step from the previous printed line (blocks are in top-to-bottom order of
            // their first line inside a region, so across blocks this is only
            // indicative; it restarts at each region) and the widest
            // gap between two words of the line, both in em.
            let step = prev_base.map_or(String::from("-"), |p: f32| {
                format!("{:.2}", (l.baseline - p) / l.size.max(0.1))
            });
            *prev_base = Some(l.baseline);
            let max_gap = l
                .words
                .windows(2)
                .map(|w| w[1].bbox.left - w[0].bbox.right)
                .fold(0.0f32, f32::max)
                / l.size.max(0.1);
            outln!(
                "        | x={:.1} base={:.1} {:.1}pt step={step}em gap={max_gap:.2}em: {}",
                l.bbox.left,
                l.baseline,
                l.size,
                parts.join(" ")
            );
        }
    }
}