Skip to main content

instant_segment/
lib.rs

1use std::ops::{Index, Range};
2use std::str;
3
4use compact_str::CompactString;
5#[cfg(feature = "serde")]
6use serde::{Deserialize, Serialize};
7
8#[cfg(feature = "test-cases")]
9pub mod test_cases;
10#[cfg(feature = "__test_data")]
11pub mod test_data;
12
13/// Central data structure used to calculate word probabilities
14#[cfg_attr(feature = "with-serde", derive(Deserialize, Serialize))]
15pub struct Segmenter {
16    // Maps a word to both its unigram score, as well has a nested HashMap in
17    // which the bigram score can be looked up using the previous word. Scores
18    // are base-10 logarithms of relative word frequencies
19    scores: HashMap<CompactString, (f64, HashMap<CompactString, f64>)>,
20    // Base-10 logarithm of the total count of unigrams
21    uni_total_log10: f64,
22    limit: usize,
23}
24
25impl Segmenter {
26    /// Create `Segmenter` from the given unigram and bigram counts.
27    pub fn new<U, B>(unigrams: U, bigrams: B) -> Self
28    where
29        U: IntoIterator<Item = (CompactString, f64)>,
30        B: IntoIterator<Item = ((CompactString, CompactString), f64)>,
31    {
32        // Initially, `scores` contains the original unigram and bigram counts
33        let mut scores = HashMap::default();
34        let mut uni_total = 0.0;
35        for (word, uni) in unigrams {
36            scores.insert(word, (uni, HashMap::default()));
37            uni_total += uni;
38        }
39        let mut bi_total = 0.0;
40        for ((word1, word2), bi) in bigrams {
41            let Some((_, bi_scores)) = scores.get_mut(&word2) else {
42                // We throw away bigrams for which we do not have a unigram for
43                // the second word. This case shouldn't ever happen on
44                // real-world data, and in fact, it never happens on the word
45                // count lists shipped with this crate.
46                continue;
47            };
48            bi_scores.insert(word1, bi);
49            bi_total += bi;
50        }
51
52        // Now convert the counts in `scores` to the values we actually want,
53        // namely logarithms of relative frequencies
54        for (uni, bi_scores) in scores.values_mut() {
55            *uni = (*uni / uni_total).log10();
56            for bi in bi_scores.values_mut() {
57                *bi = (*bi / bi_total).log10();
58            }
59        }
60
61        Self {
62            uni_total_log10: uni_total.log10(),
63            scores,
64            limit: DEFAULT_LIMIT,
65        }
66    }
67
68    /// Segment the text in `input`
69    ///
70    /// Requires that the input `text` consists of lowercase ASCII characters only. Otherwise,
71    /// returns `Err(InvalidCharacter)`. The `search` parameter contains caches that are used
72    /// segmentation; passing it in allows the callers to reuse the cache allocations.
73    pub fn segment<'a>(
74        &self,
75        input: &str,
76        search: &'a mut Search,
77    ) -> Result<Segments<'a>, InvalidCharacter> {
78        let state = SegmentState::new(Ascii::new(input)?, self, search);
79        let score = match input {
80            "" => 0.0,
81            _ => state.run(),
82        };
83
84        Ok(Segments {
85            iter: search.result.iter(),
86            score,
87        })
88    }
89
90    /// Returns the sentence's score
91    ///
92    /// Returns the relative probability for the given sentence in the the corpus represented by
93    /// this `Segmenter`. Will return `None` iff given an empty iterator argument.
94    pub fn score_sentence<'a>(&self, mut words: impl Iterator<Item = &'a str>) -> Option<f64> {
95        let mut prev = words.next()?;
96        let mut score = self.score(prev, None);
97        for word in words {
98            score += self.score(word, Some(prev));
99            prev = word;
100        }
101        Some(score)
102    }
103
104    fn score(&self, word: &str, previous: Option<&str>) -> f64 {
105        let (uni, bi_scores) = match self.scores.get(word) {
106            Some((uni, bi_scores)) => (uni, bi_scores),
107            // Penalize words not found in the unigrams according
108            // to their length, a crucial heuristic.
109            //
110            // In the original presentation non-words are scored as
111            //
112            //    (1.0 - self.uni_total_log10 - word_len)
113            //
114            // However in practice this seems to under-penalize long non-words.  The intuition
115            // behind the variation used here is that it applies this penalty once for each word
116            // there "should" have been in the non-word's place.
117            //
118            // See <https://github.com/instant-labs/instant-segment/issues/53>.
119            None => {
120                let word_len = word.len() as f64;
121                let word_count = word_len / 5.0;
122                return (1.0 - self.uni_total_log10 - word_len) * word_count;
123            }
124        };
125
126        if let Some(prev) = previous {
127            if let Some(bi) = bi_scores.get(prev) {
128                if let Some((uni_prev, _)) = self.scores.get(prev) {
129                    // Conditional probability of the word given the previous
130                    // word. The technical name is "stupid backoff" and it's
131                    // not a probability distribution but it works well in practice.
132                    return bi - uni_prev;
133                }
134            }
135        }
136
137        *uni
138    }
139
140    /// Customize the word length `limit`
141    pub fn set_limit(&mut self, limit: usize) {
142        self.limit = limit;
143    }
144}
145
146pub struct Segments<'a> {
147    iter: std::slice::Iter<'a, CompactString>,
148    score: f64,
149}
150
151impl Segments<'_> {
152    /// Returns the score of the segmented text
153    pub fn score(&self) -> f64 {
154        self.score
155    }
156}
157
158impl<'a> Iterator for Segments<'a> {
159    type Item = &'a str;
160
161    fn next(&mut self) -> Option<Self::Item> {
162        self.iter.next().map(|v| v.as_str())
163    }
164}
165
166impl ExactSizeIterator for Segments<'_> {
167    fn len(&self) -> usize {
168        self.iter.len()
169    }
170}
171
172struct SegmentState<'a> {
173    data: &'a Segmenter,
174    text: Ascii<'a>,
175    search: &'a mut Search,
176}
177
178impl<'a> SegmentState<'a> {
179    fn new(text: Ascii<'a>, data: &'a Segmenter, search: &'a mut Search) -> Self {
180        search.clear();
181        Self { data, text, search }
182    }
183
184    fn run(self) -> f64 {
185        for end in 1..=self.text.len() {
186            let start = end.saturating_sub(self.data.limit);
187            for split in start..end {
188                let (prev, prev_score) = match split {
189                    0 => (None, 0.0),
190                    _ => {
191                        let prefix = self.search.candidates[split - 1];
192                        let word = &self.text[split - prefix.len..split];
193                        (Some(word), prefix.score)
194                    }
195                };
196
197                let word = &self.text[split..end];
198                let score = self.data.score(word, prev) + prev_score;
199                match self.search.candidates.get_mut(end - 1) {
200                    Some(cur) if cur.score < score => {
201                        cur.len = end - split;
202                        cur.score = score;
203                    }
204                    None => self.search.candidates.push(Candidate {
205                        len: end - split,
206                        score,
207                    }),
208                    _ => {}
209                }
210            }
211        }
212
213        let mut end = self.text.len();
214        let mut best = self.search.candidates[end - 1];
215        let score = best.score;
216        loop {
217            let word = &self.text[end - best.len..end];
218            self.search.result.push(word.into());
219
220            end -= best.len;
221            if end == 0 {
222                break;
223            }
224
225            best = self.search.candidates[end - 1];
226        }
227
228        self.search.result.reverse();
229        score
230    }
231}
232
233/// Search state for a [`Segmenter`]
234#[derive(Clone, Default)]
235pub struct Search {
236    candidates: Vec<Candidate>,
237    result: Vec<CompactString>,
238}
239
240impl Search {
241    fn clear(&mut self) {
242        self.candidates.clear();
243        self.result.clear();
244    }
245
246    #[doc(hidden)]
247    pub fn get(&self, idx: usize) -> Option<&str> {
248        self.result.get(idx).map(|v| v.as_str())
249    }
250}
251
252#[derive(Clone, Copy, Debug, Default)]
253struct Candidate {
254    len: usize,
255    score: f64,
256}
257
258#[derive(Debug)]
259struct Ascii<'a>(&'a [u8]);
260
261impl<'a> Ascii<'a> {
262    fn new(s: &'a str) -> Result<Self, InvalidCharacter> {
263        let bytes = s.as_bytes();
264
265        let valid = bytes
266            .iter()
267            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit());
268
269        match valid {
270            true => Ok(Self(bytes)),
271            false => Err(InvalidCharacter),
272        }
273    }
274
275    fn len(&self) -> usize {
276        self.0.len()
277    }
278}
279
280impl Index<Range<usize>> for Ascii<'_> {
281    type Output = str;
282
283    fn index(&self, index: Range<usize>) -> &Self::Output {
284        let bytes = self.0.index(index);
285        // Since `Ascii` can only be instantiated with ASCII characters, this should be safe
286        unsafe { str::from_utf8_unchecked(bytes) }
287    }
288}
289
290/// Error returned by [`Segmenter::segment`] when given an invalid character
291#[derive(Debug)]
292pub struct InvalidCharacter;
293
294impl std::error::Error for InvalidCharacter {}
295
296impl std::fmt::Display for InvalidCharacter {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        f.write_str("invalid character")
299    }
300}
301
302type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;
303
304const DEFAULT_LIMIT: usize = 24;
305
306#[cfg(test)]
307pub mod tests {
308    use super::*;
309
310    #[test]
311    fn test_clean() {
312        Ascii::new("Can't buy me love!").unwrap_err();
313        let text = Ascii::new("cantbuymelove").unwrap();
314        assert_eq!(&text[0..text.len()], "cantbuymelove");
315        let text_with_numbers = Ascii::new("c4ntbuym3l0v3").unwrap();
316        assert_eq!(
317            &text_with_numbers[0..text_with_numbers.len()],
318            "c4ntbuym3l0v3"
319        );
320    }
321}