Debian Codegraph @

tests/verify.cxx

raw symbols SCIP
1 /* Copyright 2016-2024 Dimitrij Mijoski
2 *
3 * This file is part of Nuspell.
4 *
5 * Nuspell is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * Nuspell is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with Nuspell. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <hunspell/hunspell.hxx>
20 #include <nuspell/dictionary.hxx>
21 #include <nuspell/finder.hxx>
22
23 #include <chrono>
24 #include <clocale>
25 #include <fstream>
26 #include <iostream>
27 #include <unicode/ucnv.h>
28
29 #include <getopt.h>
30
31 #if __has_include(<unistd.h>)
32 #include <unistd.h> // defines _POSIX_VERSION
33 #endif
34 #ifdef _POSIX_VERSION
35 #include <langinfo.h>
36 #include <sys/resource.h>
37 #include <sys/time.h>
38 #endif
39 #ifdef _WIN32
40 #include <io.h>
41 #ifndef NOMINMAX
42 #define NOMINMAX
43 #endif
44 #define WIN32_LEAN_AND_MEAN
45 #include <windows.h>
46
47 #include <psapi.h>
48 #endif
49
50 // manually define if not supplied by the build system
51 #ifndef PROJECT_VERSION
52 #define PROJECT_VERSION "unknown.version"
53 #endif
54
55 using namespace std;
56 using nuspell::Dictionary, nuspell::Dictionary_Loading_Error,
57 nuspell::Dict_Finder_For_CLI_Tool_2;
58 namespace {
59 enum Mode { NORMAL, HELP, VERSION };
60 auto print_help(const char* program_name) -> void
61 {
62 auto p = string_view(program_name);
63 auto& o = cout;
64 o << "Usage:\n"
65 << p << " [-d dict_NAME] [OPTION]... [FILE...]\n"
66 << p << " --help|--version\n"
67 << R"(
68 Check spelling of each FILE, and measure speed and correctness in regard to
69 other spellchecking libraries. If no FILE is specified, check standard input.
70 The input text should be a simple wordlist with one word per line.
71
72 -d, --dictionary=di_CT use di_CT dictionary (only one is supported)
73 -m, --print-mismatches print mismatches (false positives and negatives)
74 -s, --test-suggestions call suggest function (useful only for debugging)
75 -w, --wikipedia-list input is Wikipedia's list of common misspellings
76 --encoding=enc set both input and output encoding
77 --input-encoding=enc input encoding, default is active locale
78 --output-encoding=enc (UNUSED, always UTF-8) output encoding, default is
79 active locale
80 --help print this help
81 --version print version number
82
83 The following environment variables can have effect:
84
85 DICTIONARY - same as -d,
86 DICPATH - additional directory path to search for dictionaries.
87
88 Example:
89 )"
90 << " " << p << " -d en_US file.txt\n"
91 << " " << p << " -d ../../subdir/di_CT.aff\n";
92 }
93
94 auto ver_str = "nuspell " PROJECT_VERSION R"(
95 Copyright 2016-2024 Dimitrij Mijoski
96 License LGPLv3+: GNU LGPL version 3 or later <http://gnu.org/licenses/lgpl.html>.
97 This is free software: you are free to change and redistribute it.
98 There is NO WARRANTY, to the extent permitted by law.
99
100 Written by Dimitrij Mijoski.
101 )";
102
103 auto print_version() -> void { cout << ver_str; }
104
105 auto get_peak_ram_usage() -> long
106 {
107 #ifdef _POSIX_VERSION
108 rusage r;
109 auto err = getrusage(RUSAGE_SELF, &r);
110 if (!err)
111 return r.ru_maxrss;
112 #elif _WIN32
113 PROCESS_MEMORY_COUNTERS pmc;
114 auto suc = GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
115 if (suc)
116 return pmc.PeakWorkingSetSize >> 10;
117 #endif
118 return 0;
119 }
120
121 auto to_utf8(string_view source, string& dest, UConverter* ucnv,
122 UErrorCode& uerr)
123 {
124 dest.resize(dest.capacity());
125 auto len = ucnv_toAlgorithmic(UCNV_UTF8, ucnv, dest.data(), dest.size(),
126 source.data(), source.size(), &uerr);
127 dest.resize(len);
128 if (uerr == U_BUFFER_OVERFLOW_ERROR) {
129 uerr = U_ZERO_ERROR;
130 ucnv_toAlgorithmic(UCNV_UTF8, ucnv, dest.data(), dest.size(),
131 source.data(), source.size(), &uerr);
132 }
133 }
134
135 auto from_utf8(string_view source, string& dest, UConverter* ucnv,
136 UErrorCode& uerr)
137 {
138 dest.resize(dest.capacity());
139 auto len =
140 ucnv_fromAlgorithmic(ucnv, UCNV_UTF8, dest.data(), dest.size(),
141 source.data(), source.size(), &uerr);
142 dest.resize(len);
143 if (uerr == U_BUFFER_OVERFLOW_ERROR) {
144 uerr = U_ZERO_ERROR;
145 ucnv_fromAlgorithmic(ucnv, UCNV_UTF8, dest.data(), dest.size(),
146 source.data(), source.size(), &uerr);
147 }
148 }
149
150 struct Options {
151 bool print_mismatches = false;
152 bool test_suggestions = false;
153 bool wikipedia_list = false;
154 };
155
156 auto process_text(Options opt, const Dictionary& dic, Hunspell& hun,
157 UConverter* hun_cnv, istream& in, UConverter* in_cnv,
158 ostream& out, UErrorCode& uerr)
159 {
160 using Duration = chrono::high_resolution_clock::duration;
161 string word, line, u8_tmp_buf, hun_word;
162 size_t total = 0;
163 size_t true_pos = 0, true_neg = 0, false_pos = 0, false_neg = 0;
164 Duration time_nu_true = {}, time_nu_false = {};
165 Duration time_hun_true = {}, time_hun_false = {};
166
167 auto nus_sugs = vector<string>();
168 Duration time_nu_sugs = {}, time_hun_sugs = {};
169 size_t nus_hits = 0, nus_misses = 0, nus_sum_orders = 0;
170 size_t hun_hits = 0, hun_misses = 0, hun_sum_orders = 0;
171
172 auto hun_enc =
173 nuspell::Encoding(hun.get_dict_encoding()).value_or_default();
174 auto in_is_utf8 = ucnv_getType(in_cnv) == UCNV_UTF8;
175 // auto out_is_utf8 = ucnv_getType(out_cnv) == UCNV_UTF8;
176 auto hun_is_utf8 = ucnv_getType(hun_cnv) == UCNV_UTF8;
177
178 for (;;) {
179 size_t i = 0;
180 if (opt.wikipedia_list) {
181 if (!getline(in, line))
182 break;
183 if (line.empty() || line.front() == '#')
184 continue;
185 auto rtrim_idx = line.find_last_not_of(" \t\r");
186 if (rtrim_idx != line.npos)
187 line.erase(++rtrim_idx);
188 if (!in_is_utf8) {
189 to_utf8(line, u8_tmp_buf, in_cnv, uerr);
190 line = u8_tmp_buf;
191 }
192 if ((i = line.find("->")) != line.npos) {
193 word.assign(line, 0, i);
194 i += 2;
195 }
196 else if ((i = line.find('\t')) != line.npos) {
197 word.assign(line, 0, i);
198 i += 1;
199 }
200 else
201 continue;
202 }
203 else if (in >> word) {
204 if (!in_is_utf8) {
205 to_utf8(word, u8_tmp_buf, in_cnv, uerr);
206 word = u8_tmp_buf;
207 }
208 }
209 else
210 break;
211 auto time_a = chrono::high_resolution_clock::now();
212 auto res_nu = dic.spell(word);
213 auto time_b = chrono::high_resolution_clock::now();
214 if (hun_is_utf8)
215 hun_word = word;
216 else
217 from_utf8(word, hun_word, hun_cnv, uerr);
218 auto res_hun = hun.spell(hun_word);
219 auto time_c = chrono::high_resolution_clock::now();
220 auto time_nu = time_b - time_a;
221 auto time_hun = time_c - time_b;
222 if (res_nu)
223 time_nu_true += time_nu;
224 else
225 time_nu_false += time_nu;
226 if (res_hun)
227 time_hun_true += time_hun;
228 else
229 time_hun_false += time_hun;
230 if (res_hun) {
231 if (res_nu) {
232 ++true_pos;
233 }
234 else {
235 ++false_neg;
236 if (opt.print_mismatches)
237 out << "FN: " << word << '\n';
238 }
239 }
240 else {
241 if (res_nu) {
242 ++false_pos;
243 if (opt.print_mismatches)
244 out << "FP: " << word << '\n';
245 }
246 else {
247 ++true_neg;
248 }
249 }
250 ++total;
251
252 if (!opt.test_suggestions && !opt.wikipedia_list)
253 continue;
254 time_a = chrono::high_resolution_clock::now();
255 dic.suggest(word, nus_sugs);
256 time_b = chrono::high_resolution_clock::now();
257 auto hun_sugs = hun.suggest(hun_word);
258 time_c = chrono::high_resolution_clock::now();
259 time_nu_sugs += time_b - time_a;
260 time_hun_sugs += time_c - time_b;
261 if (!opt.wikipedia_list)
262 continue;
263 if (opt.print_mismatches && (res_nu || res_hun)) {
264 out << "Word " << word << " detected as correct.\n"
265 << "Suggestions from list: " << line.substr(i)
266 << '\n';
267 }
268 if (opt.print_mismatches && res_nu && !empty(nus_sugs)) {
269 out << "Nuspell sugs : ";
270 for (auto it = begin(nus_sugs);;) {
271 out << *it;
272 if (++it == end(nus_sugs))
273 break;
274 out << ", ";
275 }
276 out << '\n';
277 }
278
279 for (auto& hs : hun_sugs) {
280 to_utf8(hs, u8_tmp_buf, hun_cnv, uerr);
281 hs = u8_tmp_buf;
282 }
283 // hun_sugs is now utf8
284
285 if (opt.print_mismatches && res_hun && !empty(hun_sugs)) {
286 out << "Hunspell sugs: ";
287 for (auto it = begin(hun_sugs);;) {
288 out << *it;
289 if (++it == end(hun_sugs))
290 break;
291 out << ", ";
292 }
293 out << '\n';
294 }
295 for (auto needle = ", "sv;;) {
296 auto j = line.find(needle, i);
297 auto wiki_sug = line.substr(i, j - i);
298
299 // process wiki_sug
300 auto it =
301 find(begin(nus_sugs), end(nus_sugs), wiki_sug);
302 if (it != end(nus_sugs)) {
303 ++nus_hits;
304 auto order = distance(begin(nus_sugs), it) + 1;
305 nus_sum_orders += order;
306 }
307 else {
308 ++nus_misses;
309 }
310
311 it = find(begin(hun_sugs), end(hun_sugs), wiki_sug);
312 if (it != end(hun_sugs)) {
313 ++hun_hits;
314 auto order = distance(begin(hun_sugs), it) + 1;
315 hun_sum_orders += order;
316 }
317 else {
318 ++hun_misses;
319 }
320
321 // stop condition
322 if (j == line.npos)
323 break;
324 // increment
325 i = j + size(needle);
326 }
327 if (total % 100 == 0)
328 out << total << " words processed." << endl;
329 }
330 out << "Total Words = " << total << '\n';
331 if (total == 0)
332 return;
333 auto accuracy = (true_pos + true_neg) * 1.0 / total;
334 auto precision = true_pos * 1.0 / (true_pos + false_pos);
335 auto total_hun_time = time_hun_true + time_hun_false;
336 auto total_nu_time = time_nu_true + time_nu_false;
337 auto speedup = total_hun_time.count() * 1.0 / total_nu_time.count();
338 out << "TP = " << true_pos << '\n';
339 out << "TN = " << true_neg << '\n';
340 out << "FP = " << false_pos << '\n';
341 out << "FN = " << false_neg << '\n';
342 out << "Accuracy = " << accuracy << '\n';
343 out << "Precision = " << precision << '\n';
344 out << "Time Nuspell True = " << time_nu_true.count() << '\n';
345 out << "Time Nuspell False = " << time_nu_false.count() << '\n';
346 out << "Time Hunspell True = " << time_hun_true.count() << '\n';
347 out << "Time Hunspell False = " << time_hun_false.count() << '\n';
348 out << "Speedup = " << speedup << '\n';
349 if (!opt.test_suggestions && !opt.wikipedia_list)
350 return;
351 out << '\n';
352 out << "Nus hits = " << nus_hits << '\n';
353 out << "Nus misses = " << nus_misses << '\n';
354 out << "Nus avg order = " << nus_sum_orders * 1.0 / nus_hits << '\n';
355 out << "Hun hits = " << hun_hits << '\n';
356 out << "Hun misses = " << hun_misses << '\n';
357 out << "Hun avg order = " << hun_sum_orders * 1.0 / hun_hits << '\n';
358 out << "Time Nuspell sugs = " << time_nu_sugs.count() << '\n';
359 out << "Time Hunspell sugs = " << time_hun_sugs.count() << '\n';
360 }
361 } // namespace
362 int main(int argc, char* argv[])
363 {
364 auto mode_int = int(Mode::NORMAL);
365 auto program_name = "nuspell";
366 auto dictionary = string();
367 auto input_enc = string();
368 auto output_enc = string();
369 auto options = Options();
370
371 if (argc > 0 && argv[0])
372 program_name = argv[0];
373
374 ios_base::sync_with_stdio(false);
375
376 auto optstring = "d:msw";
377 option longopts[] = {
378 {"help", no_argument, &mode_int, Mode::HELP},
379 {"version", no_argument, &mode_int, Mode::VERSION},
380 {"dictionary", required_argument, nullptr, 'd'},
381 {"print-mismatches", no_argument, nullptr, 'm'},
382 {"test-suggestions", no_argument, nullptr, 's'},
383 {"wikipedia-list", no_argument, nullptr, 'w'},
384 {"encoding", required_argument, nullptr, 'e'},
385 {"input-encoding", required_argument, nullptr, 'i'},
386 {"output-encoding", required_argument, nullptr, 'o'},
387 {}};
388 int longindex;
389 int c;
390 while ((c = getopt_long(argc, argv, optstring, longopts, &longindex)) !=
391 -1) {
392 switch (c) {
393 case 0:
394 // check longopts[longindex] if needed
395 break;
396 case 'd':
397 dictionary = optarg;
398 break;
399 case 'm':
400 options.print_mismatches = true;
401 break;
402 case 's':
403 options.test_suggestions = true;
404 break;
405 case 'w':
406 options.wikipedia_list = true;
407 break;
408 case 'e':
409 input_enc = optarg;
410 output_enc = optarg;
411 break;
412 case 'i':
413 input_enc = optarg;
414 break;
415 case 'o':
416 output_enc = optarg;
417 break;
418 case '?':
419 return EXIT_FAILURE;
420 }
421 }
422 auto mode = static_cast<Mode>(mode_int);
423 if (mode == Mode::VERSION) {
424 print_version();
425 return 0;
426 }
427 else if (mode == Mode::HELP) {
428 print_help(program_name);
429 return 0;
430 }
431 auto f = Dict_Finder_For_CLI_Tool_2();
432
433 char* loc_str = nullptr;
434 #if _WIN32
435 loc_str = setlocale(LC_CTYPE, nullptr); // will return "C"
436 #else
437 loc_str = setlocale(LC_CTYPE, "");
438 if (!loc_str) {
439 clog << "WARNING: Can not set to system locale, fall back to "
440 "\"C\".\n";
441 loc_str = setlocale(LC_CTYPE, nullptr); // will return "C"
442 }
443 #endif
444 #if _POSIX_VERSION
445 auto enc_str = nl_langinfo(CODESET);
446 if (input_enc.empty())
447 input_enc = enc_str;
448 if (output_enc.empty())
449 output_enc = enc_str;
450 #elif _WIN32
451 if (optind == argc && _isatty(_fileno(stdin)))
452 input_enc = "cp" + to_string(GetConsoleCP());
453 else if (input_enc.empty())
454 input_enc = "UTF-8";
455 if (_isatty(_fileno(stdout)))
456 output_enc = "cp" + to_string(GetConsoleOutputCP());
457 else if (output_enc.empty())
458 output_enc = "UTF-8";
459 #endif
460 auto loc_str_sv = string_view(loc_str);
461 clog << "INFO: Locale LC_CTYPE=" << loc_str_sv
462 << ", Input encoding=" << input_enc
463 << ", Output encoding=" << output_enc << endl;
464
465 if (dictionary.empty()) {
466 auto denv = getenv("DICTIONARY");
467 if (denv)
468 dictionary = denv;
469 }
470 if (dictionary.empty()) {
471 // infer dictionary from locale
472 auto idx = min(loc_str_sv.find('.'), loc_str_sv.find('@'));
473 dictionary = loc_str_sv.substr(0, idx);
474 }
475 if (dictionary.empty()) {
476 clog << "ERROR: No dictionary provided and can not infer from "
477 "OS locale\n";
478 return EXIT_FAILURE;
479 }
480 auto filename = f.get_dictionary_path(dictionary);
481 if (filename.empty()) {
482 clog << "ERROR: Dictionary " << dictionary << " not found\n";
483 return EXIT_FAILURE;
484 }
485 clog << "INFO: Pointed dictionary " << filename.string() << endl;
486 auto peak_ram_a = get_peak_ram_usage();
487 auto dic = Dictionary();
488 try {
489 dic.load_aff_dic_internal(filename, clog);
490 }
491 catch (const Dictionary_Loading_Error& e) {
492 clog << "ERROR: " << e.what() << '\n';
493 return EXIT_FAILURE;
494 }
495 auto nuspell_ram = get_peak_ram_usage() - peak_ram_a;
496 auto aff_name = filename.string();
497 auto dic_name = filename.replace_extension(".dic").string();
498 peak_ram_a = get_peak_ram_usage();
499 auto hun = Hunspell(aff_name.c_str(), dic_name.c_str());
500 auto hunspell_ram = get_peak_ram_usage() - peak_ram_a;
501 cout << "Nuspell peak RAM usage: " << nuspell_ram << "KB\n"
502 << "Hunspell peak RAM usage: " << hunspell_ram << "KB\n";
503
504 // ICU reports all types of errors, logic errors and runtime errors
505 // using this enum. We should not check for logic errors, they should
506 // not happened. Optionally, only assert that they are not there can be
507 // used. We should check for runtime errors.
508 // The encoding conversion is a common case where runtime error can
509 // happen, but by default ICU uses Unicode replacement character on
510 // errors and reports success. This can be changed, but there is no need
511 // for that.
512 auto uerr = U_ZERO_ERROR;
513 auto inp_enc_cstr = input_enc.c_str();
514 if (input_enc.empty()) {
515 inp_enc_cstr = nullptr;
516 clog << "WARNING: using default ICU encoding converter for IO"
517 << endl;
518 }
519 auto in_ucnv =
520 icu::LocalUConverterPointer(ucnv_open(inp_enc_cstr, &uerr));
521 if (U_FAILURE(uerr)) {
522 clog << "ERROR: Invalid encoding " << input_enc << ".\n";
523 return EXIT_FAILURE;
524 }
525
526 auto hun_enc =
527 nuspell::Encoding(hun.get_dict_encoding()).value_or_default();
528 auto hun_cnv =
529 icu::LocalUConverterPointer(ucnv_open(hun_enc.c_str(), &uerr));
530 if (U_FAILURE(uerr)) {
531 clog << "ERROR: Invalid Hun encoding " << hun_enc << ".\n";
532 return EXIT_FAILURE;
533 }
534
535 if (optind == argc) {
536 process_text(options, dic, hun, hun_cnv.getAlias(), cin,
537 in_ucnv.getAlias(), cout, uerr);
538 }
539 else {
540 for (; optind != argc; ++optind) {
541 auto file_name = argv[optind];
542 ifstream in(file_name);
543 if (!in.is_open()) {
544 clog << "ERROR: Can't open " << file_name
545 << '\n';
546 return EXIT_FAILURE;
547 }
548 process_text(options, dic, hun, hun_cnv.getAlias(), in,
549 in_ucnv.getAlias(), cout, uerr);
550 }
551 }
552 }