Skip to main content

paper/core/
text.rs

1//! Script-aware tokenisation and deterministic excerpting.
2//!
3//! SQLite's `unicode61` tokenizer treats a run of CJK, Thai, Lao, Khmer or
4//! Myanmar characters as a *single* token, so `保証` never matches inside
5//! `保証期間は24ヶ月です`. The fix is applied identically when indexing and when
6//! querying:
7//!
8//! - **CJK runs** become overlapping character bigrams plus the first character
9//!   of the run (`全文檢索` → `全 全文 文檢 檢索`). This is the best-performing
10//!   dictionary-free scheme measured across Chinese, Japanese and Korean; it
11//!   keeps two-character words searchable, which `trigram` cannot, and it needs
12//!   no dictionary, so it is not tied to one language variant.
13//! - **Thai, Lao, Khmer, Myanmar** have no spaces either but are not made of
14//!   bigram-sized units, so each character is emitted as a token.
15//! - **Everything else** is left to `unicode61`.
16//!
17//! Optional dictionary segmenters:
18//! - Jieba (feature `jieba-rs`) for Chinese word-level segmentation
19//! - ICU (feature `icu_segmenter`) for word boundaries in CJK, Korean, Thai,
20//!   Lao, Khmer, Myanmar, Arabic, Hebrew, Devanagari, etc.
21//! - Lindera (feature `lindera`) for Japanese with IPADIC dictionary
22//!
23//! All optional segmenters are opt-in and default off to keep the binary small
24//! and dependency-free.
25//!
26//! No stemming: it would be a guess, and a guess changes the bytes a citation
27//! points at.
28
29use unicode_normalization::UnicodeNormalization;
30
31#[cfg(feature = "icu_segmenter")]
32mod icu_segmenter;
33#[cfg(feature = "icu_segmenter")]
34use icu_segmenter::icu_segment;
35
36#[cfg(feature = "lindera")]
37mod lindera_segmenter;
38#[cfg(feature = "lindera")]
39use lindera_segmenter::lindera_segment;
40
41/// A segmenter splits text into tokens for FTS5 indexing and querying.
42///
43/// Implementations should be deterministic and produce the same tokens for
44/// identical input. The tokens are joined with spaces to form the FTS5 input.
45pub trait Segmenter: Send + Sync {
46    /// Segment text into tokens. Returns an iterator over owned token strings.
47    fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_>;
48
49    /// Name of the segmenter (for diagnostics).
50    fn name(&self) -> &'static str;
51}
52
53// Auto-implement Segmenter for Box<dyn Segmenter> so we can store boxed segmenters
54impl Segmenter for Box<dyn Segmenter> {
55    fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_> {
56        self.as_ref().segment(text)
57    }
58
59    fn name(&self) -> &'static str {
60        self.as_ref().name()
61    }
62}
63
64/// The default bigram+first-char segmenter (no dictionary, works for all CJK).
65pub struct BigramFirstCharSegmenter;
66
67impl Segmenter for BigramFirstCharSegmenter {
68    fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_> {
69        let tokens = collect_bigram_first_char(text);
70        Box::new(tokens.into_iter())
71    }
72
73    fn name(&self) -> &'static str {
74        "bigram-first-char"
75    }
76}
77
78/// Jieba Chinese segmenter (feature `jieba-rs`).
79#[cfg(feature = "jieba-rs")]
80pub struct JiebaSegmenter {
81    jieba: jieba_rs::Jieba,
82}
83
84#[cfg(feature = "jieba-rs")]
85impl Default for JiebaSegmenter {
86    fn default() -> Self {
87        Self::new()
88    }
89}
90
91#[cfg(feature = "jieba-rs")]
92impl JiebaSegmenter {
93    pub fn new() -> Self {
94        Self {
95            jieba: jieba_rs::Jieba::new(),
96        }
97    }
98}
99
100#[cfg(feature = "jieba-rs")]
101impl Segmenter for JiebaSegmenter {
102    fn segment(&self, text: &str) -> Box<dyn Iterator<Item = String> + '_> {
103        let tokens: Vec<String> = self
104            .jieba
105            .cut(text, false)
106            .into_iter()
107            .map(String::from)
108            .collect();
109        Box::new(tokens.into_iter())
110    }
111
112    fn name(&self) -> &'static str {
113        "jieba"
114    }
115}
116
117/// Global segmenter instance (initialized once).
118static SEGMENTER: std::sync::OnceLock<Box<dyn Segmenter>> = std::sync::OnceLock::new();
119
120/// Initialize the global segmenter. Call once at startup.
121/// If no feature is enabled, falls back to BigramFirstCharSegmenter.
122pub fn init_segmenter() -> &'static dyn Segmenter {
123    SEGMENTER.get_or_init(|| {
124        #[cfg(feature = "jieba-rs")]
125        {
126            return Box::new(JiebaSegmenter::new()) as Box<dyn Segmenter>;
127        }
128        #[allow(unreachable_code)]
129        Box::new(BigramFirstCharSegmenter)
130    })
131}
132
133/// Get the current segmenter (initializes if needed).
134pub fn segmenter() -> &'static dyn Segmenter {
135    init_segmenter()
136}
137
138/// Scripts written without spaces between words, indexed as characters or
139/// bigrams. Returns 1 for bigram-unit scripts (Han, kana, Hangul), 2 for
140/// character-unit scripts (Thai, Lao, Khmer, Myanmar).
141fn dense_script(c: char) -> Option<u8> {
142    match c as u32 {
143        0x0E00..=0x0E7F | // Thai
144        0x0E80..=0x0EFF | // Lao
145        0x1000..=0x109F | // Myanmar
146        0x1780..=0x17FF   // Khmer
147            => Some(2),
148        0x2E80..=0x2FFF |   // CJK radicals, Kangxi
149        0x3000..=0x303F |   // CJK symbols and punctuation
150        0x3040..=0x30FF |   // Hiragana + Katakana
151        0x3400..=0x4DBF |   // CJK Extension A
152        0x4E00..=0x9FFF |   // CJK Unified Ideographs
153        0xAC00..=0xD7AF |   // Hangul syllables
154        0xF900..=0xFAFF |   // CJK Compatibility Ideographs
155        0x20000..=0x2FA1F   // CJK Extensions B–F, compatibility supplement
156            => Some(1),
157        _ => None,
158    }
159}
160
161/// True when `c` belongs to a script indexed without spaces.
162pub fn is_dense_script(c: char) -> bool {
163    dense_script(c).is_some()
164}
165
166/// True when a query is long enough to be worth running.
167///
168/// Latin-script queries need three characters, but `検索` is a complete and
169/// common word, so any query containing a dense-script character is allowed at
170/// one character. This is a property of the script, not a language guess.
171pub fn is_searchable_query(query: &str) -> bool {
172    let mut chars = query.chars().filter(|c| !c.is_whitespace());
173    match chars.next() {
174        None => false,
175        Some(c) if is_dense_script(c) => true,
176        Some(_) => query.chars().filter(|c| !c.is_whitespace()).count() >= 3,
177    }
178}
179
180/// Collect bigram+first-char tokens for the default segmenter.
181///
182/// This replicates the original `fts_segment` behavior: only adds token
183/// boundaries for dense scripts (CJK, Thai, etc.), leaves Latin/other text
184/// as whole words.
185fn collect_bigram_first_char(text: &str) -> Vec<String> {
186    let normalised: String = text.nfkc().collect();
187    let mut tokens = Vec::new();
188    let mut run: Vec<char> = Vec::new();
189    let mut word: String = String::new(); // Accumulate non-dense-script words
190
191    fn flush_run(run: &mut Vec<char>, tokens: &mut Vec<String>) {
192        if run.is_empty() {
193            return;
194        }
195        if let Some(kind) = run.first().and_then(|c| dense_script(*c)) {
196            match kind {
197                2 => {
198                    // Character-unit scripts (Thai, Lao, Khmer, Myanmar): one token per char
199                    for c in run.iter() {
200                        tokens.push(c.to_string());
201                    }
202                }
203                _ => {
204                    // Bigram-unit scripts (CJK): first char, then overlapping bigrams
205                    if let Some(first) = run.first() {
206                        tokens.push(first.to_string());
207                    }
208                    for pair in run.windows(2) {
209                        let mut s = String::new();
210                        s.push(pair[0]);
211                        s.push(pair[1]);
212                        tokens.push(s);
213                    }
214                }
215            }
216        }
217        run.clear();
218    }
219
220    for c in normalised.chars() {
221        if dense_script(c).is_some() {
222            // Dense script character: flush any pending word first
223            if !word.is_empty() {
224                tokens.push(std::mem::take(&mut word));
225            }
226            // Accumulate dense script characters into run
227            run.push(c);
228        } else {
229            // Non-dense character: flush any dense-script run
230            flush_run(&mut run, &mut tokens);
231            if c.is_whitespace() {
232                // Whitespace separates words but is not emitted as a token
233                if !word.is_empty() {
234                    tokens.push(std::mem::take(&mut word));
235                }
236            } else {
237                // Part of a word
238                word.push(c);
239            }
240        }
241    }
242    if !word.is_empty() {
243        tokens.push(std::mem::take(&mut word));
244    }
245    flush_run(&mut run, &mut tokens);
246    tokens
247}
248
249/// Detect the primary language/script of the text for ICU segmentation.
250///
251/// Returns an ICU locale code (e.g., "zh", "ja", "ko", "th", "lo", "km", "my",
252/// "ar", "he", "hi") based on the dominant script in the text.
253/// Returns None if no supported dense script is detected.
254pub fn detect_language(text: &str) -> Option<&'static str> {
255    // Count characters per script to find the dominant one
256    let mut script_counts: std::collections::HashMap<&'static str, usize> =
257        std::collections::HashMap::new();
258
259    for c in text.chars() {
260        let script = match c as u32 {
261            // Chinese (Han)
262            0x2E80..=0x2FFF |   // CJK radicals, Kangxi
263            0x3000..=0x303F |   // CJK symbols and punctuation
264            0x3400..=0x4DBF |   // CJK Extension A
265            0x4E00..=0x9FFF |   // CJK Unified Ideographs
266            0xF900..=0xFAFF |   // CJK Compatibility Ideographs
267            0x20000..=0x2FA1F   // CJK Extensions B–F, compatibility supplement
268                => "zh",
269            // Japanese (Hiragana + Katakana)
270            0x3040..=0x30FF
271                => "ja",
272            // Korean (Hangul)
273            0xAC00..=0xD7AF
274                => "ko",
275            // Thai
276            0x0E00..=0x0E7F
277                => "th",
278            // Lao
279            0x0E80..=0x0EFF
280                => "lo",
281            // Myanmar
282            0x1000..=0x109F
283                => "my",
284            // Khmer
285            0x1780..=0x17FF
286                => "km",
287            // Arabic
288            0x0600..=0x06FF |   // Arabic
289            0x0750..=0x077F |   // Arabic Supplement
290            0x08A0..=0x08FF |   // Arabic Extended-A
291            0xFB50..=0xFDFF |   // Arabic Presentation Forms-A
292            0xFE70..=0xFEFF     // Arabic Presentation Forms-B
293                => "ar",
294            // Hebrew
295            0x0590..=0x05FF
296                => "he",
297            // Devanagari
298            0x0900..=0x097F
299                => "hi",
300            _ => continue,
301        };
302        *script_counts.entry(script).or_insert(0) += 1;
303    }
304
305    // Return the script with the highest count
306    script_counts
307        .into_iter()
308        .max_by_key(|(_, count)| *count)
309        .map(|(script, _)| script)
310}
311
312/// Check if text contains Japanese characters (Hiragana or Katakana).
313#[cfg(feature = "lindera")]
314fn is_japanese(text: &str) -> bool {
315    text.chars().any(|c| {
316        let cp = c as u32;
317        (0x3040..=0x309F).contains(&cp) || // Hiragana
318        (0x30A0..=0x30FF).contains(&cp) // Katakana
319    })
320}
321
322/// Normalise text and add token boundaries for scripts `unicode61` cannot split.
323/// Uses the configured segmenter (default: bigram+first-char).
324/// For the default segmenter, uses the original logic that only adds boundaries
325/// for dense scripts (CJK, Thai, etc.) and leaves Latin/other text unchanged.
326pub fn fts_segment(text: &str) -> String {
327    // Check if we're using a non-default segmenter (ICU, Lindera, Jieba)
328    // If so, use the segmenter; otherwise use the original logic
329    let seg = segmenter();
330    match seg.name() {
331        "bigram-first-char" => {
332            // Try ICU segmenter first (covers most scripts)
333            #[cfg(feature = "icu_segmenter")]
334            if let Some(lang) = detect_language(text) {
335                return icu_segment(text, lang);
336            }
337            // Try Lindera for Japanese
338            #[cfg(feature = "lindera")]
339            if is_japanese(text) {
340                return lindera_segment(text);
341            }
342            // Fallback to original bigram logic
343            let tokens = collect_bigram_first_char(text);
344            tokens.join(" ")
345        }
346        _ => {
347            // Use the configured segmenter (Jieba, etc.)
348            let tokens = seg.segment(text);
349            tokens.collect::<Vec<_>>().join(" ")
350        }
351    }
352}
353
354/// True when two strings carry the same whitespace-separated tokens.
355///
356/// Segmentation normalises whitespace and FTS5 tokenises newlines and spaces
357/// identically, so `a\nb` and `a b` produce the same index. Comparing tokens
358/// rather than bytes is what lets the indexer skip storing a second copy of
359/// text that segmentation did not actually change.
360pub fn same_tokens(a: &str, b: &str) -> bool {
361    a.split_whitespace().eq(b.split_whitespace())
362}
363
364/// Split a query into FTS terms after segmentation (same boundaries as the index).
365pub fn query_terms(query: &str) -> Vec<String> {
366    fts_segment(query)
367        .split_whitespace()
368        .map(|t| t.to_string())
369        .collect()
370}
371
372/// Characters shown in a search-result snippet.
373pub const SNIPPET_CHARS: usize = 240;
374
375/// A verbatim window of `text` around the first query term it contains.
376pub fn excerpt(text: &str, terms: &[String], max_chars: usize) -> String {
377    let collapsed = collapse_whitespace(text);
378    let chars: Vec<char> = collapsed.chars().collect();
379    if chars.len() <= max_chars {
380        return collapsed;
381    }
382
383    let lower: Vec<char> = chars
384        .iter()
385        .map(|c| c.to_lowercase().next().unwrap_or(*c))
386        .collect();
387    let mut hit: Option<usize> = None;
388    for term in terms {
389        let needle: Vec<char> = term
390            .chars()
391            .map(|c| c.to_lowercase().next().unwrap_or(c))
392            .collect();
393        if needle.is_empty() {
394            continue;
395        }
396        if let Some(pos) = lower
397            .windows(needle.len())
398            .position(|window| window == needle.as_slice())
399        {
400            hit = Some(hit.map_or(pos, |best: usize| best.min(pos)));
401        }
402    }
403
404    let start = hit
405        .map(|pos| pos.saturating_sub(max_chars / 3))
406        .unwrap_or(0);
407    let end = (start + max_chars).min(chars.len());
408    let mut out: String = chars[start..end].iter().collect();
409    if start > 0 {
410        out.insert(0, '…');
411    }
412    if end < chars.len() {
413        out.push('…');
414    }
415    out
416}
417
418fn collapse_whitespace(text: &str) -> String {
419    let mut out = String::with_capacity(text.len());
420    let mut prev_space = false;
421    for c in text.chars() {
422        if c.is_whitespace() {
423            if !prev_space {
424                out.push(' ');
425            }
426            prev_space = true;
427        } else {
428            out.push(c);
429            prev_space = false;
430        }
431    }
432    out.trim().to_string()
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    /// Bigram fallback only applies when the ICU feature is off.
440    #[cfg(not(feature = "icu_segmenter"))]
441    #[test]
442    fn cjk_runs_become_bigrams() {
443        let s = fts_segment("全文檢索");
444        let tokens: Vec<&str> = s.split_whitespace().collect();
445        assert_eq!(tokens, ["全", "全文", "文檢", "檢索"]);
446    }
447
448    /// With ICU, CJK text is segmented into words instead of bigrams.
449    #[cfg(feature = "icu_segmenter")]
450    #[test]
451    fn cjk_runs_become_words() {
452        let s = fts_segment("全文檢索");
453        let tokens: Vec<&str> = s.split_whitespace().collect();
454        assert!(tokens.contains(&"檢索"), "{tokens:?}");
455        assert!(
456            !tokens.contains(&"文檢"),
457            "no cross-word bigrams under ICU: {tokens:?}"
458        );
459    }
460
461    #[test]
462    fn two_character_words_survive() {
463        let doc = fts_segment("南投縣魚池鄉");
464        let query = fts_segment("魚池");
465        let query_tokens: Vec<&str> = query.split_whitespace().collect();
466        let doc_tokens: Vec<&str> = doc.split_whitespace().collect();
467        assert!(
468            query_tokens.iter().any(|qt| doc_tokens.contains(qt)),
469            "query tokens: {:?}, doc tokens: {:?}",
470            query_tokens,
471            doc_tokens
472        );
473    }
474
475    #[test]
476    fn leaves_latin_alone() {
477        assert_eq!(fts_segment("fridge warranty 2027"), "fridge warranty 2027");
478    }
479
480    #[test]
481    fn normalises_full_width() {
482        assert_eq!(fts_segment("WARRANTY"), "WARRANTY");
483    }
484
485    /// Per-character fallback only applies when the ICU feature is off.
486    #[cfg(not(feature = "icu_segmenter"))]
487    #[test]
488    fn thai_is_indexed_per_character() {
489        let s = fts_segment("การรับประกัน");
490        assert!(s.split_whitespace().count() > 3, "{s}");
491    }
492
493    /// With ICU, Thai is segmented at dictionary word boundaries.
494    #[cfg(feature = "icu_segmenter")]
495    #[test]
496    fn thai_is_indexed_per_word() {
497        let s = fts_segment("การรับประกัน");
498        let tokens: Vec<&str> = s.split_whitespace().collect();
499        assert!(tokens.contains(&"การ"), "{tokens:?}");
500        assert!(tokens.contains(&"รับประกัน"), "{tokens:?}");
501    }
502
503    #[test]
504    fn short_dense_queries_are_searchable() {
505        assert!(is_searchable_query("検索"));
506        assert!(is_searchable_query("法"));
507        assert!(!is_searchable_query("ab"));
508        assert!(!is_searchable_query("   "));
509        assert!(is_searchable_query("tax"));
510    }
511
512    #[test]
513    fn excerpt_is_a_verbatim_window() {
514        let text = "alpha beta gamma delta epsilon zeta eta theta";
515        let out = excerpt(text, &["delta".to_string()], 24);
516        assert!(out.contains("delta"), "{out}");
517        assert!(text.contains(out.trim_matches('…')), "{out}");
518    }
519
520    #[test]
521    fn excerpt_leaves_short_text_whole() {
522        assert_eq!(
523            excerpt("fridge warranty", &["warranty".to_string()], 240),
524            "fridge warranty"
525        );
526    }
527
528    #[test]
529    fn segmenter_name_default() {
530        assert_eq!(segmenter().name(), "bigram-first-char");
531    }
532}