accuracy/
main.rs

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
/*! Accuracy testing for Finite-State Spell-Checkers

A tool to help testing quality of finite-state spell-checkers. Shows precision
and recall and F scores.

# Usage examples

It's a command-line tool:
```console
$ cargo run -- typos.txt se.zhfst
```
will produce statistics of spelling corrections.

It is possible to fine-tune the options using a configuration file in json
format. The format of json file follows from the [`SpellerConfig`] definition in
the main library:
```console
$ cargo run -- --config config.json typos.txt se.zhfst
```
For automated testing in CI there is a --threshold parametre:
```console
$ cargo run -- --threshold 0.9 typos.txt se.zhfst
```
*/

use chrono::prelude::*;
use std::error::Error;
use std::{
    io::Write,
    path::Path,
    time::{Instant, SystemTime},
};

use distance::damerau_levenshtein;
use divvunspell::archive;
use divvunspell::speller::suggestion::Suggestion;
use divvunspell::speller::{ReweightingConfig, SpellerConfig};
use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use serde::Serialize;
use structopt::clap::{App, AppSettings, Arg};

static CFG: SpellerConfig = SpellerConfig {
    n_best: Some(10),
    max_weight: Some(10000.0),
    beam: None,
    reweight: Some(ReweightingConfig::default()),
    node_pool_size: 128,
    recase: true
};

fn load_words(
    path: &str,
    max_words: Option<usize>,
) -> Result<Vec<(String, String)>, Box<dyn Error>> {
    let mut rdr = csv::ReaderBuilder::new()
        .comment(Some(b'#'))
        .delimiter(b'\t')
        .has_headers(false)
        .flexible(true)
        .from_path(path)?;

    Ok(rdr
        .records()
        .filter_map(Result::ok)
        .filter_map(|r| {
            r.get(0)
                .and_then(|x| r.get(1).map(|y| (x.to_string(), y.to_string())))
        })
        .take(max_words.unwrap_or(std::usize::MAX))
        .collect())
}

#[derive(Debug, Default, Serialize, PartialOrd, Ord, PartialEq, Eq, Clone, Copy)]
struct Time {
    secs: u64,
    subsec_nanos: u32,
}

impl std::fmt::Display for Time {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let ms = self.secs * 1000 + (self.subsec_nanos as u64 / 1_000_000);
        write!(f, "{}ms", ms)
    }
}

#[derive(Debug, Serialize)]
struct AccuracyResult<'a> {
    input: &'a str,
    expected: &'a str,
    distance: usize,
    suggestions: Vec<Suggestion>,
    position: Option<usize>,
    time: Time,
}

#[derive(Debug, Serialize)]
struct Report<'a> {
    metadata: Option<&'a divvunspell::archive::meta::SpellerMetadata>,
    config: &'a SpellerConfig,
    summary: Summary,
    results: Vec<AccuracyResult<'a>>,
    start_timestamp: Time,
    total_time: Time,
}

#[derive(Serialize, Default, Debug, Clone)]
struct Summary {
    total_words: u32,
    first_position: u32,
    top_five: u32,
    any_position: u32,
    no_suggestions: u32,
    only_wrong: u32,
    slowest_lookup: Time,
    fastest_lookup: Time,
    average_time: Time,
    average_time_95pc: Time,
}

impl std::fmt::Display for Summary {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let percent =
            |v: u32| -> String { format!("{:.2}%", v as f32 / self.total_words as f32 * 100f32) };

        write!(
            f,
            "[#1] {} [^5] {} [any] {} [none] {} [wrong] {} [fast] {} [slow] {}",
            percent(self.first_position),
            percent(self.top_five),
            percent(self.any_position),
            percent(self.no_suggestions),
            percent(self.only_wrong),
            self.fastest_lookup,
            self.slowest_lookup
        )
    }
}

