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
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
//! The words of a voice from the PDF's text, set under its notes: each verse line's syllables
//! matched in order to the sung notes by where they stand, the hyphens and extender lines drawn
//! after a syllable saying whether its word goes on or it is held.

use crate::page::{Page, Staff};
use crate::words::{words_of, Word};

const DASHES: &[char] = &['-', '‐', '‑', '‒', '–', '—', '−', '~'];
const PUNCT: &[char] = &[',', '.', ';', ':', '!', '?', '"', '“', '”'];
const APOS: &[char] = &['\'', '’', 'ʼ', '‘', '`'];

/// An apostrophe as it is written: the one printed where it is the right single quote (`’`) or
/// the modifier letter (`ʼ`), which the text keeps; a left quote or a grave accent standing for
/// one is the plain `'`.
fn apostrophe(c: char) -> char {
    match c {
        '’' | 'ʼ' => c,
        _ => '\'',
    }
}

/// A syllable: its text, its middle and left edge, whether the word goes on (`cont`) or the
/// syllable is held over the notes after (`ext`).
#[derive(Clone, Debug, PartialEq)]
pub struct Syl {
    pub text: String,
    pub x: f64,
    pub left: f64,
    pub cont: bool,
    pub ext: bool,
}

/// Whether a word in the lyrics' band is a mark, not sung: a mark's word (`p`, `cresc.`,
/// `rit.`, ...), unless it goes on the word before it (`open`: that syllable ends in a hyphen)
/// and has no abbreviation's dot, or it is the plain word "dim" as printed, with no dot.
fn is_mark(t: &str, open: bool) -> bool {
    is_dynamic(t) && !((open && !t.ends_with('.')) || t == "dim")
}

fn is_dynamic(t: &str) -> bool {
    let l = t.to_lowercase();
    let l = l.trim_end_matches('.');
    matches!(
        l,
        "p" | "pp"
            | "ppp"
            | "mp"
            | "mf"
            | "f"
            | "ff"
            | "fff"
            | "sf"
            | "sfz"
            | "fp"
            | "cresc"
            | "dim"
            | "rit"
            | "rall"
            | "8va"
    )
}

/// The words in the band under a voice's staff, between x0 and x1, with a hyphen (`-`) or an
/// extender (`_`) added where a line is drawn after one.
pub fn band(pg: &Page, staff: &Staff, below: Option<&Staff>, x0: f64, x1: f64) -> Vec<Word> {
    let sp = staff.sp();
    let lo = staff.bottom() + 0.6 * sp;
    let hi = below
        .map(|b| b.top() - 0.3 * sp)
        .unwrap_or(staff.bottom() + 12.0 * sp);
    let mut words: Vec<Word> = words_of(pg)
        .into_iter()
        .filter(|w| {
            let cx = (w.x0 + w.x1) / 2.0;
            x0 - sp <= cx && cx <= x1 + sp && lo <= w.base && w.base <= hi
        })
        .collect();
    // hyphens and extenders: a hyphen stands about a quarter of the letters' size above the
    // baseline (the word goes on), an extender on it (the syllable is held)
    let mut segs: Vec<(f64, f64, f64)> = pg.hlines.iter().map(|l| (l.x0, l.x1, l.y)).collect();
    for p in &pg.polys {
        for k in 0..p.len() {
            let (a, b) = (p[k], p[(k + 1) % p.len()]);
            if (a.1 - b.1).abs() < 0.1 * sp {
                segs.push((a.0.min(b.0), a.0.max(b.0), a.1));
            }
        }
    }
    for (xa, xb, y) in segs {
        if xb - xa < 0.15 * sp || !(x0 - sp <= xa && xa <= x1 + sp && lo - sp <= y && y <= hi) {
            continue;
        }
        let near = words
            .iter_mut()
            .filter(|w| {
                -0.5 * w.size <= y - w.base
                    && y - w.base <= 0.15 * w.size
                    && -0.1 * sp <= xa - w.x1
                    && xa - w.x1 < 4.0 * w.size
            })
            .min_by(|a, b| (xa - a.x1).total_cmp(&(xa - b.x1)));
        if let Some(w) = near {
            let rel = (y - w.base) / w.size;
            let mark = if rel < -0.15 {
                Some('-')
            } else if rel > -0.12 {
                Some('_')
            } else {
                None
            };
            if let Some(m) = mark {
                if !w.text.ends_with(m) {
                    w.text = w.text.trim_end_matches(['-', '_']).to_string();
                    w.text.push(m);
                }
            }
        }
    }
    words
}

