pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
//! Layout stages of the pipeline (docs/arquitetura.md, part 2, stages 2 and 3):
//! characters → words → lines → blocks.
//!
//! - [`extract`] turns PDFium characters into our own [`Char`] values (the only part
//!   that touches PDFium).
//! - [`group`] holds the grouping heuristics as pure functions over these types, so
//!   they can be unit-tested with synthetic characters.
//! - [`columns`] finds column gutters on the words (before lines are formed) and
//!   splits the page into regions in reading order.
//! - [`furniture`] finds running headers, footers and page numbers across pages and
//!   takes them out before column detection.
//!
//! All coordinates are PDF points with the origin at the TOP-left of the page
//! (y grows downwards), the same convention as `pdfsift dump`.

pub mod columns;
pub mod extract;
pub mod furniture;
pub mod group;
pub mod hyphen;
pub mod table;

pub use columns::Region;

use pdfium_render::prelude::{PdfDocument, PdfPageIndex};

use crate::tags::RawDoc;

/// Runs extraction and grouping for every page of the document, with page
/// furniture (running headers, footers, page numbers) detected across pages and
/// kept apart in [`Page::furniture`]. `raw` is the same document on a raw PDFium handle
/// ([`crate::tags`]); without it the chars carry no marked-content signals.
pub fn analyze_document(doc: &PdfDocument, raw: Option<&RawDoc>) -> Vec<Page> {
    let pages = doc
        .pages()
        .iter()
        .enumerate()
        .map(|(i, page)| {
            let rp = PdfPageIndex::try_from(i)
                .ok()
                .and_then(|i| raw.and_then(|r| r.page(i)));
            group::PagePrimitives {
                width: page.width().value,
                height: page.height().value,
                chars: extract::page_chars(&page, rp.as_ref()),
                path_marks: extract::page_path_marks(&page),
                rules: extract::page_rules(&page),
            }
        })
        .collect();
    group::layout_document(pages)
}

/// Axis-aligned rectangle, top-origin coordinates (`top <= bottom`, `left <= right`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rect {
    pub left: f32,
    pub top: f32,
    pub right: f32,
    pub bottom: f32,
}

impl Rect {
    pub fn new(left: f32, top: f32, right: f32, bottom: f32) -> Self {
        Rect {
            left: left.min(right),
            top: top.min(bottom),
            right: left.max(right),
            bottom: top.max(bottom),
        }
    }

    pub fn width(&self) -> f32 {
        self.right - self.left
    }

    pub fn height(&self) -> f32 {
        self.bottom - self.top
    }

    pub fn center_x(&self) -> f32 {
        (self.left + self.right) / 2.0
    }

    pub fn union(&self, o: &Rect) -> Rect {
        Rect {
            left: self.left.min(o.left),
            top: self.top.min(o.top),
            right: self.right.max(o.right),
            bottom: self.bottom.max(o.bottom),
        }
    }

    /// Length of the overlap of the two horizontal extents (0 when disjoint).
    pub fn h_overlap(&self, o: &Rect) -> f32 {
        (self.right.min(o.right) - self.left.max(o.left)).max(0.0)
    }
}

/// Typographic style derived from the font (name first, descriptor flags second;
/// never from the reported weight, see docs/achados/001-kitchen-sink.md, finding 2).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Style {
    pub bold: bool,
    pub italic: bool,
    pub mono: bool,
}

impl Style {
    /// Short label for debug output: `regular`, `bold`, `bold+italic+mono`, …
    pub fn label(&self) -> String {
        let mut parts = Vec::new();
        if self.bold {
            parts.push("bold");
        }
        if self.italic {
            parts.push("italic");
        }
        if self.mono {
            parts.push("mono");
        }
        if parts.is_empty() {
            "regular".into()
        } else {
            parts.join("+")
        }
    }
}

/// One character as PDFium reports it, in our own types.
#[derive(Clone, Debug, PartialEq)]
pub struct Char {
    pub ch: char,
    /// Loose box: advance width horizontally, font ascent..descent vertically.
    pub bbox: Rect,
    /// y of the glyph origin (the baseline), top-origin.
    pub baseline: f32,
    /// Effective font size in points (includes vertical scaling of the text matrix).
    pub size: f32,
    /// Font name without the `ABCDEF+` subset prefix.
    pub font: String,
    pub style: Style,
    /// PDFium synthesized this character (spaces and line breaks it infers from gaps);
    /// it is not in the content stream.
    pub generated: bool,
    /// What the character is for later stages (hyphen candidates, see [`CharKind`]).
    pub kind: CharKind,
    /// Content-stream object and marked-content signals (docs/achados/009).
    pub source: CharSource,
}

/// Role of a character for later stages. Set by extraction (docs/achados/009).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum CharKind {
    #[default]
    Text,
    /// A hyphen that PDFium found at the end of a line after a letter. PDFium reports it as
    /// U+0002 (`FPDFText_IsHyphen`) whatever the producer drew, compound hyphens
    /// (`segunda-feira`) included (achado 003, finding 1). Extraction stores it as `-` so
    /// the text stays readable; whether it is joined is the de-hyphenation stage's call.
    LineEndHyphen,
    /// U+00AD (soft hyphen) left in the text by the producer (Typst, achado 003 finding 3).
    /// Kept as is: it is only dropped where it does not end a line, which needs lines.
    SoftHyphen,
}

