-
Notifications
You must be signed in to change notification settings - Fork 0
/
mklangid.C
2744 lines (2587 loc) · 88.4 KB
/
mklangid.C
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************** -*- C++ -*- *****************************/
/* */
/* LA-Strings: language-aware text-strings extraction */
/* by Ralf Brown / Carnegie Mellon University */
/* */
/* File: mklangid.C build language-id model database */
/* Version: 1.30 */
/* LastEdit: 2019-07-17 */
/* */
/* (c) Copyright 2010,2011,2012,2013,2014,2015,2019 */
/* Ralf Brown/Carnegie Mellon University */
/* This program is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU General Public License as */
/* published by the Free Software Foundation, version 3. */
/* */
/* This program is distributed in the hope that it will be */
/* useful, but WITHOUT ANY WARRANTY; without even the implied */
/* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR */
/* PURPOSE. See the GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public */
/* License (file COPYING) along with this program. If not, see */
/* http://www.gnu.org/licenses/ */
/* */
/************************************************************************/
#include <algorithm>
#include <cassert>
#include <cmath>
#include "langid.h"
#include "prepfile.h"
#include "mtrie.h"
#include "ptrie.h"
#include "framepac/bitvector.h"
#include "framepac/message.h"
#include "framepac/texttransforms.h"
using namespace std ;
using namespace Fr ;
/************************************************************************/
/* Configuration and Manifest Constants */
/************************************************************************/
#define VERSION "1.30"
#define MAX_NGRAMS 5000
//#define DEBUG // generate torrents of output in verbose mode
// since we always count at least trigrams, we don't support lengths less
// than three
#define ABSOLUTE_MIN_LENGTH 3
#define DEFAULT_MAX_LENGTH 8
#define ABSOLUTE_MAX_LENGTH 500
#define MAX_OVERSAMPLE 2.5
#define MAX_INCREMENT 10
// if n-gram plus an affix appears at least this many times the count
// of times the bare n-gram appears, ignore the bare n-gram
#define AFFIX_RATIO 0.90
#define MINLEN_AFFIX_RATIO 0.995 // be strict for minimum-length ngrams
// limit how low the user can set the affix ratio
#define MIN_AFFIX_RATIO 0.4
// assume that each character in a listed n-gram implies N characters
// in the total training data when TotalCount: is not present; this discount
// factor reduces false positive detections from mguesser ngram lists
#define ASSUMED_NGRAM_DENSITY 8
// how much to discount faked ngrams inserted via the UTF8: directive in
// a frequency list file
#define FAKED_NGRAM_DISCOUNT 10
#define DEFAULT_SIMILARITY_THRESHOLD 0.50
// factor times minimum representable prob at which to cut off stopgrams
#define STOPGRAM_CUTOFF 2
// weighting of stopgrams based on amount of training data
#define TRAINSIZE_NO_WEIGHT 15000
#define TRAINSIZE_FULL_WEIGHT 2000000
// the amount by which to increase the weight of an n-gram which is unique
// to a particular model among closely-related languages
#define UNIQUE_BOOST 1.0
// precompute smoothing before scaling to reduce quantization error when
// packing the trie
#define SMOOTHING_POWER 0.14
/************************************************************************/
/************************************************************************/
#ifndef lengthof
# define lengthof(x) (sizeof(x)/sizeof((x)[0]))
#endif /* lengthof */
#if BUFFER_SIZE < 2*FrMAX_LINE
# undef BUFFER_SIZE
# define BUFRER_SIZE (2*FrMAX_LINE)
#endif
/************************************************************************/
/* Types for this module */
/************************************************************************/
struct NgramEnumerationData
{
public:
NybbleTrie *m_ngrams ;
uint32_t *m_frequencies ;
bool &m_have_max_length ;
bool m_inserted_ngram ;
unsigned m_min_length ;
unsigned m_max_length ;
unsigned m_desired_length ;
unsigned m_topK ;
unsigned m_count ;
unsigned m_alignment ;
uint32_t m_min_freq ;
public:
NgramEnumerationData(bool &have_max_length)
: m_have_max_length(have_max_length), m_inserted_ngram(false), m_alignment(1)
{}
~NgramEnumerationData() {}
} ;
//----------------------------------------------------------------------
class StopGramInfo
{
private:
NybbleTrie *m_trie ;
NybbleTrie *m_currngrams ;
NybbleTrie *m_ngramweights ;
const PackedTrieFreq *m_freqbase ;
const LanguageScores *m_weights ;
const BitVector *m_selected ;
unsigned m_activelang ;
public:
StopGramInfo(NybbleTrie *t, NybbleTrie *t2, NybbleTrie *t3,
const PackedTrieFreq *base,
const LanguageScores *wt, const BitVector *sel,
unsigned lang)
{ m_trie = t ; m_currngrams = t2 ; m_ngramweights = t3 ;
m_freqbase = base ; m_weights = wt ; m_selected = sel ;
m_activelang = lang ; }
~StopGramInfo() {}
// accessors
NybbleTrie *trie() const { return m_trie ; }
NybbleTrie *currLangTrie() const { return m_currngrams ; }
NybbleTrie *weightTrie() const { return m_ngramweights ; }
unsigned activeLanguage() const { return m_activelang ; }
bool selected(size_t langid) const
{ return m_selected ? m_selected->getBit(langid) : false ; }
const PackedTrieFreq *freqBaseAddress() const { return m_freqbase ; }
double weight(size_t langid) const
{ return m_weights ? m_weights->score(langid) : 1.0 ; }
} ;
//----------------------------------------------------------------------
class StopGramWeight
{
private:
const NybbleTrie *m_weighttrie ;
uint64_t m_totalbytes ;
bool m_scaled ;
public:
StopGramWeight(const NybbleTrie *wt, uint64_t tb, bool sc)
{ m_weighttrie = wt ; m_totalbytes = tb ; m_scaled = sc ; }
~StopGramWeight() {}
// accessors
bool scaled() const { return m_scaled ; }
uint64_t totalBytes() const { return m_totalbytes ; }
const NybbleTrie *weights() const { return m_weighttrie ; }
uint32_t weight(const uint8_t *key, unsigned keylen) const ;
// modifiers
} ;
//----------------------------------------------------------------------
typedef bool FileReaderFunc(PreprocessedInputFile *, va_list) ;
/************************************************************************/
/* Global variables */
/************************************************************************/
static bool verbose = false ;
static bool store_similarities = false ;
static bool do_dump_trie = false ;
static bool crubadan_format = false ;
static BigramExtension bigram_extension = BigramExt_None ;
static unsigned topK = MAX_NGRAMS ;
static unsigned minimum_length = ABSOLUTE_MIN_LENGTH ;
static unsigned maximum_length = DEFAULT_MAX_LENGTH ;
static unsigned alignment = 1 ;
static const char *vocabulary_file = nullptr ;
static double max_oversample = MAX_OVERSAMPLE ;
static double affix_ratio = AFFIX_RATIO ;
static double discount_factor = 1.0 ;
static Owned<LanguageIdentifier> language_identifier { nullptr } ;
static bool skip_numbers = false ;
static bool subsample_input = false ;
static uint64_t byte_limit = ~0 ;
static double unique_boost = UNIQUE_BOOST ;
static double smoothing_power = SMOOTHING_POWER ;
static double log_smoothing_power = 1.0 ;
// multiple of min proportion in confusible models for an ngram to be
// added to baseline model; 0 = disable the addition
static double confusibility_thresh = 0.0 ;
/************************************************************************/
/* Helper functions */
/************************************************************************/
// in trigram.C
void insert_frequency(uint32_t newelt, uint32_t *heap, size_t heaplen) ;
uint32_t adjusted_threshold(const uint32_t *frequencies) ;
//----------------------------------------------------------------------
static void usage(const char *argv0, const char *bad_arg)
{
if (bad_arg)
cerr << "Unrecognized argument " << bad_arg << endl << endl ;
cerr << "MKLANGID version " VERSION " Copyright 2011,2012,2019 Ralf Brown/CMU -- GNU GPLv3" << endl ;
cerr << "Usage: " << argv0 << " [=DBFILE] {options} file ... [{options} file ...]"
<< endl ;
cerr << " Specify =DBFILE to use language database DBFILE instead of the\n" ;
cerr << " default " DEFAULT_LANGID_DATABASE << "; with ==DBFILE, the database\n" ;
cerr << " will not be updated (use -w to store results)" << endl ; ;
cerr << "Options:" << endl ;
cerr << " -h show this usage summary" << endl ;
cerr << " -l LANG specify language of following files (use ISO-639 two-letter code)" << endl ;
cerr << " -r REG specify regional variant of the language (use ISO two-letter" << endl ;
cerr << " country codes, e.g. for locale 'en_US', use -l en -r US" << endl ;
cerr << " [optional])" << endl ;
cerr << " -e ENC specify the character encoding, e.g. iso8859-1, utf-8, etc." << endl ;
cerr << " -s SRC specify the source of the training data (optional)" << endl ;
cerr << " -W SCR specify writing system (script) of the training data (optional)" << endl ;
cerr << " -kK collect top K n-grams by frequency (default " << topK << ")\n" ;
cerr << " -mN require n-grams to consist of at least N bytes (min 3)\n" ;
cerr << " -MN limit n-grams to at most N bytes (default " << DEFAULT_MAX_LENGTH << ", max " << ABSOLUTE_MAX_LENGTH << ")\n" ;
cerr << " -i ignore blanks when processing files\n" ;
cerr << " -n skip ngrams containing newlines in following files\n" ;
cerr << " -nn skip ngrams starting with digits as well\n" ;
cerr << " -LN limit training to first N bytes of input\n" ;
cerr << " -L@N limit training to N bytes uniformly sampled from input\n" ;
cerr << " -b omit bigram table from model for following files\n" ;
cerr << " -ON set maximum oversampling factor to N (default " << max_oversample << ")" << endl ;
cerr << " -aX set affix ratio; remove 'ABC' if c(ABCD) >= X * c(ABC)" << endl ;
cerr << " -dX set probability discount factor for X" << endl ;
cerr << " -R SPEC compute stop-grams relative to related language(s) listed in SPEC" << endl ;
cerr << " -B BOOST increase smoothed scores of n-grams unique to model by BOOST*" << endl ;
cerr << " -S SMTH set smoothing power to SMTH (negative for logarithmic)" << endl;
cerr << " -1 convert Latin-1 input to UTF-8" << endl ;
cerr << " -2b pad input bytes to 16 bits (big-endian)" << endl ;
cerr << " -2l pad input bytes to 16 bits (little-endian)" << endl ;
cerr << " -2- don't pad input bytes to 16 bits" << endl ;
cerr << " -8b convert UTF8 input to UTF-16 (big-endian)" << endl ;
cerr << " -8l convert UTF8 input to UTF-16 (little-endian)" << endl ;
cerr << " -8- don't convert UTF8" << endl ;
cerr << " -AN alignment: only start ngram at multiple of N (1,2,4)" << endl ;
cerr << " -f following files are frequency lists (count then string)" << endl ;
cerr << " -fc following files are frequency lists (count/string, word delim)" << endl ;
cerr << " -ft following files are frequency lists (string/tab/count)" << endl ;
cerr << " -v run verbosely" << endl ;
cerr << " -wFILE write resulting vocabulary list to FILE in plain text" << endl ;
cerr << " -D dump computed multi-trie to standard output" << endl ;
cerr << "Notes:" << endl ;
cerr << "\tThe -1 -b -f -i -n -nn -R -w flags reset after each group of files." << endl;
cerr << "\t-2 and -8 are mutually exclusive -- the last one specified is used." << endl ;
exit(1) ;
}
//----------------------------------------------------------------------
static const char *get_arg(int &argc, const char **&argv)
{
if (argv[1][2])
return argv[1]+2 ;
else
{
argc-- ;
argv++ ;
return argv[1] ;
}
}
//----------------------------------------------------------------------
static void print_quoted_char(CFile& f, uint8_t ch)
{
switch (ch)
{
case '\0': f.puts("\\0") ; break ;
case '\f': f.puts("\\f") ; break ;
case '\n': f.puts("\\n") ; break ;
case '\r': f.puts("\\r") ; break ;
case '\t': f.puts("\\t") ; break ;
case ' ': f.puts("\\ ") ; break ;
case '\\': f.puts("\\\\") ; break ;
default: f.putc(ch) ; break ;
}
return ;
}
//----------------------------------------------------------------------
static int UCS2_to_UTF8(unsigned long codepoint, char *buf)
{
if (codepoint < 0x80)
{
// encode as single byte
*buf = (char)codepoint ;
return 1 ;
}
else if (codepoint > 0x10FFFF)
return -1 ;
if (codepoint < 0x800)
{
// encode in two bytes
buf[0] = (unsigned char)(0xC0 | ((codepoint & 0x07C0) >> 6)) ;
buf[1] = (unsigned char)(0x80 | (codepoint & 0x003F)) ;
return 2 ;
}
else if (codepoint < 0x010000)
{
// encode as three bytes
buf[0] = (unsigned char)(0xE0 | ((codepoint & 0xF000) >> 12)) ;
buf[1] = (unsigned char)(0x80 | ((codepoint & 0x0FC0) >> 6)) ;
buf[2] = (unsigned char)(0x80 | (codepoint & 0x003F)) ;
return 3 ;
}
else
{
// encode as four bytes
buf[0] = (unsigned char)(0xF0 | ((codepoint & 0x1C0000) >> 18)) ;
buf[1] = (unsigned char)(0x80 | ((codepoint & 0x03F000) >> 12)) ;
buf[2] = (unsigned char)(0x80 | ((codepoint & 0x000FC0) >> 6)) ;
buf[3] = (unsigned char)(0x80 | (codepoint & 0x00003F)) ;
return 4 ;
}
}
//----------------------------------------------------------------------
static uint64_t read_files(const char **filelist, unsigned num_files,
bool show_error, FileReaderFunc *reader, ...)
{
if (!filelist)
return 0 ;
va_list args ;
va_start(args,reader) ;
uint64_t total_bytes = 0 ;
bool OK = true ;
for (size_t i = 0 ; i < num_files && total_bytes < byte_limit && OK ; i++)
{
const char *filename = filelist[i] ;
if (filename && *filename)
{
PreprocessedInputFile infile(filename,byte_limit - total_bytes, subsample_input) ;
if (infile.good())
{
SystemMessage::status(" Processing %s",filename) ;
va_list argcopy ;
va_copy(argcopy,args) ;
if (!reader(&infile,argcopy))
OK = false ;
}
else if (show_error)
{
SystemMessage::error("Unable to open '%s' for reading",filename) ;
}
total_bytes += infile.bytesRead() ;
infile.close() ;
}
}
va_end(args) ;
return total_bytes ;
}
/************************************************************************/
/* Language-name manipulation functions */
/************************************************************************/
static int compare_langcode(const LanguageID *id1, const LanguageID *id2)
{
if (!id1)
return id2 ? +1 : 0 ;
else if (!id2)
return -1 ;
const char *l1 = id1->language() ;
const char *l2 = id2->language() ;
if (!l1)
return l2 ? +1 : 0 ;
else if (!l2)
return -1 ;
return strcmp(l1,l2) ;
}
//----------------------------------------------------------------------
static int compare_codepair(const LanguageID *id1, const LanguageID *id2)
{
if (!id1)
return id2 ? +1 : 0 ;
else if (!id2)
return -1 ;
const char *l1 = id1->language() ;
const char *l2 = id2->language() ;
if (!l1)
return l2 ? +1 : 0 ;
else if (!l2)
return -1 ;
int cmp = strcmp(l1,l2) ;
if (cmp)
return cmp ;
const char *enc1 = id1->encoding() ;
const char *enc2 = id2->encoding() ;
if (!enc1)
return enc2 ? +1 : 0 ;
else if (!enc2)
return -1 ;
return strcmp(enc1,enc2) ;
}
/************************************************************************/
/* Methods for class StopGramWeight */
/************************************************************************/
uint32_t StopGramWeight::weight(const uint8_t *key, unsigned keylen) const
{
uint32_t raw = weights()->find(key,keylen) ;
if (!scaled() && raw > 0)
{
double percent = raw / (double)TRIE_SCALE_FACTOR ;
double proportion = percent / 100.0 ;
uint32_t unscaled = (uint32_t)(proportion * totalBytes() + 0.5) ;
return unscaled ;
}
else
return raw ;
}
/************************************************************************/
/* Stopgram Computation */
/************************************************************************/
static bool collect_language_ngrams_packed(const PackedTrieNode *node,
const uint8_t *key,
unsigned keylen, void *user_data)
{
auto stop_gram_info = reinterpret_cast<StopGramInfo*>(user_data) ;
assert(stop_gram_info != nullptr) ;
assert(node != nullptr) ;
if (node->leaf())
{
auto freq = node->frequencies(stop_gram_info->freqBaseAddress()) ;
// the following is the smallest value which can be represented by
// the bitfields in PackedTrieFreq; anything less than that will
// round to zero unless smoothed
double minweight = PackedTrieFreq::minWeight() ;
// since extra stopgrams have a cost both in storage and runtime,
// we want to omit any that have little possible impact on the
// overall score, so bump up the above absolute minimum threshold
minweight *= STOPGRAM_CUTOFF ;
for ( ; ; freq++)
{
unsigned langid = freq->languageID() ;
if (stop_gram_info->activeLanguage() == langid)
{
uint32_t wt = freq->scaledScore() ;
stop_gram_info->currLangTrie()->insert(key,keylen,wt,false) ;
}
if (stop_gram_info->selected(langid) &&
!freq->isStopgram() && freq->percentage() > 0.0)
{
double wt = stop_gram_info->weight(langid) * freq->scaledScore() ;
uint32_t weight = (uint32_t)(wt + 0.5) ;
if (weight >= minweight)
{
// if the weight is large enough to be bothered with,
// add the ngram to the presence trie and its computed
// weight to the weight trie
stop_gram_info->trie()->insert(key,keylen,0,false) ;
stop_gram_info->weightTrie()->insertMax(key,keylen,weight,
false) ;
}
}
if (freq->isLast())
break ;
}
}
return true ;
}
//----------------------------------------------------------------------
static bool select_models_by_name(const char *languages, BitVector &selected)
{
auto descriptions = dup_string(languages) ;
char *desc = *descriptions ;
bool did_select = false ;
while (desc && *desc)
{
char *desc_end = strchr(desc,',') ;
if (desc_end)
*desc_end++ = '\0' ;
else
desc_end = strchr(desc,'\0') ;
unsigned langnum = language_identifier->languageNumber(desc) ;
if (langnum != (unsigned)~0)
{
selected.setBit(langnum,true) ;
did_select = true ;
}
else
{
SystemMessage::warning("no match for language descriptor '%s'",desc) ;
}
desc = desc_end ;
}
return did_select ;
}
//----------------------------------------------------------------------
static bool select_models_by_similarity(size_t langid, BitVector &selected,
LanguageScores *weights,
const char *thresh)
{
bool did_select = false ;
if (!weights)
{
SystemMessage::error("Unable to compute cross-language similarities, will not compute stop-grams.") ;
return did_select ;
}
char *endptr = nullptr ;
double threshold = strtod(thresh,&endptr) ;
if (threshold <= 0.0 || threshold > 1.0)
threshold = DEFAULT_SIMILARITY_THRESHOLD ;
const LanguageID *curr = language_identifier->languageInfo(langid) ;
// figure out which, if any, language models are close enough to the
// current one to be the basis for stopgrams
for (size_t langnum = 0 ; langnum < weights->numLanguages() ; langnum++)
{
if (langnum == langid || weights->score(langnum) < threshold)
continue ;
const LanguageID *other = language_identifier->languageInfo(langnum) ;
if (other)
{
// check that the other model isn't the same language,
// region, AND encoding
if (curr->language() && other->language() &&
strcmp(curr->language(),other->language()) == 0 &&
curr->region() && other->region() &&
strcmp(curr->region(),other->region()) == 0 &&
curr->encoding() && other->encoding() &&
strcmp(curr->encoding(),other->encoding()) == 0)
continue ;
}
did_select = true ;
selected.setBit(langnum,true) ;
if (/*verbose &&*/ other)
{
SystemMessage::status(" similarity to %s_%s-%s is %g",other->language(),other->region(),other->encoding(),
weights->score(langnum)) ;
}
}
return did_select ;
}
//----------------------------------------------------------------------
static Owned<NybbleTrie> load_stop_grams_selected(unsigned langid,
LanguageScores *weights,
LangIDPackedMultiTrie *ptrie,
const BitVector *selected,
Owned<NybbleTrie>& curr_ngrams,
Owned<NybbleTrie>& ngram_weights)
{
// further discount the selected other languages by the absolute
// amount of training data in the primary language (since less
// data means a greater chance that the n-gram is not seen purely
// due to data sparsity)
const LanguageID *curr = language_identifier->languageInfo(langid) ;
if (!curr)
{
return new NybbleTrie ;
}
auto train = curr->trainingBytes() ;
if (train < TRAINSIZE_FULL_WEIGHT)
{
train = (train > TRAINSIZE_NO_WEIGHT) ? train - TRAINSIZE_NO_WEIGHT : 0 ;
double scalefactor = (TRAINSIZE_FULL_WEIGHT - TRAINSIZE_NO_WEIGHT) ;
double scale = ::pow(train / scalefactor,0.7) ;
weights->scaleScores(scale) ;
}
// because the values stored in the tries have already been
// adjusted to smooth them, we need to apply the same
// adjustment to the inter-model weights to avoid overly
// reducing the weights of stopgrams
for (size_t i = 0 ; i < weights->numLanguages() ; i++)
{
if (selected->getBit(i))
{
double sc = weights->score(i) ;
sc = ::pow(sc,smoothing_power) ;
#if 0 //!!!
if (i != langid)
{
// adjust the strength of the stop-grams for each model
// pair by the coverage fractions of the two models
double cover = curr->coverageFactor() ;
if (cover > 0.0)
sc /= cover ;
// assume that the coverages are independent of each
// other, which lets us simply multiple the two
// coverage fractions
const LanguageID *other = language_identifier->languageInfo(i) ;
cover = other->coverageFactor() ;
cerr<<"adj="<<cover<<endl;
if (cover > 0.0)
sc /= cover ;
}
#endif
weights->setScore(i,sc) ;
}
}
uint8_t key[1000] ;
unsigned maxkey = ptrie->longestKey() ;
if (maxkey > sizeof(key))
maxkey = sizeof(key) ;
Owned<NybbleTrie> stop_grams ;
curr_ngrams.reinit() ;
ngram_weights.reinit() ;
auto freq_base = ptrie->frequencyBaseAddress() ;
StopGramInfo stop_gram_info(stop_grams,curr_ngrams,ngram_weights,
freq_base,weights,selected,langid) ;
ptrie->enumerate(key,maxkey,collect_language_ngrams_packed,&stop_gram_info) ;
return stop_grams ;
}
//----------------------------------------------------------------------
static Owned<NybbleTrie> load_stop_grams(const LanguageID *lang_info, const char *languages,
Owned<NybbleTrie>& curr_ngrams,
Owned<NybbleTrie>& ngram_weights,
uint64_t &training_bytes)
{
curr_ngrams = nullptr ;
ngram_weights = nullptr ;
training_bytes = 0 ;
if (!languages)
return nullptr ;
auto ptrie = language_identifier->trie() ;
if (!ptrie)
{
return nullptr ;
}
unsigned langid = language_identifier->languageNumber(lang_info) ;
training_bytes = language_identifier->trainingBytes(langid) ;
SystemMessage::status("Computing similarities relative to %s_%s-%s",lang_info->language(),lang_info->region(),
lang_info->encoding()) ;
auto weights = language_identifier->similarity(langid) ;
ScopedObject<BitVector> selected(language_identifier->numLanguages()) ;
bool selected_models ;
if (languages && *languages == '@')
{
selected_models = select_models_by_similarity(langid,*selected,weights,languages+1) ;
}
else
{
selected_models = select_models_by_name(languages,*selected) ;
}
Owned<NybbleTrie> stop_grams { nullptr } ;
if (selected_models || 1) //!!! we need to run regardless, to create curr_ngrams
{
curr_ngrams = nullptr ;
ngram_weights = nullptr ;
stop_grams = load_stop_grams_selected(langid,weights,ptrie,&selected,curr_ngrams,ngram_weights) ;
}
else
{
stop_grams.reinit() ;
}
return stop_grams ;
}
//----------------------------------------------------------------------
// count the ngrams in the current training data which match ngrams in
// the highly-similar models selected earlier
static void accumulate_confusible_ngrams(PreprocessedInputFile *infile,
NybbleTrie *confusible,
NybbleTriePointer *states)
{
auto maxkey = confusible->longestKey() ;
while (infile->moreData())
{
int keybyte = infile->getByte() ;
if (keybyte == EOF)
break ;
states[maxkey].invalidate() ;
states[0].resetKey() ;
for (auto i = maxkey ; i > 0 ; i--)
{
if (!states[i-1])
continue ;
if (states[i-1].extendKey((uint8_t)(keybyte&0xFF)))
{
// check whether we're at a leaf node; if so, increment its frequency
auto node = states[i-1].node() ;
if (node && node->leaf())
{
node->incrFrequency() ;
}
states[i] = states[i-1] ;
}
else
{
states[i].invalidate() ;
}
states[i-1].invalidate() ;
}
}
return ;
}
//----------------------------------------------------------------------
static bool accumulate_confusible_ngrams(PreprocessedInputFile *infile, va_list args)
{
auto confusible = va_arg(args,NybbleTrie*) ;
if (!infile || !infile->good() || !confusible)
return false ;
unsigned maxkey = confusible->longestKey() ;
NewPtr<NybbleTriePointer> states(maxkey+2) ;
if (states)
{
for (size_t i = 0 ; i < maxkey+2 ; ++i)
states[i].setTrie(confusible) ;
accumulate_confusible_ngrams(infile,confusible,states.begin()) ;
}
return true ;
}
//----------------------------------------------------------------------
static bool add_stop_gram(const NybbleTrie* trie, uint32_t nodeindex,
const uint8_t *key, unsigned keylen,
void *user_data)
{
auto node = trie->node(nodeindex) ;
assert(node != nullptr) ;
if (keylen <= 2 || !node->leaf())
return true ;
if (node->frequency() == 0 || node->isStopgram())
{
auto ngrams = reinterpret_cast<NybbleTrie*>(user_data) ;
auto weights = reinterpret_cast<StopGramWeight*>(ngrams->userData()) ;
auto weight = weights->weight(key,keylen) ;
ngrams->insert(key,keylen,weight,true) ;
}
else if (confusibility_thresh > 0.0)
{
// optionally add the ngram as a regular ngram if the proportion
// in the current training data is higher than the given
// multiple of the lowest proportion in the confusible models
//FIXME
// ngrams->insert(key,keylen,weight,false) ;
}
return true ;
}
//----------------------------------------------------------------------
static bool boost_unique_ngram(const NybbleTrie* trie, uint32_t nodeindex,
const uint8_t *key, unsigned keylen,
void *user_data)
{
auto stop_grams = reinterpret_cast<NybbleTrie*>(user_data) ;
auto n = trie->node(nodeindex) ;
if (n && n->leaf() && n->frequency() > 0 && !n->isStopgram())
{
auto sgnode = stop_grams->findNode(key,keylen) ;
if (!sgnode || !sgnode->leaf())
{
auto freq = n->frequency() ;
// boost the weight of this node
auto boost = scale_frequency(unique_boost,smoothing_power,
log_smoothing_power) ;
auto boosted = (uint32_t)(freq * boost + 0.9) ;
if (boosted < n->frequency()) // did we roll over?
boosted = 0xFFFFFFFF ;
n->setFrequency(boosted) ;
}
}
return true ;
}
//----------------------------------------------------------------------
static bool add_stop_grams(const char **filelist, unsigned num_files,
NybbleTrie *ngrams, NybbleTrie *stop_grams,
const NybbleTrie *ngram_weights, bool scaled)
{
if (!stop_grams || stop_grams->size() <= 100)
return true ;
SystemMessage::status("Computing Stop-Grams") ;
// accumulate counts for all the ngrams in the stop-gram list
uint64_t total_bytes
= read_files(filelist,num_files,false,&accumulate_confusible_ngrams,stop_grams) ;
StopGramWeight stop_gram_weight(ngram_weights,total_bytes,scaled) ;
ngrams->setUserData(&stop_gram_weight) ;
stop_grams->setUserData(&stop_gram_weight) ;
// 'stop_grams' contains the union of all n-grams in the models for
// closely-related languages. Any n-grams in the current language's
// model which don't appear in any of the other models get a boost,
// because they are particularly strong evidence that the text is in
// the given language
unsigned longkey = stop_grams->longestKey() ;
if (ngrams->longestKey() > longkey)
longkey = ngrams->longestKey() ;
LocalAlloc<uint8_t> ngram_buf(longkey+1) ;
if (unique_boost > 1.0)
{
ngrams->enumerate(&ngram_buf,ngrams->longestKey(),boost_unique_ngram,stop_grams) ;
}
// scan the stop-gram list and add any with a zero count to the main
// n-gram list, flagged as stop-grams; optionally, add any which
// have higher counts in the current language but are not in the
// baseline model to the model as well
stop_grams->enumerate(ngram_buf,stop_grams->longestKey(),add_stop_gram,ngrams) ;
return true ;
}
/************************************************************************/
/* Model output */
/************************************************************************/
static unsigned count_languages(const LanguageIdentifier *id,
int (*cmp)(const LanguageID*,const LanguageID*))
{
unsigned count = 0 ;
if (id)
{
size_t num_langs = id->numLanguages() ;
LocalAlloc<LanguageID*> langcodes(num_langs) ;
for (size_t i = 0 ; i < num_langs ; i++)
{
langcodes[i] = (LanguageID*)id->languageInfo(i) ;
}
// sort the codes to get runs of equal codes
std::sort(&langcodes,&langcodes+num_langs,cmp) ;
count = 1 ;
for (size_t i = 1 ; i < num_langs ; i++)
{
// increment the count every time the code differs from the
// one before
if (cmp(langcodes[i-1],langcodes[i]) != 0)
count++ ;
}
}
return count ;
}
//----------------------------------------------------------------------
static bool save_database(const char *database_file)
{
if (!database_file || !*database_file)
database_file = DEFAULT_LANGID_DATABASE ;
if (language_identifier->numLanguages() > 0)
{
unsigned num_languages = count_languages(language_identifier,compare_langcode) ;
unsigned num_pairs = count_languages(language_identifier,compare_codepair) ;
SystemMessage::status("Database contains %lu models, %u distinct language codes,\n\t"
"and %u language/encoding pairs",language_identifier->numLanguages(),num_languages,num_pairs) ;
SystemMessage::status("Saving database to '%s'",database_file) ;
return language_identifier->write(database_file) ;
}
return false ;
}
//----------------------------------------------------------------------
static bool dump_ngrams(const NybbleTrie* trie, uint32_t nodeindex, const uint8_t *key,
unsigned keylen, void *user_data)
{
CFile& f = *((CFile*)user_data) ;
auto node = trie->node(nodeindex) ;
if (node->leaf())
{
uint32_t freq = node->frequency() ;
if (node->isStopgram() && freq > 0)
f.putc('-') ;
f.printf("%u\t",freq) ;
for (size_t i = 0 ; i < keylen ; i++)
{
print_quoted_char(f,key[i]) ;
}
f.printf("\n") ;
}
return true ;
}
//----------------------------------------------------------------------
// this global variable makes dump_vocabulary() non-reentrant
static uint64_t dump_total_bytes ;
static bool dump_ngrams_scaled(const NybbleTrie* trie, uint32_t nodeindex,
const uint8_t *key,
unsigned keylen, void *user_data)
{
CFile& f = *((CFile*)user_data) ;
auto node = trie->node(nodeindex) ;
if (node->leaf())
{
uint32_t freq = node->frequency() ;
if (node->isStopgram() && freq > 0)
f.putc('-') ;
double unscaled = (unscale_frequency(freq,smoothing_power) * dump_total_bytes / 100.0) + 0.99 ;
f.printf("%u\t",(unsigned)unscaled) ;
for (size_t i = 0 ; i < keylen ; i++)
{
print_quoted_char(f,key[i]) ;
}
f.printf("\n") ;
}
return true ;
}
//----------------------------------------------------------------------
static void dump_vocabulary(const NybbleTrie *ngrams, bool scaled,
const char *vocab_file, unsigned max_length,
uint64_t total_bytes, const LanguageID &opts)
{
COutputFile f(vocab_file) ;
if (!f)
{
SystemMessage::error("Unable to open '%s' to write vocabulary",vocab_file) ;
return ;
}
if (total_bytes)
f.printf("TotalCount: %llu\n", (unsigned long long)total_bytes) ;
f.printf("Lang: %s",opts.language()) ;
if (opts.friendlyName() != opts.language())
f.printf("=%s",opts.friendlyName()) ;
f.printf("\nScript: %s\nRegion: %s\nEncoding: %s\nSource: %s\n",
opts.script(),opts.region(),opts.encoding(),opts.source()) ;
if (alignment > 1)
f.printf("Alignment: %d\n",alignment) ;
if (discount_factor > 1.0)
f.printf("Discount: %g\n",discount_factor) ;
if (ngrams->ignoringWhiteSpace())
f.printf("IgnoreBlanks: yes\n") ;
if (opts.coverageFactor() > 0.0 && opts.coverageFactor() != 1.0)
f.printf("Coverage: %g\n",opts.coverageFactor()) ;
if (opts.countedCoverage() > 0.0 && opts.countedCoverage() != 1.0)
f.printf("WeightedCoverage: %g\n",opts.countedCoverage()) ;
if (opts.freqCoverage() > 0.0)
f.printf("FreqCoverage: %g\n",opts.freqCoverage()) ;
if (opts.matchFactor() > 0.0)
f.printf("MatchFactor: %g\n",opts.matchFactor()) ;
LocalAlloc<uint8_t> keybuf(max_length+1) ;
if (scaled)
{
dump_total_bytes = total_bytes ;
(void)ngrams->enumerate(keybuf,max_length,dump_ngrams_scaled,&f) ;
}
else
(void)ngrams->enumerate(keybuf,max_length,dump_ngrams,&f) ;
return ;
}
/************************************************************************/
/************************************************************************/
static unsigned set_oversampling(unsigned top_K, unsigned abs_min_len,
unsigned min_len, bool aligned)
{
if (abs_min_len < min_len)
{
double base = aligned ? 2.0 : 1.0 ;
double oversample = ::pow(2,base+(min_len-abs_min_len)/5.0) ;
if (oversample > max_oversample)