/// The band's words as verse lines, top to bottom, each left to right.
pub fn verse_lines(words: Vec<Word>, sp: f64) -> Vec<Vec<Word>> {
    let mut ws = words;
    ws.sort_by(|a, b| a.base.total_cmp(&b.base));
    let mut lines: Vec<Vec<Word>> = Vec::new();
    for w in ws {
        match lines.last_mut() {
            Some(l)
                if (w.base - l.iter().map(|v| v.base).sum::<f64>() / l.len() as f64).abs()
                    < 0.9 * sp =>
            {
                l.push(w)
            }
            _ => lines.push(vec![w]),
        }
    }
    for l in lines.iter_mut() {
        l.sort_by(|a, b| a.x0.total_cmp(&b.x0));
    }
    lines
}

/// Marks that are not words left out; punctuation and apostrophes glued to their word.
///
/// A mark's word (`rit`, `f`) after a syllable that ends in a hyphen goes on that syllable's
/// word ("me- rit"): it is sung, not a mark, unless it has an abbreviation's dot (the
/// "cresc." of "molto - cresc."). One with a hyphen or an extender drawn after it is a syllable
/// too (the band adds `-` or `_` to its text, and it is then no mark's word). A hyphen
/// standing alone goes on from the syllable before it, never from a mark left out (the dashes
/// of "cresc. - - -"). See `is_mark`.
fn tidy(line: &[Word], sp: f64) -> Vec<Word> {
    // (the last word kept a syllable; the word it is in going on to the next)
    let (mut syl, mut open) = (false, false);
    let mut ws: Vec<Word> = Vec::new();
    for w in line {
        let w = Word {
            text: w.text.trim().to_string(),
            ..w.clone()
        };
        let t = w.text.as_str();
        if t.is_empty() {
            continue;
        }
        if is_mark(t, open)
            || t.chars()
                .all(|c| c.is_ascii_digit() || c == '(' || c == ')')
        {
            (syl, open) = (false, false);
            continue;
        }
        if t.chars().all(|c| DASHES.contains(&c)) {
            open = syl;
        } else if !t.chars().all(|c| PUNCT.contains(&c) || APOS.contains(&c)) {
            syl = true;
            open = t.trim_end_matches(PUNCT).ends_with(DASHES);
        }
        ws.push(w);
    }
    let mut out: Vec<Word> = Vec::new();
    let mut i = 0;
    while i < ws.len() {
        let t = ws[i].text.clone();
        if t.chars().all(|c| PUNCT.contains(&c)) {
            if let Some(p) = out.last_mut() {
                p.text.push_str(&t);
            }
            i += 1;
            continue;
        }
        if t.chars().all(|c| APOS.contains(&c)) {
            // (as printed: the first of them, where a font draws one in two pieces)
            let a = t.chars().next().map_or('\'', apostrophe);
            let gl = out.last().map(|p| ws[i].x0 - p.x1).unwrap_or(1e18);
            let gr = ws.get(i + 1).map(|n| n.x0 - ws[i].x1).unwrap_or(1e18);
            let prev_dash = out.last().is_some_and(|p| p.text.ends_with(DASHES));
            if !out.is_empty() && i + 1 < ws.len() && gl < 0.6 * sp && gr < 0.6 * sp && !prev_dash {
                let n = ws[i + 1].clone();
                let p = out.last_mut().unwrap();
                p.text.push(a);
                p.text.push_str(&n.text);
                p.x1 = n.x1;
                i += 2;
                continue;
            }
            if i + 1 < ws.len() && gr < 0.6 * sp {
                let x0 = ws[i].x0;
                ws[i + 1].text.insert(0, a);
                ws[i + 1].x0 = x0;
            } else if let Some(p) = out.last_mut() {
                p.text.push(a);
            }
            i += 1;
            continue;
        }
        out.push(ws[i].clone());
        i += 1;
    }
    out
}

/// One verse line's words as syllables.
pub fn syllables(line: &[Word], sp: f64) -> Vec<Syl> {
    let mut out: Vec<Syl> = Vec::new();
    for w in tidy(line, sp) {
        let t = w.text.as_str();
        if t.chars().all(|c| DASHES.contains(&c) || c == '_') {
            // a hyphen or extender alone
            if let Some(p) = out.last_mut() {
                if t.contains('_') {
                    p.ext = true;
                } else {
                    p.cont = true;
                }
            }
            continue;
        }
        // held: an extender at the end, before any punctuation glued on after it
        let ext = t.trim_end_matches(PUNCT).ends_with('_');
        let t: String = t.chars().filter(|&c| c != '_').collect();
        let t = t.as_str();
        let chars: Vec<char> = t.chars().collect();
        let n = chars.len().max(1) as f64;
        let mut segs: Vec<Syl> = Vec::new();
        let mut pos = 0usize;
        let mut k = 0;
        while k < chars.len() {
            let dash = DASHES.contains(&chars[k]);
            let mut e = k;
            while e < chars.len() && DASHES.contains(&chars[e]) == dash {
                e += 1;
            }
            if dash {
                if let Some(s) = segs.last_mut() {
                    s.cont = true;
                }
            } else {
                let a = w.x0 + (w.x1 - w.x0) * pos as f64 / n;
                let b = w.x0 + (w.x1 - w.x0) * (pos + e - k) as f64 / n;
                segs.push(Syl {
                    text: chars[k..e].iter().collect(),
                    x: (a + b) / 2.0,
                    left: a,
                    cont: false,
                    ext: false,
                });
            }
            pos += e - k;
            k = e;
        }
        if segs.is_empty() {
            continue;
        }
        if chars.first().is_some_and(|c| DASHES.contains(c)) {
            if let Some(p) = out.last_mut() {
                p.cont = true;
            }
        }
        if ext {
            segs.last_mut().unwrap().ext = true;
        }
        out.extend(segs);
    }
    out
}

