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
use fnv::FnvHashMap;
use lang::*;
use script::*;
use trigrams::*;
use info::Info;
use options::{Options, List};
const MAX_TRIGRAM_DISTANCE : u32 = 300;
const MAX_TOTAL_DISTANCE : u32 = 90_000;
pub fn detect(text: &str) -> Option<Info> {
detect_with_options(text, &Options::default())
}
pub fn detect_lang(text: &str) -> Option<Lang> {
detect(text).map(|info| info.lang)
}
pub fn detect_lang_with_options(text: &str, options: &Options) -> Option<Lang> {
detect_with_options(text, options).map(|info| info.lang)
}
pub fn detect_with_options(text: &str, options: &Options) -> Option<Info> {
detect_script(text).and_then(|script| {
detect_lang_based_on_script(text, options, script).map( |(lang, confidence)| {
Info { lang, script, confidence }
})
})
}
fn detect_lang_based_on_script(text: &str, options: &Options, script : Script) -> Option<(Lang, f64)> {
match script {
Script::Latin => detect_lang_in_profiles(text, options, LATIN_LANGS),
Script::Cyrillic => detect_lang_in_profiles(text, options, CYRILLIC_LANGS),
Script::Devanagari => detect_lang_in_profiles(text, options, DEVANAGARI_LANGS),
Script::Hebrew => detect_lang_in_profiles(text, options, HEBREW_LANGS),
Script::Ethiopic => detect_lang_in_profiles(text, options, ETHIOPIC_LANGS),
Script::Arabic => detect_lang_in_profiles(text, options, ARABIC_LANGS),
Script::Mandarin => Some((Lang::Cmn, 1.0)),
Script::Bengali => Some((Lang::Ben, 1.0)),
Script::Hangul => Some((Lang::Kor, 1.0)),
Script::Georgian => Some((Lang::Kat, 1.0)),
Script::Greek => Some((Lang::Ell, 1.0)),
Script::Kannada => Some((Lang::Kan, 1.0)),
Script::Tamil => Some((Lang::Tam, 1.0)),
Script::Thai => Some((Lang::Tha, 1.0)),
Script::Gujarati => Some((Lang::Guj, 1.0)),
Script::Gurmukhi => Some((Lang::Pan, 1.0)),
Script::Telugu => Some((Lang::Tel, 1.0)),
Script::Malayalam => Some((Lang::Mal, 1.0)),
Script::Oriya => Some((Lang::Ori, 1.0)),
Script::Myanmar => Some((Lang::Mya, 1.0)),
Script::Sinhala => Some((Lang::Sin, 1.0)),
Script::Khmer => Some((Lang::Khm, 1.0)),
Script::Katakana | Script::Hiragana => Some((Lang::Jpn, 1.0))
}
}
fn detect_lang_in_profiles(text: &str, options: &Options, lang_profile_list : LangProfileList) -> Option<(Lang, f64)> {
let mut lang_distances : Vec<(Lang, u32)> = vec![];
let trigrams = get_trigrams_with_positions(text);
for &(ref lang, lang_trigrams) in lang_profile_list {
match options.list {
Some(List::White(ref whitelist)) if !whitelist.contains(lang) => continue,
Some(List::Black(ref blacklist)) if blacklist.contains(lang) => continue,
_ => {},
}
let dist = calculate_distance(lang_trigrams, &trigrams);
lang_distances.push(((*lang), dist));
}
lang_distances.sort_by_key(|key| key.1 );
if lang_distances.len() < 2 {
return lang_distances.first().map(|pair| (pair.0, 1.0));
}
let lang_dist1 = lang_distances[0];
let lang_dist2 = lang_distances[1];
let score1 = MAX_TOTAL_DISTANCE - lang_dist1.1;
let score2 = MAX_TOTAL_DISTANCE - lang_dist2.1;
let rate = (score1 - score2) as f64 / (score2 as f64);
let confident_rate = (12.0 / trigrams.len() as f64) + 0.05;
let confidence =
if rate > confident_rate {
1.0
} else {
rate / confident_rate
};
Some((lang_dist1.0, confidence))
}
fn calculate_distance(lang_trigrams: LangProfile, text_trigrams: &FnvHashMap<String, u32>) -> u32 {
let mut total_dist = 0u32;
for (i, &trigram) in lang_trigrams.iter().enumerate() {
let dist = match text_trigrams.get(trigram) {
Some(&n) => (n as i32 - i as i32).abs() as u32,
None => MAX_TRIGRAM_DISTANCE
};
total_dist += dist;
}
total_dist
}
#[cfg(test)]
mod tests {
use super::*;
use script::Script;
#[test]
fn test_detect_spanish() {
let text = "Además de todo lo anteriormente dicho, también encontramos...";
let output = detect(text);
assert_eq!(output.is_some(), true);
let info = output.unwrap();
assert_eq!(info.lang, Lang::Spa);
assert_eq!(info.script, Script::Latin);
}
#[test]
fn test_detect_lang_ukrainian() {
let text = "Та нічого, все нормально. А в тебе як?";
assert_eq!(detect_lang(text), Some(Lang::Ukr));
}
#[test]
fn test_detect_with_options_with_blacklist() {
let text = "I am begging pardon";
let output = detect_with_options(text, &Options::default());
assert_eq!(output.is_some(), true);
let info = output.unwrap();
assert_eq!(info.lang, Lang::Tgl);
let blacklist = vec![Lang::Tgl, Lang::Jav, Lang::Nld, Lang::Uzb, Lang::Swe, Lang::Nob, Lang::Ceb, Lang::Ilo];
let options = Options::new().set_blacklist(blacklist);
let output = detect_with_options(text, &options);
assert_eq!(output.is_some(), true);
let info = output.unwrap();
assert_eq!(info.lang, Lang::Eng);
}
#[test]
fn test_detect_with_options_with_blacklist_none() {
let text = "האקדמיה ללשון העברית";
let blacklist = vec![Lang::Heb, Lang::Ydd];
let options = Options::new().set_blacklist(blacklist);
let output = detect_with_options(text, &options);
assert_eq!(output, None);
}
#[test]
fn test_detect_with_options_with_whitelist() {
let whitelist = vec![Lang::Epo, Lang::Ukr];
let options = Options::new().set_whitelist(whitelist);
let text = "Mi ne scias!";
let output = detect_with_options(text, &options);
assert_eq!(output.is_some(), true);
let info = output.unwrap();
assert_eq!(info.lang, Lang::Epo);
}
}