Skip to main content

khive_text/
lang.rs

1//! Script/alphabet identification for per-language routing decisions.
2
3use std::collections::HashMap;
4
5/// Return whether `c` is in a supported CJK, Hiragana, Katakana, or Hangul block, or is one of
6/// the three ideographic letters of the CJK Symbols and Punctuation block.
7///
8/// See `crates/khive-text/docs/api/identifier-and-script.md`.
9#[inline]
10pub fn is_cjk_char(c: char) -> bool {
11    matches!(c,
12        '\u{3005}'..='\u{3007}'     // 々 iteration mark, 〆 closing mark, 〇 ideographic zero
13        | '\u{3040}'..='\u{309F}'   // Hiragana
14        | '\u{30A0}'..='\u{30FF}'   // Katakana
15        | '\u{3400}'..='\u{4DBF}'   // CJK Extension A
16        | '\u{4E00}'..='\u{9FFF}'   // CJK Unified Ideographs
17        | '\u{F900}'..='\u{FAFF}'   // CJK Compatibility Ideographs
18        | '\u{AC00}'..='\u{D7AF}'   // Hangul Syllables
19        | '\u{20000}'..='\u{2A6DF}' // CJK Extension B
20    )
21}
22
23/// Return whether strictly more than 15% of `text` characters are CJK.
24pub fn contains_cjk(text: &str) -> bool {
25    let (cjk_count, char_count) = cjk_counts(text);
26    if char_count == 0 {
27        return false;
28    }
29    (cjk_count as f64 / char_count as f64) > 0.15
30}
31
32/// The 15% classifier using `f32` arithmetic for existing memory routing behavior.
33/// Near the boundary it can differ from [`contains_cjk`], which uses `f64`.
34pub fn contains_cjk_f32(text: &str) -> bool {
35    let (cjk_count, char_count) = cjk_counts(text);
36    if char_count == 0 {
37        return false;
38    }
39    (cjk_count as f32 / char_count as f32) > 0.15
40}
41
42fn cjk_counts(text: &str) -> (usize, usize) {
43    text.chars().fold((0, 0), |(cjk, total), ch| {
44        (cjk + usize::from(is_cjk_char(ch)), total + 1)
45    })
46}
47
48/// Character-count profile containing CJK and ASCII-letter fractions.
49///
50/// See `crates/khive-text/docs/api/identifier-and-script.md`.
51#[derive(Debug, Clone, PartialEq)]
52pub struct ScriptProfile {
53    /// Fraction of characters that are CJK (0.0-1.0).
54    pub cjk_fraction: f64,
55    /// Fraction of characters that are ASCII letters (0.0-1.0).
56    pub latin_fraction: f64,
57    /// Total character count (not byte count).
58    pub char_count: usize,
59}
60
61impl ScriptProfile {
62    /// Analyze `text` and return a ScriptProfile.
63    pub fn analyze(text: &str) -> Self {
64        let (cjk, n) = cjk_counts(text);
65        if n == 0 {
66            return Self {
67                cjk_fraction: 0.0,
68                latin_fraction: 0.0,
69                char_count: 0,
70            };
71        }
72        let latin = text.chars().filter(|c| c.is_ascii_alphabetic()).count();
73        Self {
74            cjk_fraction: cjk as f64 / n as f64,
75            latin_fraction: latin as f64 / n as f64,
76            char_count: n,
77        }
78    }
79
80    /// True when CJK fraction exceeds 15%.
81    pub fn is_cjk_dominant(&self) -> bool {
82        self.cjk_fraction > 0.15
83    }
84}
85
86/// Returns true when `query` is worth sending to a retrieval backend.
87/// Rejects empty, symbol-only, single ASCII letter, and repeated-char (>80%) gibberish.
88///
89/// See `crates/khive-text/docs/api/identifier-and-script.md`.
90pub fn is_meaningful_text_query(query: &str) -> bool {
91    let trimmed = query.trim();
92    if trimmed.is_empty() {
93        return false;
94    }
95
96    let non_ws: Vec<char> = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
97    if non_ws.is_empty() {
98        return false;
99    }
100
101    // Symbol/punctuation/emoji-only queries are not meaningful, including Unicode symbols.
102    if !non_ws.iter().any(|c| c.is_alphanumeric()) {
103        return false;
104    }
105
106    // Single ASCII letter
107    if non_ws.len() == 1 && non_ws[0].is_ascii_alphabetic() {
108        return false;
109    }
110
111    // Repeated-char gibberish: dominant char > 80% of non-ws chars.
112    // Skip when total == 1 — a single character cannot exhibit gibberish repetition.
113    let total = non_ws.len();
114    if total > 1 {
115        let mut counts: HashMap<char, usize> = HashMap::new();
116        for c in &non_ws {
117            *counts.entry(*c).or_insert(0) += 1;
118        }
119        if let Some(&max_count) = counts.values().max() {
120            if max_count as f64 / total as f64 > 0.80 {
121                return false;
122            }
123        }
124    }
125
126    true
127}
128
129/// Deprecated name for [`is_meaningful_text_query`].
130#[deprecated(note = "use is_meaningful_text_query")]
131pub fn is_meaningful_query(query: &str) -> bool {
132    is_meaningful_text_query(query)
133}
134
135#[cfg(test)]
136#[path = "lang/tests.rs"]
137mod tests;