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
//! `cargo run -p fm-vector --example read_pdf -- SCORE.pdf OUT.fmn [OUT.musicxml]`: read a PDF
//! from its vectors and write the .fmn (and the MusicXML), or say why it cannot be read.

fn main() {
    let a: Vec<String> = std::env::args().collect();
    if a.len() < 3 {
        eprintln!("usage: read_pdf SCORE.pdf OUT.fmn [OUT.musicxml]");
        std::process::exit(2);
    }
    let bytes = std::fs::read(&a[1]).expect("reading the PDF");
    if a[2] == "--layout" {
        print!(
            "{}",
            fm_vector::describe_layout(&bytes).unwrap_or_else(|e| e)
        );
        return;
    }
    let t = std::time::Instant::now();
    // FMV_UNREAD: the share of the staves' bars that may be left unread (0 to 1)
    let leaving = std::env::var("FMV_UNREAD")
        .ok()
        .and_then(|v| v.parse::<f64>().ok());
    let read = match leaving {
        Some(share) => fm_vector::read_pdf_leaving(&bytes, share),
        None => fm_vector::read_pdf(&bytes),
    };
    match read {
        Ok(r) => {
            std::fs::write(&a[2], &r.fmn).expect("writing the .fmn");
            if let Some(x) = a.get(3) {
                std::fs::write(x, &r.musicxml).expect("writing the MusicXML");
            }
            println!(
                "read in {:?}: {} systems, {} bars, {} notes, {} syllables{}",
                t.elapsed(),
                r.systems,
                r.bars,
                r.notes,
                r.syllables,
                match r.unread.len() {
                    0 => String::new(),
                    n => format!(", {n} staves' bars not read"),
                }
            );
            for u in &r.unread {
                // (the place: page, x0, x1, y0, y1, time; then what was seen, `; ` between)
                let place = u.place.as_ref().map_or(String::new(), |p| {
                    format!(
                        "\t{}\t{:.1}\t{:.1}\t{:.1}\t{:.1}\t{}/{}\t{}",
                        p.page,
                        p.x0,
                        p.x1,
                        p.y0,
                        p.y1,
                        p.time.0,
                        p.time.1,
                        p.seen.join("; ")
                    )
                });
                // (then the part's other staves in that bar: staff|y0|y1|seen, ` || ` between)
                let beside: Vec<String> = u
                    .beside
                    .iter()
                    .map(|(st, p)| format!("{st}|{:.1}|{:.1}|{}", p.y0, p.y1, p.seen.join("; ")))
                    .collect();
                let place = if place.is_empty() {
                    place
                } else {
                    format!("{place}\t{}", beside.join(" || "))
                };
                println!("unread\t{}\t{}\t{}{place}", u.bar, u.staff, u.why);
            }
            // (FMV_OPTIONS: the unread bars' options, a line of JSON each, by the .fmn's name)
            if let Ok(dir) = std::env::var("FMV_OPTIONS") {
                let stem = std::path::Path::new(&a[2]).file_stem().unwrap_or_default();
                let out = std::path::Path::new(&dir)
                    .join(stem)
                    .with_extension("jsonl");
                let text: String = r.options.iter().map(|l| format!("{l}\n")).collect();
                std::fs::write(out, text).expect("writing the options");
            }
            for n in r.notices {
                println!("notice: {n}");
            }
            // the bars in the order they play, runs written as from-to
            let score = readback::parse_str(&r.musicxml).expect("its own MusicXML reads");
            let labels: Vec<String> = score.bars.iter().map(|b| b.label.clone()).collect();
            match score.playback_order() {
                Ok(order) => {
                    let mut runs: Vec<(usize, usize)> = Vec::new();
                    for &i in &order {
                        match runs.last_mut() {
                            Some(run) if run.1 + 1 == i => run.1 = i,
                            _ => runs.push((i, i)),
                        }
                    }
                    let text: Vec<String> = runs
                        .iter()
                        .map(|&(a, b)| {
                            if a == b {
                                labels[a].clone()
                            } else {
                                format!("{}-{}", labels[a], labels[b])
                            }
                        })
                        .collect();
                    println!("plays: {} ({} bars)", text.join(", "), order.len());
                }
                Err(e) => println!("plays: no order ({e:?})"),
            }
        }
        Err(e) => {
            println!("refused after {:?}: {e}", t.elapsed());
            std::process::exit(1);
        }
    }
}