use std::collections::HashSet;
use std::path::Path;
use std::time::Instant;
use bengali_spell_checker::{SpellChecker, normalize, tokenize};
use crate::dict;
const SUGGEST_LIMIT: usize = 10;
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)?;
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(" ")
}
}
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)
}
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);
}
}