fm-vector 0.1.0

A notation program's PDF read from its vectors: every notehead, stem, beam and barline where the engraver put it, read into .fmn and compiled to MusicXML, with the words from the PDF's text. No model, no server: it runs in the browser.
Documentation
//! The page's text as words and lines.

use std::collections::{BTreeMap, BTreeSet};

use crate::page::Page;

/// A word: its letters, left and right edges, baseline and font size.
#[derive(Clone, Debug, PartialEq)]
pub struct Word {
    pub text: String,
    pub x0: f64,
    pub x1: f64,
    pub base: f64,
    pub size: f64,
}

/// How far back, in the letters' size, a kerned letter is drawn over the one before it.
const KERN: f64 = 0.12;

/// A kerned letter pair: its letters and its size in tenths.
pub type Kern = (char, char, i64);

/// The letter pairs shown kerned in a document's pages: a pair (letters and size) that steps
/// from one text-showing operation to the next by a small offset, the same each time it does
/// so. A font's kerning is a table, the same for a pair wherever it stands; two words set
/// close together are as far apart as their notes put them, never twice alike. So pages where
/// more than one in ten of the pairs seen more than once steps by unlike offsets set words
/// close, not kerned: none of their pairs is taken as kerned.
pub fn kerned_pairs<'a>(pages: impl IntoIterator<Item = &'a Page>) -> BTreeSet<Kern> {
    let mut seen: BTreeMap<Kern, Vec<f64>> = BTreeMap::new();
    for w in pages.into_iter().flat_map(|pg| pg.letters.windows(2)) {
        let (p, l) = (&w[0], &w[1]);
        let size = l.size.max(p.size);
        let gap = (l.x0 - p.x1) / size;
        if p.run != l.run
            && (l.size - p.size).abs() <= 0.01 * size
            && (l.base - p.base).abs() <= 0.2 * size
            && gap.abs() > 0.02
            && (-KERN..=0.05).contains(&gap)
        {
            seen.entry(pair_key(p.ch, l.ch, size))
                .or_default()
                .push(gap);
        }
    }
    let alike = |gaps: &Vec<f64>| {
        let lo = gaps.iter().copied().fold(f64::MAX, f64::min);
        let hi = gaps.iter().copied().fold(f64::MIN, f64::max);
        hi - lo < 0.006
    };
    let unlike = seen.values().filter(|g| !alike(g)).count();
    let repeated = seen.values().filter(|g| g.len() >= 2).count();
    if unlike * 10 > repeated {
        return BTreeSet::new();
    }
    seen.into_iter()
        .filter(|(_, gaps)| alike(gaps))
        .map(|(k, _)| k)
        .collect()
}

fn pair_key(a: char, b: char, size: f64) -> Kern {
    (a, b, (size * 10.0).round() as i64)
}

/// A ligature as its letters (the words are compared and sung by their letters).
fn unligated(c: char) -> impl Iterator<Item = char> {
    let s: &'static str = match c {
        '\u{FB00}' => "ff",
        '\u{FB01}' => "fi",
        '\u{FB02}' => "fl",
        '\u{FB03}' => "ffi",
        '\u{FB04}' => "ffl",
        _ => "",
    };
    s.chars().chain(s.is_empty().then_some(c))
}

/// The page's words: letters cut at spaces, at a change of baseline or size, and at gaps between
/// letters (some programs set two words in one string with no space, only a gap). A new
/// text-showing operation cuts only where the letters do not run on: some programs show every
/// letter on its own.
pub fn words_of(pg: &Page) -> Vec<Word> {
    let mut out = Vec::new();
    // (the document's, set when its pages are read; a page alone, its own)
    let own;
    let kerned = match &pg.kerned {
        Some(k) => k,
        None => {
            own = kerned_pairs([pg]);
            &own
        }
    };
    let mut piece: Vec<&crate::page::Letter> = Vec::new();
    let flush = |piece: &mut Vec<&crate::page::Letter>, out: &mut Vec<Word>| {
        if !piece.is_empty() {
            out.push(Word {
                text: piece.iter().flat_map(|l| unligated(l.ch)).collect(),
                x0: piece.iter().map(|l| l.x0).fold(f64::MAX, f64::min),
                x1: piece.iter().map(|l| l.x1).fold(f64::MIN, f64::max),
                base: piece[0].base,
                size: piece[0].size,
            });
            piece.clear();
        }
    };
    for l in &pg.letters {
        let breaks = piece.last().is_some_and(|p| {
            let gap = l.x0 - p.x1;
            let size = l.size.max(p.size);
            // (a kerned pair is shown as two operations, the second drawn back a little over
            // the first, "W" and "e" of one word, or set off a little from it, "g" and "r")
            let kern = kerned.contains(&pair_key(p.ch, l.ch, size));
            (p.run != l.run
                && ((l.size - p.size).abs() > 0.01 * size || (gap.abs() > 0.02 * size && !kern)))
                || (l.base - p.base).abs() > 0.2 * p.size
                || gap > 0.05 * size
                || gap < -0.25 * size // a jump back: the next syllable, placed on its own
        });
        if breaks {
            flush(&mut piece, &mut out);
        }
        if l.ch.is_whitespace() {
            flush(&mut piece, &mut out);
        } else {
            piece.push(l);
        }
    }
    flush(&mut piece, &mut out);
    out
}

