bnspell-cli 0.1.0

Command-line Bengali (Bangla) spell checker
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use std::collections::HashSet;
use std::path::Path;
use std::time::Instant;

use bengali_spell_checker::{SpellChecker, normalize, tokenize};

use crate::dict;

/// `eval/run.ts` asks for 10 suggestions.
const SUGGEST_LIMIT: usize = 10;
/// Repeated checks of the formal list, same as `eval/run.ts`.
const CHECK_REPEATS: u32 = 200;

struct Inputs {
    pairs: Vec<(String, String)>,
    typos: Vec<(String, String)>,
    formal: Vec<String>,
    informal: Vec<String>,
}

struct Report {
    pairs: usize,
    correct_accepted: usize,
    caught: usize,
    top1: usize,
    top5: usize,
    formal_words: usize,
    formal_fp: Vec<String>,
    informal_words: usize,
    informal_fp: Vec<String>,
    rejected_correct: Vec<String>,
    accepted_misspelling: Vec<String>,
    load_s: f64,
    rss_delta: u64,
    hwm: u64,
    check_us: f64,
    suggest_median_ms: Option<f64>,
    suggest_p95_ms: Option<f64>,
}

struct TypoScore {
    pairs: usize,
    caught: usize,
    top1: usize,
    top5: usize,
    rejected_correct: Vec<String>,
    accepted_misspelling: Vec<String>,
    not_first: Vec<String>,
    suggest_median_ms: Option<f64>,
    suggest_p95_ms: Option<f64>,
}

struct Mem {
    rss: u64,
    hwm: u64,
}

pub fn run(dict_dir: &Path, package: &Path, verbose: bool) -> Result<(), String> {
    let inputs = load_inputs(package)?;
    // Baseline is after the eval inputs are loaded and before the dictionary.
    let baseline = mem();
    let files = dict::read_resources(dict_dir)?;
    let started = Instant::now();
    let mut checker = dict::checker_from(&files)?;
    let load_s = started.elapsed().as_secs_f64();
    drop(files);
    let after = mem();
    let mut report = evaluate(&checker, &inputs, "default")?;
    report.load_s = load_s;
    report.rss_delta = after.rss.saturating_sub(baseline.rss);
    report.hwm = after.hwm;
    let wiki = score_typos(&checker, &inputs.typos, "wiki default");
    checker.set_strict(true);
    let strict = evaluate(&checker, &inputs, "strict")?;
    let wiki_strict = score_typos(&checker, &inputs.typos, "wiki strict");
    print_table(&report, &strict);
    print_wiki(&wiki, &wiki_strict);
    print_footer("default", &report, verbose);
    print_footer("strict", &strict, verbose);
    if verbose {
        print_wiki_misses("default", &wiki);
        print_wiki_misses("strict", &wiki_strict);
    }
    Ok(())
}

fn load_inputs(package: &Path) -> Result<Inputs, String> {
    let pairs = read_pairs(&dict::read_file(&package.join("complex-words.txt"))?);
    let typos = read_typos(&dict::read_file(&package.join("eval/data/wiki-typos.tsv"))?);
    let formal = prose_words(&dict::read_file(
        &package.join("eval/data/correct-text.txt"),
    )?);
    let informal = prose_words(&dict::read_file(
        &package.join("eval/data/informal-text.txt"),
    )?);
    if pairs.is_empty() || typos.is_empty() || formal.is_empty() || informal.is_empty() {
        return Err("eval inputs produced no pairs or no tokens".to_string());
    }
    Ok(Inputs {
        pairs,
        typos,
        formal,
        informal,
    })
}