/// Where a character comes from and the marked content around its object (achado 007).
/// All `None` when the raw PDFium handle is unavailable or the char has no object.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CharSource {
    /// Index of the source page object, counting depth-first in content-stream order
    /// (a form XObject comes before its children). It equals the top-level index shown by
    /// `pdfsift dump` when no form XObject precedes the object. None when PDFium links
    /// the char to no object: generated line breaks, and generated spaces between two
    /// objects. A space PDFium generates inside one object (LaTeX) has that object.
    pub object: Option<u32>,
    /// Marked-content ID of the innermost mark that has one.
    pub mcid: Option<i32>,
    /// ActualText of the innermost mark that has one. PDFium has already applied it to
    /// the text where it could (ligatures, Typst's mid-line `-`): a signal, never to be
    /// re-applied (achado 007, finding 2).
    pub actual_text: Option<String>,
    /// ActualText of the structure element that owns [`Self::mcid`] (or its nearest
    /// ancestor that has one). LibreOffice tagged puts U+00AD here for typesetter hyphens.
    pub struct_actual_text: Option<String>,
    /// Level (1–6) of the nearest `H1`..`H6` structure element above the MCID (Chrome and
    /// Typst tag headings; Chrome also tags the document title `H1`).
    pub struct_heading: Option<u8>,
    /// Inside an `/Artifact` mark (pagination, layout, background content).
    pub artifact: Option<Artifact>,
    /// ActualText of the object right before this char's object in the content stream,
    /// when that object yields no characters (PDFium drops it). Set only on the first char
    /// of an object. Chrome: U+00AD before a soft-hyphen break; Typst: `-` repeated at the
    /// start of the next line after a compound-word break (achado 007, findings 3 and 5).
    pub hidden_text_before: Option<String>,
    /// The char is drawn inside a form XObject that covers less than half of the page:
    /// a figure (diagram labels, map legends, achado 012). None for text outside forms
    /// and inside page-sized forms (`\includepdf` and similar wrappers).
    pub figure: Option<Figure>,
}

/// A form XObject drawn on the page that looks like a figure (achado 012).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Figure {
    /// Index of the top-level page object (the outermost form).
    pub object: u32,
    /// Bounds of the form on the page, top-origin.
    pub rect: Rect,
}

/// An `/Artifact` mark. PDFium does not return name-valued mark params (achado 007,
/// finding 1), so `subtype` (`Header`, `Footer`, …) is None with PDFium chromium/8179.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Artifact {
    pub subtype: Option<String>,
    /// The mark has a property list (`/Artifact <<…>> BDC`), as opposed to `/Artifact BMC`.
    /// Chrome and Typst write `/Type /Pagination` this way; LibreOffice uses plain BMC.
    pub has_params: bool,
    /// A pagination artifact (running header, footer, page number). The `/Type` value is
    /// unreadable, so this is inferred from the `/Subtype` key: ISO 32000-1 (Table 330)
    /// says Subtype should appear only when Type is Pagination. Chrome and Typst write
    /// it; a bare `/Artifact BMC` (LibreOffice tagged) is not pagination.
    pub pagination: bool,
}

/// A run of characters with no gap and one font/size. Words split at a style change
/// without a space (`negrito` + `,`) are marked `glued`, so text can be rebuilt exactly.
#[derive(Clone, Debug, PartialEq)]
pub struct Word {
    pub text: String,
    pub bbox: Rect,
    pub baseline: f32,
    pub size: f32,
    pub font: String,
    pub style: Style,
    /// No whitespace separates this word from the previous one in the same line.
    pub glued: bool,
    /// Number of characters (for weighting dominant size/style).
    pub len: usize,
    /// Indices of the word's chars in [`Page::chars`] (the page's chars in extraction
    /// order). Empty for words that are not text (a vector bullet). Later stages read
    /// the per-char signals through it (de-hyphenation, achado 009).
    pub chars: std::ops::Range<usize>,
    /// Every char of the word is inside the same figure form XObject
    /// ([`CharSource::figure`]). Column detection treats figure text apart (achado 012).
    pub figure: Option<Figure>,
}

/// Words that share a baseline (superscripts and subscripts included), left to right.
#[derive(Clone, Debug, PartialEq)]
pub struct Line {
    pub words: Vec<Word>,
    pub bbox: Rect,
    /// Baseline of the dominant (main-size) words.
    pub baseline: f32,
    /// Dominant font size (weighted by characters).
    pub size: f32,
    /// Dominant style (weighted by characters).
    pub style: Style,
}

impl Line {
    /// The line's text: words joined by one space unless glued.
    pub fn text(&self) -> String {
        let mut s = String::new();
        for (i, w) in self.words.iter().enumerate() {
            if i > 0 && !w.glued {
                s.push(' ');
            }
            s.push_str(&w.text);
        }
        s
    }
}

/// Consecutive lines that belong together (a paragraph, a heading, a list item, …).
/// No classification yet: that is the next stage.
#[derive(Clone, Debug, PartialEq)]
pub struct Block {
    pub lines: Vec<Line>,
    pub bbox: Rect,
    pub size: f32,
    pub style: Style,
    /// Index into [`Page::regions`] (the column or full-width band the block is in).
    pub region: usize,
}

/// One page after grouping.
#[derive(Clone, Debug, PartialEq)]
pub struct Page {
    /// 1-based page number.
    pub number: usize,
    pub width: f32,
    pub height: f32,
    /// Regions in reading order (full-width bands and columns, see [`columns`]).
    pub regions: Vec<Region>,
    /// Blocks in reading order: region by region, top to bottom inside a region.
    pub blocks: Vec<Block>,
    /// Running headers, footers and page numbers, taken out of `blocks` (stage 5,
    /// [`furniture`]), top to bottom.
    pub furniture: Vec<furniture::Furniture>,
    /// The page's chars in extraction order; [`Word::chars`] indexes this.
    pub chars: Vec<Char>,
}