1use std::collections::HashMap;
8use std::fmt;
9use std::sync::{LazyLock, OnceLock};
10
11use regex::Regex;
12use serde_json::Value;
13use unicode_normalization::UnicodeNormalization;
14
15const LANGUAGE_TRIGRAMS_LINKS: &str = include_str!("data/language-trigrams.lino");
16const MAX_LENGTH: usize = 2048;
17const MAX_DIFFERENCE: usize = 300;
18const DEFAULT_THRESHOLD: f64 = 0.1;
19const MINIMUM_CONFIDENCE_GAP: f64 = 0.02;
20static LETTER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A\p{L}\z").expect("letter regex"));
21static MARK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A\p{M}\z").expect("mark regex"));
22
23pub const LANGUAGE_IDENTIFIER_TERM: &str = "identifier:trigram";
25
26struct Script {
27 name: String,
28 ranges: Vec<(u32, u32)>,
29}
30
31type LanguageModel = (String, HashMap<String, usize>);
33
34struct TrigramData {
35 languages: HashMap<String, &'static str>,
36 scripts: Vec<Script>,
37 models: HashMap<String, Vec<LanguageModel>>,
38 cyrillic_catalog_alphabet: String,
39}
40
41fn trigram_data() -> &'static TrigramData {
42 static DATA: OnceLock<TrigramData> = OnceLock::new();
43 DATA.get_or_init(parse_trigram_data)
44}
45
46fn parse_trigram_data() -> TrigramData {
47 let value: Value =
48 crate::structured_data_links::read_structured_data_lino(LANGUAGE_TRIGRAMS_LINKS)
49 .expect("language trigram data is valid Links Notation");
50 let languages = value["languages"]
51 .as_object()
52 .expect("languages object")
53 .iter()
54 .map(|(code, name)| {
55 let name = crate::natural_language::canonical_natural_language(
56 name.as_str().expect("language name"),
57 )
58 .expect("supported natural language");
59 (code.clone(), name)
60 })
61 .collect();
62 let scripts = value["scripts"]
63 .as_array()
64 .expect("scripts array")
65 .iter()
66 .map(|script| Script {
67 name: script["name"].as_str().expect("script name").to_string(),
68 ranges: script["ranges"]
69 .as_array()
70 .expect("script ranges")
71 .iter()
72 .map(|range| {
73 let bound = |index: usize| {
74 u32::try_from(range[index].as_u64().expect("range bound"))
75 .expect("code point")
76 };
77 (bound(0), bound(1))
78 })
79 .collect(),
80 })
81 .collect();
82 let models = value["models"]
83 .as_array()
84 .expect("models array")
85 .iter()
86 .map(|model| {
87 let languages = model["languages"]
88 .as_array()
89 .expect("model languages")
90 .iter()
91 .map(|language| {
92 let ranks = language["trigrams"]
93 .as_str()
94 .expect("trigram model")
95 .split('|')
96 .enumerate()
97 .map(|(rank, trigram)| (trigram.to_string(), rank))
98 .collect();
99 (language["code"].as_str().expect("code").to_string(), ranks)
100 })
101 .collect();
102 (
103 model["script"].as_str().expect("script").to_string(),
104 languages,
105 )
106 })
107 .collect();
108 TrigramData {
109 languages,
110 scripts,
111 models,
112 cyrillic_catalog_alphabet: value["cyrillicCatalogAlphabet"]
113 .as_str()
114 .expect("Cyrillic catalog alphabet")
115 .to_owned(),
116 }
117}
118
119#[derive(Clone, Debug, PartialEq)]
121pub struct LanguageCandidate {
122 pub language: &'static str,
124 pub confidence: f64,
126}
127
128#[derive(Clone, Debug, PartialEq)]
130pub struct LanguageIdentificationSpan {
131 pub start: usize,
133 pub end: usize,
135 pub language: Option<&'static str>,
137 pub candidates: Vec<LanguageCandidate>,
139}
140
141#[derive(Clone, Debug, PartialEq)]
143pub struct LanguageIdentification {
144 pub language: Option<&'static str>,
146 pub candidates: Vec<LanguageCandidate>,
148 pub spans: Vec<LanguageIdentificationSpan>,
150}
151
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub struct InvalidLanguageIdentificationThreshold;
155
156impl fmt::Display for InvalidLanguageIdentificationThreshold {
157 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
158 formatter.write_str("Language identification threshold must be between 0 and 1")
159 }
160}
161
162impl std::error::Error for InvalidLanguageIdentificationThreshold {}
163
164#[must_use]
170pub fn identify_language(text: &str) -> LanguageIdentification {
171 language_identification(text, DEFAULT_THRESHOLD)
172}
173
174pub fn identify_language_with_threshold(
184 text: &str,
185 threshold: f64,
186) -> Result<LanguageIdentification, InvalidLanguageIdentificationThreshold> {
187 if !(0.0..=1.0).contains(&threshold) {
188 return Err(InvalidLanguageIdentificationThreshold);
189 }
190 Ok(language_identification(text, threshold))
191}
192
193fn language_identification(text: &str, threshold: f64) -> LanguageIdentification {
194 let data = trigram_data();
195 let mut totals = Vec::<(&'static str, f64)>::new();
196 let mut letter_count = 0;
197 let spans: Vec<_> = script_runs(data, text)
198 .into_iter()
199 .map(|run| {
200 let candidates = rank_run(data, &text[run.start..run.end], &run);
201 letter_count += run.letter_count;
202 for candidate in &candidates {
203 let weighted = candidate.confidence * f64::from(run.letter_count);
204 if let Some((_, sum)) = totals
205 .iter_mut()
206 .find(|(name, _)| *name == candidate.language)
207 {
208 *sum += weighted;
209 } else {
210 totals.push((candidate.language, weighted));
211 }
212 }
213 LanguageIdentificationSpan {
214 start: run.start,
215 end: run.end,
216 language: select_language(&candidates, threshold),
217 candidates,
218 }
219 })
220 .collect();
221 if let [span] = spans.as_slice() {
222 return LanguageIdentification {
223 language: span.language,
224 candidates: span.candidates.clone(),
225 spans,
226 };
227 }
228 let mut candidates: Vec<_> = totals
229 .into_iter()
230 .map(|(language, total)| LanguageCandidate {
231 language,
232 confidence: total / f64::from(letter_count),
233 })
234 .collect();
235 candidates.sort_by(|left, right| right.confidence.total_cmp(&left.confidence));
236 LanguageIdentification {
237 language: select_language(&candidates, threshold),
238 candidates,
239 spans,
240 }
241}
242
243fn select_language(candidates: &[LanguageCandidate], threshold: f64) -> Option<&'static str> {
244 let [best, remaining @ ..] = candidates else {
245 return None;
246 };
247 if best.confidence < threshold {
248 return None;
249 }
250 if remaining
251 .first()
252 .is_some_and(|second| best.confidence - second.confidence < MINIMUM_CONFIDENCE_GAP)
253 {
254 return None;
255 }
256 Some(best.language)
257}
258
259struct ScriptRun<'a> {
260 script: Option<&'a str>,
261 start: usize,
262 end: usize,
263 letter_count: u32,
264}
265
266fn script_runs<'a>(data: &'a TrigramData, text: &str) -> Vec<ScriptRun<'a>> {
267 let mut runs = Vec::<ScriptRun<'a>>::new();
268 let mut attached = false;
269 for (start, character) in text.char_indices().take(MAX_LENGTH) {
270 let mut utf8 = [0; 4];
271 let encoded = character.encode_utf8(&mut utf8);
272 let end = start + encoded.len();
273 if LETTER.is_match(encoded) {
274 let script = data
275 .scripts
276 .iter()
277 .find(|script| in_ranges(u32::from(character), &script.ranges))
278 .map(|script| script.name.as_str());
279 if let Some(run) = runs.last_mut().filter(|run| run.script == script) {
280 run.end = end;
281 run.letter_count += 1;
282 } else {
283 runs.push(ScriptRun {
284 script,
285 start,
286 end,
287 letter_count: 1,
288 });
289 }
290 attached = true;
291 } else {
292 attached = attached && MARK.is_match(encoded);
293 if attached && let Some(run) = runs.last_mut() {
294 run.end = end;
295 }
296 }
297 }
298 runs
299}
300
301fn rank_run(data: &TrigramData, text: &str, run: &ScriptRun<'_>) -> Vec<LanguageCandidate> {
302 let Some(script) = run.script else {
303 return Vec::new();
304 };
305 let Some(models) = data.models.get(script) else {
306 return data
307 .languages
308 .get(script)
309 .map_or_else(Vec::new, |&language| {
310 vec![LanguageCandidate {
311 language,
312 confidence: 1.0,
313 }]
314 });
315 };
316 if run.letter_count < 3 || models.is_empty() {
317 return Vec::new();
318 }
319
320 let characters: Vec<_> = text.nfc().collect();
321 if script == "Cyrillic"
322 && characters.iter().any(|character| {
323 LETTER.is_match(character.encode_utf8(&mut [0; 4]))
324 && !data
325 .cyrillic_catalog_alphabet
326 .contains(character.to_lowercase().next().unwrap_or(*character))
327 })
328 {
329 return Vec::new();
330 }
331
332 let trigrams = trigram_counts(&characters);
333 let maximum = trigrams.len() * MAX_DIFFERENCE;
334 let mut ranked: Vec<_> = models
335 .iter()
336 .map(|(code, model)| {
337 (
338 data.languages.get(code).copied(),
339 trigram_distance(&trigrams, model),
340 )
341 })
342 .collect();
343 ranked.sort_by_key(|&(_, distance)| distance);
344 if ranked
346 .iter()
347 .any(|&(language, distance)| language.is_none() && distance == ranked[0].1)
348 {
349 return Vec::new();
350 }
351 let score = |value| f64::from(u32::try_from(value).expect("bounded trigram score"));
352 ranked
353 .into_iter()
354 .filter_map(|(language, distance)| {
355 let language = language?;
356 (distance < maximum).then(|| LanguageCandidate {
357 language,
358 confidence: score(maximum - distance) / score(maximum),
359 })
360 })
361 .collect()
362}
363
364pub fn identify_catalog_language(text: &str) -> Option<&'static str> {
366 let data = trigram_data();
367 let characters: Vec<char> = text.chars().take(MAX_LENGTH).collect();
368 if characters.is_empty() {
369 return None;
370 }
371
372 let script = top_script(&data.scripts, &characters)?;
373 let Some(models) = data.models.get(script) else {
374 return data.languages.get(script).copied();
375 };
376
377 let trigrams = trigram_counts(&characters);
378 let (code, distance) = models
379 .iter()
380 .filter(|(code, _)| data.languages.contains_key(code))
381 .map(|(code, model)| (code, trigram_distance(&trigrams, model)))
382 .fold(
383 None,
384 |best: Option<(&String, usize)>, candidate| match best {
385 Some(best) if best.1 <= candidate.1 => Some(best),
386 _ => Some(candidate),
387 },
388 )?;
389 if distance >= characters.len() * MAX_DIFFERENCE {
391 return None;
392 }
393 data.languages.get(code).copied()
394}
395
396fn top_script<'a>(scripts: &'a [Script], characters: &[char]) -> Option<&'a str> {
397 let mut top = None;
398 let mut top_count = 0;
399 for script in scripts {
400 let count = characters
401 .iter()
402 .filter(|character| in_ranges(u32::from(**character), &script.ranges))
403 .count();
404 if count > top_count {
405 top = Some(script.name.as_str());
406 top_count = count;
407 }
408 }
409 top
410}
411
412fn in_ranges(code_point: u32, ranges: &[(u32, u32)]) -> bool {
413 ranges
414 .binary_search_by(|&(start, end)| {
415 if code_point < start {
416 std::cmp::Ordering::Greater
417 } else if code_point > end {
418 std::cmp::Ordering::Less
419 } else {
420 std::cmp::Ordering::Equal
421 }
422 })
423 .is_ok()
424}
425
426const fn is_ecmascript_whitespace(character: char) -> bool {
428 matches!(
429 character,
430 '\t' | '\n' | '\u{0b}' | '\u{0c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}'
431 ..='\u{200a}'
432 | '\u{2028}'
433 | '\u{2029}'
434 | '\u{202f}'
435 | '\u{205f}'
436 | '\u{3000}'
437 | '\u{feff}'
438 )
439}
440
441fn clean_characters(characters: &[char]) -> Vec<char> {
444 let mut cleaned = String::new();
445 for &character in characters {
446 if ('\u{21}'..='\u{40}').contains(&character) || is_ecmascript_whitespace(character) {
447 if !cleaned.is_empty() && !cleaned.ends_with(' ') {
448 cleaned.push(' ');
449 }
450 } else {
451 cleaned.push(character);
452 }
453 }
454 if cleaned.ends_with(' ') {
455 cleaned.pop();
456 }
457 cleaned.to_lowercase().chars().collect()
458}
459
460fn trigram_counts(characters: &[char]) -> Vec<(String, usize)> {
462 let mut padded = vec![' '];
463 padded.extend(clean_characters(characters));
464 padded.push(' ');
465 let mut counts: Vec<(String, usize)> = Vec::new();
466 let mut positions: HashMap<String, usize> = HashMap::new();
467 for window in padded.windows(3) {
468 let trigram: String = window.iter().collect();
469 if let Some(&position) = positions.get(&trigram) {
470 counts[position].1 += 1;
471 } else {
472 positions.insert(trigram.clone(), counts.len());
473 counts.push((trigram, 1));
474 }
475 }
476 counts.sort_by_key(|(_, count)| *count);
477 counts
478}
479
480fn trigram_distance(trigrams: &[(String, usize)], model: &HashMap<String, usize>) -> usize {
481 trigrams
482 .iter()
483 .map(|(trigram, count)| {
484 model
485 .get(trigram)
486 .map_or(MAX_DIFFERENCE, |rank| count.abs_diff(rank + 1))
487 })
488 .sum()
489}