fn evaluate(checker: &SpellChecker, inputs: &Inputs, label: &str) -> Result<Report, String> {
    let mut formal_fp = Vec::new();
    for word in &inputs.formal {
        if !checker.correct(word) {
            formal_fp.push(word.clone());
        }
    }
    let mut informal_fp = Vec::new();
    for word in &inputs.informal {
        if !checker.correct(word) {
            informal_fp.push(word.clone());
        }
    }

    let mut correct_accepted = 0usize;
    let mut caught = 0usize;
    let mut top1 = 0usize;
    let mut top5 = 0usize;
    let mut suggest_ms = Vec::new();
    let mut rejected_correct = Vec::new();
    let mut accepted_misspelling = Vec::new();

    for (wrong, right) in &inputs.pairs {
        if checker.correct(right) {
            correct_accepted += 1;
        } else {
            rejected_correct.push(right.clone());
        }
        if checker.correct(wrong) {
            accepted_misspelling.push(wrong.clone());
            continue;
        }
        caught += 1;
        let started = Instant::now();
        let suggestions = checker.suggest(wrong, SUGGEST_LIMIT);
        let elapsed_ms = started.elapsed().as_secs_f64() * 1_000.0;
        suggest_ms.push(elapsed_ms);
        let fixes = right_fixes(checker, right);
        if suggestions.first().is_some_and(|word| fixes.contains(word)) {
            top1 += 1;
        }
        if suggestions.iter().take(5).any(|word| fixes.contains(word)) {
            top5 += 1;
        }
        if caught.is_multiple_of(25) {
            eprintln!("suggest {label} {caught} last_ms {elapsed_ms:.1}");
        }
    }

    suggest_ms.sort_by(f64::total_cmp);
    let suggest_median_ms = suggest_ms.first().map(|_| percentile(&suggest_ms, 0.5));
    let suggest_p95_ms = suggest_ms.first().map(|_| percentile(&suggest_ms, 0.95));
    let check_us = check_micros(checker, &inputs.formal);
    Ok(Report {
        pairs: inputs.pairs.len(),
        correct_accepted,
        caught,
        top1,
        top5,
        formal_words: inputs.formal.len(),
        formal_fp,
        informal_words: inputs.informal.len(),
        informal_fp,
        rejected_correct,
        accepted_misspelling,
        load_s: 0.0,
        rss_delta: 0,
        hwm: 0,
        check_us,
        suggest_median_ms,
        suggest_p95_ms,
    })
}

fn score_typos(checker: &SpellChecker, pairs: &[(String, String)], label: &str) -> TypoScore {
    let mut caught = 0usize;
    let mut top1 = 0usize;
    let mut top5 = 0usize;
    let mut suggest_ms = Vec::new();
    let mut rejected_correct = Vec::new();
    let mut accepted_misspelling = Vec::new();
    let mut not_first = Vec::new();
    for (wrong, right) in pairs {
        let fixes = right_fixes(checker, right);
        if !checker.correct(right) {
            rejected_correct.push(right.clone());
        }
        if checker.correct(wrong) {
            accepted_misspelling.push(wrong.clone());
            continue;
        }
        caught += 1;
        let started = Instant::now();
        let suggestions = checker.suggest(wrong, SUGGEST_LIMIT);
        let elapsed_ms = started.elapsed().as_secs_f64() * 1_000.0;
        suggest_ms.push(elapsed_ms);
        if suggestions.first().is_some_and(|word| fixes.contains(word)) {
            top1 += 1;
        } else {
            let got = suggestions.first().map(String::as_str).unwrap_or("—");
            not_first.push(format!("{wrong} → {right} (got {got})"));
        }
        if suggestions.iter().take(5).any(|word| fixes.contains(word)) {
            top5 += 1;
        }
        if caught.is_multiple_of(25) {
            eprintln!("suggest {label} {caught} last_ms {elapsed_ms:.1}");
        }
    }
    suggest_ms.sort_by(f64::total_cmp);
    TypoScore {
        pairs: pairs.len(),
        caught,
        top1,
        top5,
        rejected_correct,
        accepted_misspelling,
        not_first,
        suggest_median_ms: suggest_ms.first().map(|_| percentile(&suggest_ms, 0.5)),
        suggest_p95_ms: suggest_ms.first().map(|_| percentile(&suggest_ms, 0.95)),
    }
}

fn check_micros(checker: &SpellChecker, words: &[String]) -> f64 {
    let mut accepted = 0u64;
    let started = Instant::now();
    for _ in 0..CHECK_REPEATS {
        for word in words {
            if checker.correct(std::hint::black_box(word)) {
                accepted += 1;
            }
        }
    }
    std::hint::black_box(accepted);
    let ops = f64::from(CHECK_REPEATS) * words.len() as f64;
    started.elapsed().as_secs_f64() * 1e6 / ops
}

fn print_table(default: &Report, strict: &Report) {
    let rows = [
        (
            format!("Correct spelling accepted ({} pairs)", default.pairs),
            pct(default.correct_accepted, default.pairs),
            pct(strict.correct_accepted, strict.pairs),
        ),
        (
            "Misspelling caught".to_string(),
            pct(default.caught, default.pairs),
            pct(strict.caught, strict.pairs),
        ),
        (
            "Right fix is the first suggestion".to_string(),
            pct(default.top1, default.pairs),
            pct(strict.top1, strict.pairs),
        ),
        (
            "Right fix in the top 5".to_string(),
            pct(default.top5, default.pairs),
            pct(strict.top5, strict.pairs),
        ),
        (
            format!(
                "False positives on formal text ({} words)",
                default.formal_words
            ),
            pct_count(default.formal_fp.len(), default.formal_words),
            pct_count(strict.formal_fp.len(), strict.formal_words),
        ),
        (
            format!(
                "False positives on informal text ({} words)",
                default.informal_words
            ),
            pct_count(default.informal_fp.len(), default.informal_words),
            pct_count(strict.informal_fp.len(), strict.informal_words),
        ),
        (
            "Dictionary load".to_string(),
            format!("{:.6} s", default.load_s),
            "—".to_string(),
        ),
        (
            "Heap after load".to_string(),
            format!("RSS +{} (HWM {})", default.rss_delta, default.hwm),
            "—".to_string(),
        ),
        (
            "Check, per word".to_string(),
            format!("{:.3} µs", default.check_us),
            format!("{:.3} µs", strict.check_us),
        ),
        (
            "Suggest, median / p95".to_string(),
            suggest_cell(default),
            suggest_cell(strict),
        ),
    ];
    println!("| Metric | Default | Strict |");
    println!("|---|---|---|");
    for (label, left, right) in rows {
        println!("| {label} | {left} | {right} |");
    }
}

