Skip to main content

geocoder_core/text/
mod.rs

1//! Language-agnostic text primitives, ported from `addok.helpers.text`.
2//!
3//! Country or language specific processing lives in `crate::profile`.
4
5mod synonyms;
6mod token;
7
8use unidecode::unidecode;
9
10pub use synonyms::Synonyms;
11pub use token::{Token, TokenKind};
12
13/// `addok.helpers.text.ascii`: lowercase, transliterate, replace every non-word
14/// character by a space, collapse runs of spaces and trim.
15pub fn ascii(value: &str) -> String {
16    alphanumerize(&transliterate(&value.to_lowercase()))
17        .trim()
18        .to_string()
19}
20
21fn alphanumerize(text: &str) -> String {
22    let mut out = String::with_capacity(text.len());
23    let mut previous_space = false;
24    for c in text.chars() {
25        // After unidecode the text is ASCII, where `\w` is `[A-Za-z0-9_]`.
26        let c = if c.is_alphanumeric() || c == '_' {
27            c
28        } else {
29            ' '
30        };
31        if c == ' ' {
32            if previous_space {
33                continue;
34            }
35            previous_space = true;
36        } else {
37            previous_space = false;
38        }
39        out.push(c);
40    }
41    out
42}
43
44/// Python's `\w` on `str`: `isalnum()` or `_`. Unlike the `regex` crate's
45/// `\w`, it includes numbers such as "½" and excludes combining marks.
46fn is_word_char(c: char) -> bool {
47    c.is_alphanumeric() || c == '_'
48}
49
50/// `addok.helpers.text.tokenize` followed by `normalize`.
51pub fn tokenize(text: &str) -> Vec<Token> {
52    text.split(|c: char| !is_word_char(c))
53        .filter(|w| !w.is_empty())
54        .enumerate()
55        .map(|(position, word)| Token::new(normalize(word), position))
56        .collect()
57}
58
59/// `addok.helpers.text.normalize`: `unidecode(s.lower())`.
60pub fn normalize(token: &str) -> String {
61    transliterate(&token.to_lowercase())
62}
63
64/// `unidecode`, aligned on Python's Unidecode 1.3.6 (pinned by addok 1.1)
65/// where the Rust tables differ: vulgar fractions get a leading space
66/// (" 1/2"), which splits the token later on, like addok does with
67/// mis-encoded "œ" ("S½urdres" → "s", "1/2urdr").
68fn transliterate(s: &str) -> String {
69    if !s.contains(['¼', '½', '¾']) {
70        return unidecode(s);
71    }
72    let spaced = s
73        .replace('¼', " 1/4")
74        .replace('½', " 1/2")
75        .replace('¾', " 3/4");
76    unidecode(&spaced)
77}
78
79/// Python's `str.isdigit()` for the ASCII strings we deal with.
80pub fn is_digit(s: &str) -> bool {
81    !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())
82}
83
84/// `addok.helpers.text.compare_ngrams(left, right, N=2, pad_len=0)`, i.e.
85/// `NGram.compare`: shared bigrams (with multiplicity) over the bigrams of
86/// both strings minus the shared ones.
87pub fn compare_ngrams(left: &str, right: &str) -> f64 {
88    let left: Vec<char> = ascii(left).chars().collect();
89    let right: Vec<char> = ascii(right).chars().collect();
90    if left.len() == 1 && right.len() == 1 {
91        return if left == right { 1.0 } else { 0.0 };
92    }
93    if left.len() < 2 || right.len() < 2 {
94        return 0.0;
95    }
96    let mut counts: std::collections::HashMap<(char, char), u32> = std::collections::HashMap::new();
97    for w in left.windows(2) {
98        *counts.entry((w[0], w[1])).or_default() += 1;
99    }
100    let mut same = 0u32;
101    for w in right.windows(2) {
102        if let Some(remaining) = counts.get_mut(&(w[0], w[1]))
103            && *remaining > 0
104        {
105            *remaining -= 1;
106            same += 1;
107        }
108    }
109    if same == 0 {
110        return 0.0;
111    }
112    let all = (left.len() - 1) + (right.len() - 1) - same as usize;
113    same as f64 / all as f64
114}
115
116/// `addok.helpers.text.compute_edge_ngrams`: prefixes from `min` chars up to,
117/// but excluding, the token itself, on the token cut to `max + 1` chars.
118pub fn edge_ngrams(token: &str, min: usize, max: usize) -> Vec<String> {
119    let chars: Vec<char> = token.chars().take(max + 1).collect();
120    (min..chars.len())
121        .map(|i| chars[..i].iter().collect())
122        .collect()
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    #[test]
130    fn ascii_folds_like_addok() {
131        assert_eq!(ascii("Rue de l'Église"), "rue de l eglise");
132        assert_eq!(ascii(" Saint-Étienne  (42)"), "saint etienne 42");
133    }
134
135    #[test]
136    fn ngram_compare_matches_python() {
137        // Values computed with ngram 4.0.3, the version addok 1.0.3 pins.
138        let cases = [
139            ("rue de la paix 75002 paris", "rue de la paix paris", 0.76),
140            (
141                "avenue des champs elysees 75008 paris",
142                "20 avenue des champs elysees paris",
143                0.769_230_769,
144            ),
145            ("rue de bordeaux 16000 angouleme", "bordeaux", 0.233_333_333),
146        ];
147        for (l, r, expected) in cases {
148            assert!((compare_ngrams(l, r) - expected).abs() < 1e-6, "{l} / {r}");
149        }
150    }
151
152    #[test]
153    fn edge_ngrams_exclude_the_token() {
154        assert_eq!(edge_ngrams("paris", 3, 20), vec!["par", "pari"]);
155        assert!(edge_ngrams("rue", 3, 20).is_empty());
156    }
157}