bnspell-cli 0.1.0

Command-line Bengali (Bangla) spell checker
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use bengali_spell_checker::{SpellChecker, normalize, tokenize};
use icu_collator::Collator;
use icu_collator::options::CollatorOptions;
use icu_locale_core::locale;

struct Row {
    count: usize,
    files: HashSet<PathBuf>,
    context: String,
}

pub fn run(
    checker: &SpellChecker,
    dir: &Path,
    out: Option<&Path>,
    suggest_n: usize,
) -> Result<(), String> {
    let files = list_texts(dir)?;
    let mut rows: HashMap<String, Row> = HashMap::new();
    let mut tokens = 0usize;
    let mut flagged = 0usize;
    for path in &files {
        let text = std::fs::read_to_string(path)
            .map_err(|err| format!("read {}: {err}", path.display()))?;
        tokens += tokenize(&text).len();
        for token in checker.check(&text) {
            flagged += 1;
            let word = normalize(&token.word);
            let row = rows.entry(word).or_insert_with(|| Row {
                count: 0,
                files: HashSet::new(),
                context: snippet(&text, token.start_utf16, token.end_utf16),
            });
            row.count += 1;
            row.files.insert(path.clone());
        }
    }
    let distinct = rows.len();
    if let Some(path) = out {
        write_tsv(checker, &mut rows, path, suggest_n)?;
    }
    println!("{}", summary_line(files.len(), tokens, flagged, distinct));
    Ok(())
}

fn write_tsv(
    checker: &SpellChecker,
    rows: &mut HashMap<String, Row>,
    path: &Path,
    suggest_n: usize,
) -> Result<(), String> {
    let mut ranked: Vec<(String, Row)> = rows.drain().collect();
    let collator = bengali_collator()?;
    ranked.sort_by(|a, b| {
        b.1.count
            .cmp(&a.1.count)
            .then_with(|| collator.compare(&a.0, &b.0))
    });
    let mut header = vec!["word".to_string(), "count".to_string(), "files".to_string()];
    for index in 1..=suggest_n {
        header.push(format!("suggestion{index}"));
    }
    header.push("context".to_string());
    let mut lines = vec![header.join("\t")];
    let mut suggested = 0usize;
    for (index, (word, row)) in ranked.iter().enumerate() {
        let want = row.count >= 2 || index < 300;
        let suggestions = if want {
            suggested += 1;
            if suggested.is_multiple_of(100) {
                eprintln!("suggestions {suggested}");
            }
            checker.suggest(word, suggest_n)
        } else {
            Vec::new()
        };
        let mut cells = vec![
            tsv_cell(word),
            row.count.to_string(),
            row.files.len().to_string(),
        ];
        for slot in 0..suggest_n {
            cells.push(
                suggestions
                    .get(slot)
                    .map(|item| tsv_cell(item))
                    .unwrap_or_default(),
            );
        }
        cells.push(tsv_cell(&row.context));
        lines.push(cells.join("\t"));
    }
    let mut text = lines.join("\n");
    text.push('\n');
    std::fs::write(path, text).map_err(|err| format!("write {}: {err}", path.display()))
}

fn summary_line(files: usize, tokens: usize, flagged: usize, distinct: usize) -> String {
    let pct = if tokens == 0 {
        "0.00".to_string()
    } else {
        format!("{:.2}", flagged as f64 / tokens as f64 * 100.0)
    };
    format!(
        "files {files} | bengali tokens {tokens} | flagged {flagged} ({pct}%) | distinct {distinct}"
    )
}

fn bengali_collator() -> Result<icu_collator::CollatorBorrowed<'static>, String> {
    Collator::try_new(locale!("bn").into(), CollatorOptions::default())
        .map_err(|err| format!("bengali collation: {err}"))
}

fn list_texts(root: &Path) -> Result<Vec<PathBuf>, String> {
    let mut out = Vec::new();
    walk(root, &mut out)?;
    out.sort();
    Ok(out)
}