impl Summary {
    fn new<'a>(results: &[AccuracyResult<'a>]) -> Summary {
        let mut summary = Summary::default();

        results.iter().for_each(|result| {
            summary.total_words += 1;

            if let Some(position) = result.position {
                summary.any_position += 1;

                if position == 0 {
                    summary.first_position += 1;
                }

                if position < 5 {
                    summary.top_five += 1;
                }
            } else if result.suggestions.is_empty() {
                summary.no_suggestions += 1;
            } else {
                summary.only_wrong += 1;
            }
        });

        summary.slowest_lookup = results
            .iter()
            .max_by(|x, y| x.time.cmp(&y.time))
            .unwrap()
            .time;
        summary.fastest_lookup = results
            .iter()
            .min_by(|x, y| x.time.cmp(&y.time))
            .unwrap()
            .time;

        summary
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    pretty_env_logger::init();

    let matches = App::new("divvunspell-accuracy")
        .setting(AppSettings::ArgRequiredElseHelp)
        .version(env!("CARGO_PKG_VERSION"))
        .about("Accuracy testing for DivvunSpell.")
        .arg(
            Arg::with_name("config")
                .short("c")
                .takes_value(true)
                .help("Provide JSON config file to override test defaults"),
        )
        .arg(
            Arg::with_name("words")
                .value_name("WORDS")
                .help("The 'input -> expected' list in tab-delimited value file (TSV)"),
        )
        // .arg(
        //     Arg::with_name("bhfst")
        //         .value_name("BHFST")
        //         .help("Use the given BHFST file"),
        // )
        .arg(
            Arg::with_name("zhfst")
                .value_name("ZHFST")
                .help("Use the given ZHFST file"),
        )
        .arg(
            Arg::with_name("json-output")
                .short("o")
                .value_name("JSON-OUTPUT")
                .help("The file path for the JSON report output"),
        )
        .arg(
            Arg::with_name("tsv-output")
                .short("t")
                .value_name("TSV-OUTPUT")
                .help("The file path for the TSV line append"),
        )
        .arg(
            Arg::with_name("max-words")
                .short("w")
                .takes_value(true)
                .help("Truncate typos list to max number of words specified"),
        )
        .arg(
            Arg::with_name("threshold")
                .short("T")
                .takes_value(true)
                .help("Minimum precision @ 5 for automated testing"),
        )
        .get_matches();

    let cfg: SpellerConfig = match matches.value_of("config") {
        Some(path) => {
            let file = std::fs::File::open(path)?;
            serde_json::from_reader(file)?
        }
        None => CFG.clone(),
    };

    // let archive: BoxSpellerArchive<ThfstTransducer, ThfstTransducer> =
    //     match matches.value_of("bhfst") {
    //         Some(path) => BoxSpellerArchive::open(path)?,
    //         None => {
    //             eprintln!("No BHFST found for given path; aborting.");
    //             std::process::exit(1);
    //         }
    //     };

    let archive = match matches.value_of("zhfst") {
        Some(path) => archive::open(Path::new(path))?,
        None => {
            eprintln!("No ZHFST found for given path; aborting.");
            std::process::exit(1);
        }
    };

    let words = match matches.value_of("words") {
        Some(path) => load_words(
            path,
            matches
                .value_of("max-words")
                .and_then(|x| x.parse::<usize>().ok()),
        )?,
        None => {
            eprintln!("No word list for given path; aborting.");
            std::process::exit(1);
        }
    };

    let pb = ProgressBar::new(words.len() as u64);
    pb.set_style(
        ProgressStyle::default_bar()
            .template("{pos}/{len} [{percent}%] {wide_bar} {elapsed_precise}"),
    );

    let start_time = Instant::now();
    let results = words
        .par_iter()
        .progress_with(pb)
        .map(|(input, expected)| {
            let now = Instant::now();
            let suggestions = archive.speller().suggest_with_config(&input, &cfg);
            let now = now.elapsed();

            let time = Time {
                secs: now.as_secs(),
                subsec_nanos: now.subsec_nanos(),
            };

            let position = suggestions.iter().position(|x| x.value == expected);

            let distance = damerau_levenshtein(input, expected);
            AccuracyResult {
                input,
                expected,
                distance,
                time,
                suggestions,
                position,
            }
        })
        .collect::<Vec<_>>();

    let now = start_time.elapsed();
    let total_time = Time {
        secs: now.as_secs(),
        subsec_nanos: now.subsec_nanos(),
    };
    let now_date = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap();
    let start_timestamp = Time {
        secs: now_date.as_secs(),
        subsec_nanos: now_date.subsec_nanos(),
    };

    let summary = Summary::new(&results);
    println!("{}", summary);

    if let Some(path) = matches.value_of("json-output") {
        let output = std::fs::File::create(path)?;
        let report = Report {
            metadata: archive.metadata(),
            config: &cfg,
            summary: summary.clone(),
            results,
            start_timestamp,
            total_time,
        };
        println!("Writing JSON report…");
        serde_json::to_writer_pretty(output, &report)?;
    } else if let Some(path) = matches.value_of("tsv-output") {
        let mut output = match std::fs::OpenOptions::new().append(true).open(path) {
            Ok(f) => Ok(f),
            Err(_) => std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path),
        }?;
        let md = output.metadata()?;
        if md.len() == 0 {
            // new file, write headers:
            output
                .write_all(b"id\tdate\ttag/branch\ttop1\ttop5\tworse\tno suggs\twrong suggs\n")?;
        }
        let git_id = std::process::Command::new("git")
            .arg("rev-parse")
            .arg("--short")
            .arg("HEAD")
            .output()?;
        output.write_all(String::from_utf8(git_id.stdout).unwrap().trim().as_bytes())?;
        output.write_all(b"\t")?;
        output.write_all(Local::now().to_rfc3339().as_bytes())?;
        output.write_all(b"\t")?;
        let git_descr = std::process::Command::new("git").arg("describe").output()?;
        output.write_all(
            String::from_utf8(git_descr.stdout)
                .unwrap()
                .trim()
                .as_bytes(),
        )?;
        output.write_all(b"\t")?;
        output.write_all(summary.first_position.to_string().as_bytes())?;
        output.write_all(b"\t")?;
        output.write_all(summary.top_five.to_string().as_bytes())?;
        output.write_all(b"\t")?;
        output.write_all(summary.any_position.to_string().as_bytes())?;
        output.write_all(b"\t")?;
        output.write_all(summary.no_suggestions.to_string().as_bytes())?;
        output.write_all(b"\t")?;
        output.write_all(summary.only_wrong.to_string().as_bytes())?;
        output.write_all(b"\n")?;
    };

    println!("Done!");
    match matches.value_of("threshold") {
        Some(threshold) => {
            if threshold.parse::<f32>().unwrap() < (summary.top_five as f32/
                summary.total_words as f32 * 100.0) {
                Ok(())
            }
            else {
                Err("accuracy @5 lower threshold")?
            }
        },
        None => Ok(())
    }
}