fn print_wiki(default: &TypoScore, strict: &TypoScore) {
    let rows = [
        (
            "Misspelling caught".to_string(),
            pct(default.caught, default.pairs),
            pct(strict.caught, strict.pairs),
        ),
        (
            "Right fix is the first suggestion".to_string(),
            pct(default.top1, default.pairs),
            pct(strict.top1, strict.pairs),
        ),
        (
            "Right fix in the top 5".to_string(),
            pct(default.top5, default.pairs),
            pct(strict.top5, strict.pairs),
        ),
        (
            "Right fix is the first suggestion, among caught".to_string(),
            pct(default.top1, default.caught),
            pct(strict.top1, strict.caught),
        ),
        (
            "Right fix in the top 5, among caught".to_string(),
            pct(default.top5, default.caught),
            pct(strict.top5, strict.caught),
        ),
        (
            "Suggest, median / p95".to_string(),
            typo_suggest_cell(default),
            typo_suggest_cell(strict),
        ),
    ];
    println!("\nReal typos (Wikipedia), {} pairs", default.pairs);
    println!("| Metric | Default | Strict |");
    println!("|---|---|---|");
    for (label, left, right) in rows {
        println!("| {label} | {left} | {right} |");
    }
}

fn print_wiki_misses(mode: &str, score: &TypoScore) {
    println!(
        "\nCorrect words rejected (Wikipedia, {mode}, {}):\n{}",
        score.rejected_correct.len(),
        score.rejected_correct.join(" ")
    );
    println!(
        "\nMisspellings accepted (Wikipedia, {mode}, {}):\n{}",
        score.accepted_misspelling.len(),
        score.accepted_misspelling.join(" ")
    );
    println!(
        "\nRight fix not first (Wikipedia, {mode}, {}):\n{}",
        score.not_first.len(),
        score.not_first.join("\n")
    );
}

fn typo_suggest_cell(score: &TypoScore) -> String {
    match (score.suggest_median_ms, score.suggest_p95_ms) {
        (Some(median), Some(p95)) => format!("{median:.3} / {p95:.3} ms"),
        _ => "n/a".to_string(),
    }
}

fn suggest_cell(report: &Report) -> String {
    match (report.suggest_median_ms, report.suggest_p95_ms) {
        (Some(median), Some(p95)) => format!("{median:.3} / {p95:.3} ms"),
        _ => "n/a".to_string(),
    }
}

fn print_footer(mode: &str, report: &Report, verbose: bool) {
    for (kind, words) in [
        ("formal text", report.formal_fp.as_slice()),
        ("informal text", report.informal_fp.as_slice()),
    ] {
        let unique = unique_words(words);
        let list = if unique.is_empty() {
            "none".to_string()
        } else {
            unique.join(" ")
        };
        println!("\nFalse positives on {kind} ({mode}): {list}");
    }
    if !verbose {
        return;
    }
    for (kind, words) in [
        ("formal text", report.formal_fp.as_slice()),
        ("informal text", report.informal_fp.as_slice()),
    ] {
        println!(
            "\nFalse positives on {kind} ({mode}, {}):\n{}",
            words.len(),
            false_positive_counts(words)
        );
    }
    println!(
        "\nCorrect words rejected ({mode}, {}):\n{}",
        report.rejected_correct.len(),
        report.rejected_correct.join(" ")
    );
    println!(
        "\nMisspellings accepted ({mode}, {}):\n{}",
        report.accepted_misspelling.len(),
        report.accepted_misspelling.join(" ")
    );
}

fn pct(num: usize, den: usize) -> String {
    if den == 0 {
        return "0.0%".to_string();
    }
    format!("{:.1}%", (num as f64 / den as f64) * 100.0)
}

fn pct_count(num: usize, den: usize) -> String {
    format!("{} ({num})", pct(num, den))
}