/// An order-keeping match of syllables to notes (their x): each syllable's note, or None.
pub fn align(syls: &[Syl], notes_x: &[f64], sp: f64) -> Vec<Option<usize>> {
    let (m, n) = (syls.len(), notes_x.len());
    let (skip_note, skip_syl) = (1.5, 25.0);
    let mut d = vec![vec![1e18f64; n + 1]; m + 1];
    let mut back = vec![vec![0u8; n + 1]; m + 1];
    for j in 0..=n {
        d[0][j] = j as f64 * skip_note;
    }
    for i in 1..=m {
        d[i][0] = i as f64 * skip_syl;
        back[i][0] = 2;
        for j in 1..=n {
            // a syllable stands centred under its note, or from the note's left when it is held
            // over the notes after (an engraver's habit): whichever is nearer
            let (s, x) = (&syls[i - 1], notes_x[j - 1]);
            let off = (s.x - x).abs().min((s.left + 0.6 * sp - x).abs());
            let c = [
                d[i - 1][j - 1] + off / sp,
                d[i][j - 1] + skip_note,
                d[i - 1][j] + skip_syl,
            ];
            let (k, v) = c
                .iter()
                .enumerate()
                .fold((0, f64::MAX), |b, (k, &v)| if v < b.1 { (k, v) } else { b });
            d[i][j] = v;
            back[i][j] = k as u8;
        }
    }
    let (mut i, mut j) = (m, n);
    let mut res = vec![None; m];
    while i > 0 {
        if j == 0 || back[i][j] == 2 {
            i -= 1;
        } else if back[i][j] == 0 {
            res[i - 1] = Some(j - 1);
            i -= 1;
            j -= 1;
        } else {
            j -= 1;
        }
    }
    res
}