/// A line of text: its words joined, its extent, baseline and largest size.
#[derive(Clone, Debug)]
pub struct Line {
    pub text: String,
    pub x0: f64,
    pub x1: f64,
    pub base: f64,
    pub size: f64,
}

/// Words on one baseline (within `tol`) as lines, top to bottom.
pub fn lines_of(words: &[Word], tol: f64) -> Vec<Line> {
    let mut ws: Vec<&Word> = words.iter().collect();
    ws.sort_by(|a, b| a.base.total_cmp(&b.base));
    let mut groups: Vec<Vec<&Word>> = Vec::new();
    for w in ws {
        match groups.last_mut() {
            Some(g) if (w.base - g[0].base).abs() < tol => g.push(w),
            _ => groups.push(vec![w]),
        }
    }
    groups
        .into_iter()
        .map(|mut g| {
            g.sort_by(|a, b| a.x0.total_cmp(&b.x0));
            Line {
                text: g
                    .iter()
                    .map(|w| w.text.as_str())
                    .collect::<Vec<_>>()
                    .join(" "),
                x0: g[0].x0,
                x1: g.iter().map(|w| w.x1).fold(f64::MIN, f64::max),
                base: g[0].base,
                size: g.iter().map(|w| w.size).fold(0.0, f64::max),
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::page::Letter;

    fn letters(s: &str, x: f64, run: usize) -> Vec<Letter> {
        s.chars()
            .enumerate()
            .map(|(i, ch)| Letter {
                ch,
                x0: x + i as f64 * 5.0,
                x1: x + i as f64 * 5.0 + 5.0,
                base: 100.0,
                size: 10.0,
                run,
            })
            .collect()
    }

    #[test]
    fn words_part_at_spaces_runs_and_gaps() {
        let mut pg = Page {
            letters: letters("lo ra", 0.0, 1),
            ..Page::default()
        };
        pg.letters.extend(letters("mi", 25.0, 2)); // another run, running on: one word
        pg.letters.extend(letters("su", 40.0, 2)); // same run, a gap of 5
        pg.letters.extend(letters("do", 50.6, 3)); // another run after a small gap
        pg.letters.extend(letters("fa", 0.0, 3)); // same run, jumping back
        let w: Vec<String> = words_of(&pg).into_iter().map(|w| w.text).collect();
        assert_eq!(w, ["lo", "rami", "su", "do", "fa"]);
    }

    /// The words of `pieces` (text, x, run), on one baseline, in that order.
    fn words(pieces: &[(&str, f64)]) -> Vec<String> {
        let mut pg = Page::default();
        for (k, &(t, x)) in pieces.iter().enumerate() {
            pg.letters.extend(letters(t, x, k));
        }
        words_of(&pg).into_iter().map(|w| w.text).collect()
    }

    #[test]
    fn a_kerned_pair_is_one_word() {
        // "W" and "eibes" shown apart, the second drawn back over the first by a kerning's
        // worth, and again later by the same; a syllable set back by more is its own
        let w = words(&[
            ("W", 0.0),
            ("ei", 4.4),
            ("so", 12.0),
            ("W", 40.0),
            ("e", 44.4),
        ]);
        assert_eq!(w, ["Wei", "so", "We"]);
        // "g" and "r" set a little apart, twice alike; a ligature is its letters
        let w = words(&[("g", 0.0), ("r\u{FB02}y", 5.3), ("g", 30.0), ("r", 35.3)]);
        assert_eq!(w, ["grfly", "gr"]);
    }

    #[test]
    fn words_set_close_at_unlike_offsets_are_two() {
        // "me" and "go", "me" and "gi": syllables of two notes set close, the pair "eg"
        // stepping back by unlike amounts: no kerning, two words each time
        let w = words(&[("me", 0.0), ("go", 9.6), ("me", 30.0), ("gi", 39.3)]);
        assert_eq!(w, ["me", "go", "me", "gi"]);
        // and on such a page no pair is taken as kerned, not even one stepped back once
        let w = words(&[
            ("me", 0.0),
            ("go", 9.6),
            ("me", 30.0),
            ("gi", 39.3),
            ("W", 60.0),
            ("ei", 64.4),
        ]);
        assert_eq!(w, ["me", "go", "me", "gi", "W", "ei"]);
        // where pairs step alike, one stepped back once is kerned
        let w = words(&[("W", 0.0), ("ei", 4.4)]);
        assert_eq!(w, ["Wei"]);
    }
}