fn unique_words(words: &[String]) -> Vec<&str> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for word in words {
        if seen.insert(word.as_str()) {
            out.push(word.as_str());
        }
    }
    out
}

fn false_positive_counts(words: &[String]) -> String {
    let mut counts: Vec<(&str, usize)> = Vec::new();
    for word in words {
        if let Some(slot) = counts.iter_mut().find(|(seen, _)| *seen == word.as_str()) {
            slot.1 += 1;
        } else {
            counts.push((word.as_str(), 1));
        }
    }
    if counts.is_empty() {
        "none".to_string()
    } else {
        counts
            .iter()
            .map(|(word, count)| format!("{word} ({count})"))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// Same index as `eval/run.ts`: `sorted[min(len - 1, floor(len * p))]`.
fn percentile(sorted: &[f64], p: f64) -> f64 {
    let idx = (sorted.len() as f64 * p).floor() as usize;
    sorted[idx.min(sorted.len() - 1)]
}

fn read_typos(text: &str) -> Vec<(String, String)> {
    let mut seen = HashSet::new();
    let mut pairs = Vec::new();
    for line in text.split('\n') {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut cols = line.split('\t');
        let Some(wrong) = cols.next() else {
            continue;
        };
        let Some(right) = cols.next() else {
            continue;
        };
        let wrong = wrong.trim();
        let right = right.trim();
        if wrong.is_empty() || right.is_empty() || wrong.contains(' ') || right.contains(' ') {
            continue;
        }
        if seen.insert(format!("{wrong}\t{right}")) {
            pairs.push((wrong.to_string(), right.to_string()));
        }
    }
    pairs
}

fn read_pairs(text: &str) -> Vec<(String, String)> {
    let mut seen = HashSet::new();
    let mut pairs = Vec::new();
    for line in text.split('\n') {
        let Some((wrong, right)) = line.split_once(" - ") else {
            continue;
        };
        let wrong = wrong.trim();
        let right = right.trim();
        if wrong.is_empty() || right.is_empty() || wrong.contains(' ') || right.contains(' ') {
            continue;
        }
        if seen.insert(format!("{wrong}\t{right}")) {
            pairs.push((wrong.to_string(), right.to_string()));
        }
    }
    pairs
}

fn prose_words(text: &str) -> Vec<String> {
    let body = text
        .split('\n')
        .filter(|line| !line.trim().is_empty() && !line.starts_with('#'))
        .collect::<Vec<_>>()
        .join("\n");
    tokenize(&body)
        .into_iter()
        .map(|token| token.word)
        .collect()
}

fn mem() -> Mem {
    let text = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
    let mut rss = 0u64;
    let mut hwm = 0u64;
    for line in text.lines() {
        if let Some(rest) = line.strip_prefix("VmRSS:") {
            rss = kib(rest);
        } else if let Some(rest) = line.strip_prefix("VmHWM:") {
            hwm = kib(rest);
        }
    }
    Mem { rss, hwm }
}

fn kib(rest: &str) -> u64 {
    rest.split_whitespace()
        .next()
        .unwrap_or("0")
        .parse::<u64>()
        .unwrap_or(0)
        .saturating_mul(1024)
}

/// The reference, plus its Academy form when the reference is a listed variant:
/// suggestions offer the Academy form, so either one is the right fix.
fn right_fixes(checker: &SpellChecker, right: &str) -> Vec<String> {
    let target = normalize(right);
    let mut fixes = vec![target.clone()];
    if checker.correct_with(&target, false) && !checker.correct_with(&target, true) {
        fixes.extend(checker.suggest_with(&target, 1, true));
    }
    fixes
}

#[cfg(test)]
mod tests {
    use super::{percentile, prose_words, read_pairs, read_typos};

    #[test]
    fn typos_ignore_comments_counts_and_duplicate_pairs() {
        let pairs = read_typos("# comment\nআ - ইগনোর\nক\tখ\t9\nক\tখ\t2\n\n");
        assert_eq!(pairs, vec![("ক".to_string(), "খ".to_string())]);
    }

    #[test]
    fn pairs_skip_phrases_and_keep_the_first_duplicate() {
        let pairs = read_pairs("a - b\nক - খ খ\na - b\nno separator\n");
        assert_eq!(pairs, vec![("a".to_string(), "b".to_string())]);
    }

    #[test]
    fn prose_skips_comments_and_blank_lines() {
        assert_eq!(
            prose_words("# comment\n\nআমি যাই।\n"),
            vec!["আমি".to_string(), "যাই".to_string()]
        );
    }

    #[test]
    fn percentile_matches_the_eval_script() {
        let values = [0.0, 10.0, 20.0, 30.0];
        assert_eq!(percentile(&values, 0.5), 20.0);
        assert_eq!(percentile(&values, 0.95), 30.0);
    }
}