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