/// A syllable as a token, as printed: a space inside it and the marks the format reads (`_`,
/// `*`, `#`, a backslash) each after a backslash (`to\ the`, `\*`). An apostrophe printed `’`
/// or `ʼ` stays the character it is (the text keeps it); a left quote standing for one is `'`.
pub fn clean(t: &str) -> String {
    let mut s = String::new();
    for c in t.trim().chars() {
        match c {
            '‘' => s.push('\''),
            c if c.is_whitespace() => s.push_str("\\ "),
            '*' | '_' | '#' | '\\' => s.extend(['\\', c]),
            c => s.push(c),
        }
    }
    if s.is_empty() {
        "?".into()
    } else {
        s
    }
}

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

    fn w(text: &str, x0: f64) -> Word {
        Word {
            text: text.into(),
            x0,
            x1: x0 + 6.0 * text.chars().count() as f64,
            base: 100.0,
            size: 10.0,
        }
    }

    #[test]
    fn a_syllable_keeps_the_marks_the_format_reads_after_a_backslash() {
        assert_eq!(clean("to the"), "to\\ the");
        assert_eq!(clean(" *"), "\\*");
        assert_eq!(clean("a_b#"), "a\\_b\\#");
        // an apostrophe as printed: the right single quote and the modifier letter stay
        assert_eq!(clean("l’a"), "l’a");
        assert_eq!(clean("lʼa"), "lʼa");
        assert_eq!(clean("l'a"), "l'a");
        assert_eq!(clean("‘ta"), "'ta");
        assert_eq!(clean(" "), "?");
        // and the compiler gives each back as printed
        let fmn = "part V \"V\" voice\nkey 0 major\ntime 2/4\nbar 1\nV: c5/4 d5\nV lyrics: ";
        let line = format!("{fmn}{} {}\n", clean("to the"), clean("a_b#"));
        let xml = fm_transcribe::compile(&line).unwrap().musicxml;
        assert!(xml.contains("<text>to the</text>") && xml.contains("<text>a_b#</text>"));
        let line = format!("{fmn}{} {}\n", clean("l’a"), clean("tʼa"));
        let xml = fm_transcribe::compile(&line).unwrap().musicxml;
        assert!(xml.contains("<text>l’a</text>") && xml.contains("<text>tʼa</text>"));
    }

    #[test]
    fn an_apostrophe_set_apart_joins_its_word_as_printed() {
        let texts = |ws: &[Word]| -> Vec<String> {
            syllables(ws, 5.0).into_iter().map(|s| s.text).collect()
        };
        // between two words set close: one word, the apostrophe the one printed
        assert_eq!(texts(&[w("l", 0.0), w("’", 6.5), w("a", 13.0)]), ["l’a"]);
        assert_eq!(texts(&[w("l", 0.0), w("ʼ", 6.5), w("a", 13.0)]), ["lʼa"]);
        assert_eq!(texts(&[w("l", 0.0), w("'", 6.5), w("a", 13.0)]), ["l'a"]);
        // a left quote or a grave accent standing for one is the plain apostrophe
        assert_eq!(texts(&[w("l", 0.0), w("‘", 6.5), w("a", 13.0)]), ["l'a"]);
        // before a word, and after one
        assert_eq!(texts(&[w("’", 0.0), w("ta", 6.5)]), ["’ta"]);
        assert_eq!(texts(&[w("ta", 0.0), w("’", 40.0)]), ["ta’"]);
    }

    #[test]
    fn syllables_keep_their_hyphens_and_holds() {
        let s = syllables(
            &[w("lo-", 0.0), w("ra", 40.0), w("mi_", 80.0), w(",", 98.0)],
            5.0,
        );
        let t: Vec<(&str, bool, bool)> =
            s.iter().map(|s| (s.text.as_str(), s.cont, s.ext)).collect();
        assert_eq!(
            t,
            [
                ("lo", true, false),
                ("ra", false, false),
                ("mi,", false, true)
            ]
        );
    }

    #[test]
    fn a_word_after_a_hyphen_or_before_one_is_a_syllable_not_a_mark() {
        let texts = |ws: &[Word]| -> Vec<(String, bool, bool)> {
            syllables(ws, 5.0)
                .into_iter()
                .map(|s| (s.text, s.cont, s.ext))
                .collect()
        };
        let s = |t: &str, cont: bool, ext: bool| (t.to_string(), cont, ext);
        // after a syllable ending in a hyphen, drawn on it or set apart: the word goes on
        assert_eq!(
            texts(&[w("me-", 0.0), w("rit", 40.0)]),
            [s("me", true, false), s("rit", false, false)]
        );
        assert_eq!(
            texts(&[w("ca", 0.0), w("-", 20.0), w("dim", 40.0)]),
            [s("ca", true, false), s("dim", false, false)]
        );
        assert_eq!(
            texts(&[w("so-", 0.0), w("f", 40.0), w("ter", 60.0)]),
            [
                s("so", true, false),
                s("f", false, false),
                s("ter", false, false)
            ]
        );
        // with a hyphen or an extender drawn after it: a syllable
        assert_eq!(
            texts(&[w("rit-", 0.0), w("ual", 40.0)]),
            [s("rit", true, false), s("ual", false, false)]
        );
        assert_eq!(texts(&[w("dim_", 0.0)]), [s("dim", false, true)]);
        // a mark standing alone is still left out, one with its dot after a hyphen, and one
        // after a mark's dashes
        assert_eq!(
            texts(&[w("la", 0.0), w("rit.", 40.0), w("lo", 80.0)]),
            [s("la", false, false), s("lo", false, false)]
        );
        assert_eq!(
            texts(&[w("molto-", 0.0), w("cresc.", 60.0), w("lo", 90.0)]),
            [s("molto", true, false), s("lo", false, false)]
        );
        assert_eq!(
            texts(&[w("la", 0.0), w("mf", 40.0)]),
            [s("la", false, false)]
        );
        // the plain word "dim", with no dot, is sung; "dim." and "Dim." are marks
        assert_eq!(
            texts(&[
                w("the", 0.0),
                w("dim", 30.0),
                w("Dim.", 60.0),
                w("dim.", 90.0)
            ]),
            [s("the", false, false), s("dim", false, false)]
        );
        assert_eq!(
            texts(&[
                w("cresc.", 0.0),
                w("-", 40.0),
                w("dim.", 60.0),
                w("lo", 90.0)
            ]),
            [s("lo", false, false)]
        );
    }

    #[test]
    fn a_syllable_finds_its_note_and_a_stray_one_none() {
        let syl = |x: f64| Syl {
            text: "x".into(),
            x,
            left: x - 3.0,
            cont: false,
            ext: false,
        };
        let at = align(&[syl(10.0), syl(30.0), syl(31.0)], &[10.0, 30.0], 5.0);
        assert_eq!(at, [Some(0), Some(1), None]);
    }
}