fn walk(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> {
    let entries = std::fs::read_dir(dir).map_err(|err| format!("read {}: {err}", dir.display()))?;
    for entry in entries {
        let entry = entry.map_err(|err| format!("read {}: {err}", dir.display()))?;
        let path = entry.path();
        let kind = entry
            .file_type()
            .map_err(|err| format!("stat {}: {err}", path.display()))?;
        if kind.is_dir() {
            walk(&path, out)?;
        } else if kind.is_file() && is_txt(&path) {
            out.push(path);
        }
    }
    Ok(())
}

fn is_txt(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name.ends_with(".txt"))
}

/// About six whitespace-separated words: three before the token and two after.
fn snippet(text: &str, start: usize, end: usize) -> String {
    let before = slice_utf16(text, start.saturating_sub(180), start);
    let word = slice_utf16(text, start, end);
    let after = slice_utf16(text, end, end.saturating_add(180));
    let before_words: Vec<&str> = before.split_whitespace().collect();
    let from = before_words.len().saturating_sub(3);
    let mut parts: Vec<&str> = before_words[from..].to_vec();
    parts.push(word);
    parts.extend(after.split_whitespace().take(2));
    collapse_space(&parts.join(" "))
}

fn slice_utf16(text: &str, start: usize, end: usize) -> &str {
    let end = end.max(start);
    &text[utf16_byte(text, start)..utf16_byte(text, end)]
}

fn utf16_byte(text: &str, index: usize) -> usize {
    let mut units = 0usize;
    for (byte, ch) in text.char_indices() {
        if units >= index {
            return byte;
        }
        units += ch.len_utf16();
    }
    text.len()
}

fn collapse_space(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut spaced = false;
    for ch in text.chars() {
        if ch.is_whitespace() {
            spaced = true;
            continue;
        }
        if spaced && !out.is_empty() {
            out.push(' ');
        }
        spaced = false;
        out.push(ch);
    }
    out
}

fn tsv_cell(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut skipping = false;
    for ch in text.chars() {
        if ch == '\t' || ch == '\n' || ch == '\r' {
            if !skipping {
                out.push(' ');
                skipping = true;
            }
            continue;
        }
        skipping = false;
        out.push(ch);
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{bengali_collator, slice_utf16, snippet, summary_line};

    #[test]
    fn summary_matches_the_corpus_script() {
        assert_eq!(
            summary_line(2, 0, 0, 0),
            "files 2 | bengali tokens 0 | flagged 0 (0.00%) | distinct 0"
        );
        assert_eq!(
            summary_line(3, 200, 1, 1),
            "files 3 | bengali tokens 200 | flagged 1 (0.50%) | distinct 1"
        );
    }

    #[test]
    fn snippet_keeps_three_words_before_and_two_after() {
        let text = "one two three four TARGET five six seven";
        let start = text.find("TARGET").unwrap();
        let end = start + "TARGET".len();
        assert_eq!(snippet(text, start, end), "two three four TARGET five six");
    }

    #[test]
    fn utf16_slice_counts_a_surrogate_pair_as_two() {
        let text = "\u{1F600}ক";
        assert_eq!(slice_utf16(text, 2, 3), "ক");
    }

    #[test]
    fn bengali_order_puts_the_higher_count_first() {
        let collator = bengali_collator().unwrap();
        let mut rows = [("খ".to_string(), 1usize), ("ক".to_string(), 3)];
        rows.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| collator.compare(&a.0, &b.0)));
        assert_eq!(rows[0].0, "ক");
        let mut tied = [("খ".to_string(), 1usize), ("ক".to_string(), 1)];
        tied.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| collator.compare(&a.0, &b.0)));
        assert_eq!(tied[0].0, "ক");
        assert_eq!(collator.compare("ক", "খ"), std::cmp::Ordering::Less);
    }
}