use std::collections::HashMap;
#[inline]
pub fn is_cjk_char(c: char) -> bool {
matches!(c,
'\u{3040}'..='\u{309F}' | '\u{30A0}'..='\u{30FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{AC00}'..='\u{D7AF}' | '\u{20000}'..='\u{2A6DF}' )
}
pub fn contains_cjk(text: &str) -> bool {
let (cjk_count, char_count) = cjk_counts(text);
if char_count == 0 {
return false;
}
(cjk_count as f64 / char_count as f64) > 0.15
}
pub fn contains_cjk_f32(text: &str) -> bool {
let (cjk_count, char_count) = cjk_counts(text);
if char_count == 0 {
return false;
}
(cjk_count as f32 / char_count as f32) > 0.15
}
fn cjk_counts(text: &str) -> (usize, usize) {
text.chars().fold((0, 0), |(cjk, total), ch| {
(cjk + usize::from(is_cjk_char(ch)), total + 1)
})
}
#[derive(Debug, Clone, PartialEq)]
pub struct ScriptProfile {
pub cjk_fraction: f64,
pub latin_fraction: f64,
pub char_count: usize,
}
impl ScriptProfile {
pub fn analyze(text: &str) -> Self {
let (cjk, n) = cjk_counts(text);
if n == 0 {
return Self {
cjk_fraction: 0.0,
latin_fraction: 0.0,
char_count: 0,
};
}
let latin = text.chars().filter(|c| c.is_ascii_alphabetic()).count();
Self {
cjk_fraction: cjk as f64 / n as f64,
latin_fraction: latin as f64 / n as f64,
char_count: n,
}
}
pub fn is_cjk_dominant(&self) -> bool {
self.cjk_fraction > 0.15
}
}
pub fn is_meaningful_text_query(query: &str) -> bool {
let trimmed = query.trim();
if trimmed.is_empty() {
return false;
}
let non_ws: Vec<char> = trimmed.chars().filter(|c| !c.is_whitespace()).collect();
if non_ws.is_empty() {
return false;
}
if !non_ws.iter().any(|c| c.is_alphanumeric()) {
return false;
}
if non_ws.len() == 1 && non_ws[0].is_ascii_alphabetic() {
return false;
}
let total = non_ws.len();
if total > 1 {
let mut counts: HashMap<char, usize> = HashMap::new();
for c in &non_ws {
*counts.entry(*c).or_insert(0) += 1;
}
if let Some(&max_count) = counts.values().max() {
if max_count as f64 / total as f64 > 0.80 {
return false;
}
}
}
true
}
#[deprecated(note = "use is_meaningful_text_query")]
pub fn is_meaningful_query(query: &str) -> bool {
is_meaningful_text_query(query)
}
#[cfg(test)]
#[path = "lang/tests.rs"]
mod tests;