-
Notifications
You must be signed in to change notification settings - Fork 1
/
TextCat.php
331 lines (292 loc) · 7.88 KB
/
TextCat.php
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
<?php
/**
* TextCat language classifier
* See http://odur.let.rug.nl/~vannoord/TextCat/
*/
class TextCat {
const STATUSTOOSHORT = 'Input is too short.';
const STATUSNOMATCH = 'No match found.';
const STATUSAMBIGUOUS = 'Cannot determine language.';
/**
* Minimum input length to be considered for
* classification
* @var string
*/
private $resultStatus = '';
/**
* Number of ngrams to be used.
* @var int
*/
private $maxNgrams = 3000;
/**
* Minimum frequency of ngram to be counted.
* ( For language model generation set this
* >0 to decrease CPU and memory reqs. )
* @var int
*/
private $minFreq = 0;
/**
* Regexp used as word separator
* @var string
*/
private $wordSeparator = '0-9\s\(\)';
/**
* List of language files
* @var string[]
*/
private $langFiles = array();
/**
* Minimum input length to be considered for
* classification
* @var int
*/
private $minInputLength = 0;
/**
* Maximum ratio of the score between a given
* candidate and the best candidate for the
* given candidate to be considered an alternative.
* @var float
*/
private $resultsRatio = 1.05;
/**
* Maximum number of languages to return, within
* the resultsRatio. If there are more, the result
* is too ambiguous.
* @var int
*/
private $maxReturnedLanguages = 10;
/**
* Maximum proportion of maximum score allowed.
* Compare score to worst possible score, and if
* it is too close, consider it not worth reporting.
* @var float
*/
private $maxProportion = 1.00;
/**
* Amount to boost scores for languages
* specified by $boostedLangs; typical
* values are 0 to 0.15;
* @var float
*/
private $langBoostScore = 0.00;
/**
* List of languages to boost by $langBoostScore
* @var string[]
*/
private $boostedLangs = array();
/**
* @param
*/
public function getResultStatus() {
return $this->resultStatus;
}
/**
* @param int $maxNgrams
*/
public function setMaxNgrams( $maxNgrams ) {
$this->maxNgrams = $maxNgrams;
}
/**
* @param int $minFreq
*/
public function setMinFreq( $minFreq ) {
$this->minFreq = $minFreq;
}
/**
* @param int $minInputLength
*/
public function setMinInputLength( $minInputLength ) {
$this->minInputLength = $minInputLength;
}
/**
* @param float $resultsRatio
*/
public function setResultsRatio( $resultsRatio ) {
$this->resultsRatio = $resultsRatio;
}
/**
* @param int $maxReturnedLanguages
*/
public function setMaxReturnedLanguages( $maxReturnedLanguages ) {
$this->maxReturnedLanguages = $maxReturnedLanguages;
}
/**
* @param float $maxProportion
*/
public function setMaxProportion( $maxProportion ) {
$this->maxProportion = $maxProportion;
}
/**
* @param float $langBoostScore
*/
public function setLangBoostScore( $langBoostScore ) {
$this->langBoostScore = $langBoostScore;
}
/**
* @param float $langBoostScore
*/
public function setBoostedLangs( $boostedLangs = array() ) {
// flip for more efficient lookups
$this->boostedLangs = array_flip( $boostedLangs );
}
/**
* @param string $wordSeparator
*/
public function setWordSeparator( $wordSeparator ) {
$this->wordSeparator = $wordSeparator;
}
/**
* @param string|array $dirs
*/
public function __construct( $dirs = array() ) {
if ( empty( $dirs ) ) {
$dirs = array( __DIR__."/LM" );
}
if ( !is_array( $dirs ) ) {
$dirs = array( $dirs );
}
foreach ( $dirs as $dir ) {
foreach ( new DirectoryIterator( $dir ) as $file ) {
if ( !$file->isFile() ) {
continue;
}
if ( $file->getExtension() == "lm" &&
!isset( $this->langFiles[$file->getBasename( ".lm" )] ) ) {
$this->langFiles[$file->getBasename( ".lm" )] = $file->getPathname();
}
}
}
}
/**
* Create ngrams list for text.
* @param string $text
* @param int $maxNgrams How many ngrams to use.
* @return int[]
*/
public function createLM( $text, $maxNgrams ) {
$ngram = array();
foreach ( preg_split( "/[{$this->wordSeparator}]+/u", $text ) as $word ) {
if ( empty( $word ) ) {
continue;
}
$word = "_".$word."_";
$len = mb_strlen( $word, "UTF-8" );
for ( $i=0;$i<$len;$i++ ) {
$rlen = $len - $i;
if ( $rlen > 4 ) {
@$ngram[mb_substr( $word, $i, 5, "UTF-8" )]++;
}
if ( $rlen > 3 ) {
@$ngram[mb_substr( $word, $i, 4, "UTF-8" )]++;
}
if ( $rlen > 2 ) {
@$ngram[mb_substr( $word, $i, 3, "UTF-8" )]++;
}
if ( $rlen > 1 ) {
@$ngram[mb_substr( $word, $i, 2, "UTF-8" )]++;
}
@$ngram[mb_substr( $word, $i, 1, "UTF-8" )]++;
}
}
if ( $this->minFreq ) {
$min = $this->minFreq;
$ngram = array_filter( $ngram, function ( $v ) use( $min ) { return $v > $min;
} );
}
uksort( $ngram, function( $k1, $k2 ) use( $ngram ) {
if ( $ngram[$k1] == $ngram[$k2] ) {
return strcmp( $k1, $k2 );
}
return $ngram[$k2] - $ngram[$k1];
} );
if ( count( $ngram ) > $maxNgrams ) {
array_splice( $ngram, $maxNgrams );
}
return $ngram;
}
/**
* Load data from language file.
* @param string $langFile
* @return int[] Language file data
*/
public function loadLanguageFile( $langFile ) {
include $langFile;
array_splice( $ranks, $this->maxNgrams );
return $ranks;
}
/**
* Write ngrams to file in PHP format
* @param int[] $ngrams
* @param string $outfile Output filename
*/
public function writeLanguageFile( $ngrams, $outfile ) {
$out = fopen( $outfile, "w" );
// write original array as "$ngrams"
fwrite( $out, '<?php $ngrams = ' . var_export( $ngrams, true ) . ";\n" );
// write reduced array as "$ranks"
$rank = 1;
$ranks = array_map( function ( $x ) use( &$rank ) { return $rank++;
}, $ngrams );
fwrite( $out, '$ranks = ' . var_export( $ranks, true ) . ";\n" );
fclose( $out );
}
/**
* Classify text.
* @param string $text
* @param string[] $candidates List of candidate languages.
* @return int[] Array with keys of language names and values of score.
* Sorted by ascending score, with first result being the best.
*/
public function classify( $text, $candidates = null ) {
$results = array();
$this->resultStatus = '';
// strip non-word characters before checking for min length, don't assess empty strings
$wordLength = mb_strlen( preg_replace( "/[{$this->wordSeparator}]+/", "", $text ) );
if ( $wordLength < $this->minInputLength || $wordLength == 0 ) {
$this->resultStatus = self::STATUSTOOSHORT;
return $results;
}
$inputgrams = array_keys( $this->createLM( $text, $this->maxNgrams ) );
if ( $candidates ) {
// flip for more efficient lookups
$candidates = array_flip( $candidates );
}
foreach ( $this->langFiles as $language => $langFile ) {
if ( $candidates && !isset( $candidates[$language] ) ) {
continue;
}
$ngrams = $this->loadLanguageFile( $langFile );
$p = 0;
foreach ( $inputgrams as $i => $ingram ) {
if ( !empty( $ngrams[$ingram] ) ) {
$p += abs( $ngrams[$ingram] - $i );
} else {
$p += $this->maxNgrams;
}
}
if ( isset( $this->boostedLangs[$language] ) ) {
$p = round( $p * ( 1 - $this->langBoostScore ) );
}
$results[$language] = $p;
}
asort( $results );
// ignore any item that scores higher than best * resultsRatio
$max = reset( $results ) * $this->resultsRatio;
$results = array_filter( $results, function ( $res ) use ( $max ) { return $res <= $max;
} );
// if more than maxReturnedLanguages remain, the result is too ambiguous, so bail
if ( count( $results ) > $this->maxReturnedLanguages ) {
$this->resultStatus = self::STATUSAMBIGUOUS;
return array();
}
// filter max proportion of max score after ambiguity check; reuse $max variable
$max = count( $inputgrams ) * $this->maxNgrams * $this->maxProportion;
$results = array_filter( $results, function ( $res ) use ( $max ) { return $res <= $max;
} );
if ( count( $results ) == 0 ) {
$this->resultStatus = self::STATUSNOMATCH;
return $results;
}
return $results;
}
}