use std::collections::HashSet;
use std::sync::LazyLock;
use super::words::{CHAT_WORDS, CLOSED_WORDS, DAY_GROUPS, DAYS, FUNCTION_WORDS, NUMBER_WORDS, RANGE_WORDS};
const ANSWER_WORDS: &[&str] = &[
"yes",
"yeah",
"yep",
"sure",
"certainly",
"absolutely",
"indeed",
"correct",
"no",
"not",
"nope",
"don",
"doesn",
"didn",
"never",
"cannot",
"ya",
"iya",
"betul",
"benar",
"tentu",
"tidak",
"nggak",
"gak",
"enggak",
"bukan",
"belum",
"tak",
];
pub(super) fn words(text: &str) -> Vec<String> {
let mut words = Vec::new();
let mut word = String::new();
for character in text.chars() {
if character.is_alphanumeric() {
word.extend(character.to_lowercase());
continue;
}
if !word.is_empty() {
words.push(std::mem::take(&mut word));
}
if matches!(character, '-' | '–' | '—') {
words.push("-".to_owned());
}
}
if !word.is_empty() {
words.push(word);
}
words
}
pub(super) fn stems(word: &str) -> Vec<String> {
let mut roots = vec![word.to_owned()];
const PREFIXES: &[(&str, &str)] = &[
("meng", "k"),
("meny", "s"),
("mem", "p"),
("men", "t"),
("me", ""),
("peng", "k"),
("peny", "s"),
("pem", "p"),
("pen", "t"),
("pe", ""),
("ber", ""),
("ter", ""),
("di", ""),
("ke", ""),
];
for (prefix, eaten) in PREFIXES {
if let Some(rest) = word.strip_prefix(prefix)
&& rest.chars().count() >= 4
{
roots = vec![rest.to_owned()];
if !eaten.is_empty() && rest.starts_with(['a', 'e', 'i', 'o', 'u']) {
roots.push(format!("{eaten}{rest}"));
}
break;
}
}
roots
.into_iter()
.map(|mut root| {
for _ in 0..2 {
let ending = ["nya", "kan", "an", "ing", "ies", "es", "ed", "ly", "s", "i"]
.into_iter()
.find(|suffix| root.strip_suffix(suffix).is_some_and(|rest| rest.chars().count() >= 4));
match ending {
Some(suffix) => root.truncate(root.len() - suffix.len()),
None => break,
}
}
root.chars().take(5).collect()
})
.collect()
}
fn is_number_like(word: &str) -> bool {
word.chars().any(|c| c.is_ascii_digit())
}
static FUNCTION: LazyLock<HashSet<&'static str>> = LazyLock::new(|| FUNCTION_WORDS.split_whitespace().collect());
static CHAT: LazyLock<HashSet<&'static str>> = LazyLock::new(|| CHAT_WORDS.split_whitespace().collect());
static CHAT_STEMS: LazyLock<HashSet<String>> = LazyLock::new(|| CHAT.iter().flat_map(|word| stems(word)).collect());
pub(super) fn says_nothing(word: &str) -> bool {
word == "-"
|| word.chars().count() < 3
|| is_number_like(word)
|| FUNCTION.contains(word)
|| CHAT.contains(word)
|| stems(word).iter().any(|stem| CHAT_STEMS.contains(stem))
|| day_of(word).is_some()
|| DAY_GROUPS.iter().any(|(group, _)| *group == word)
|| super::numbers::is_currency_or_multiplier(word)
|| super::numbers::is_number_word(word)
}
#[derive(Debug, Default)]
pub(super) struct KnownWords {
stems: HashSet<String>,
joined: HashSet<String>,
}
impl KnownWords {
pub(super) fn holds(&self, word: &str) -> bool {
let joined: String = word.split_whitespace().collect();
self.joined.contains(&joined) || stems(&joined).iter().any(|stem| self.stems.contains(stem))
}
pub(super) fn of(text: &str) -> Self {
let words = words(text);
let known: HashSet<String> =
words.iter().filter(|word| !says_nothing(word)).flat_map(|word| stems(word)).collect();
let mut joined = HashSet::new();
for pair in words.windows(2) {
if let [first, second] = pair
&& first != "-"
&& second != "-"
{
joined.insert(format!("{first}{second}"));
}
}
for three in words.windows(3) {
if let [first, joiner, last] = three
&& joiner == "-"
{
joined.insert(format!("{first}{last}"));
}
}
Self { stems: known, joined }
}
pub(super) fn sort(&self, sentence: &str) -> (Vec<String>, Vec<String>) {
let mut held = Vec::new();
let mut novel = Vec::new();
let words = words(sentence);
let knows = |word: &str| self.joined.contains(word) || stems(word).iter().any(|stem| self.stems.contains(stem));
let mut index = 0;
while let Some(word) = words.get(index) {
index += 1;
if says_nothing(word) {
continue;
}
let next = words.get(index).filter(|next| *next != "-");
let (written, is_known) = match next {
Some(next) if !knows(word) && knows(&format!("{word}{next}")) => {
index += 1;
(format!("{word} {next}"), true)
}
_ => (word.clone(), knows(word)),
};
let list = if is_known { &mut held } else { &mut novel };
if !list.contains(&written) {
list.push(written);
}
}
(held, novel)
}
}
const UNKNOWN_PHRASES: &[&[&str]] = &[
&["not", "sure"],
&["unsure"],
&["not", "certain"],
&["don", "t", "know"],
&["do", "not", "know"],
&["don", "t", "have", "information"],
&["don", "t", "have", "that", "information"],
&["don", "t", "have", "any", "information"],
&["don", "t", "have", "info"],
&["don", "t", "have", "details"],
&["do", "not", "have", "information"],
&["do", "not", "have", "that", "information"],
&["do", "not", "have", "any", "information"],
&["no", "information"],
&["no", "details"],
&["not", "mentioned"],
&["not", "mention"],
&["doesn", "t", "mention"],
&["does", "not", "mention"],
&["can", "t", "find"],
&["cannot", "find"],
&["couldn", "t", "find"],
&["unable", "to", "find"],
&["tidak", "tahu"],
&["kurang", "tahu"],
&["belum", "tahu"],
&["tidak", "yakin"],
&["kurang", "yakin"],
&["belum", "punya", "info"],
&["belum", "punya", "informasi"],
&["tidak", "punya", "info"],
&["tidak", "punya", "informasi"],
&["tidak", "memiliki", "info"],
&["tidak", "memiliki", "informasi"],
&["belum", "memiliki", "info"],
&["belum", "memiliki", "informasi"],
&["tidak", "ada", "informasi"],
&["tidak", "ada", "info"],
&["belum", "ada", "informasi"],
&["belum", "ada", "info"],
&["tidak", "disebutkan"],
&["tidak", "terdapat"],
&["informasi", "tidak", "tersedia"],
&["info", "tidak", "tersedia"],
&["owner", "will"],
&["front", "desk", "will"],
&["will", "reply", "soon"],
&["will", "get", "back"],
&["hand", "you", "over"],
&["hand", "this", "over"],
&["pass", "your", "question"],
&["pass", "this", "question"],
&["pemilik", "akan"],
&["admin", "akan"],
&["akan", "segera", "membalas"],
&["akan", "segera", "menjawab"],
&["serahkan", "pertanyaan"],
&["teruskan", "pertanyaan"],
&["meneruskan", "pertanyaan"],
];
pub(super) fn admits_unknown(sentence: &str) -> bool {
let words = words(sentence);
UNKNOWN_PHRASES
.iter()
.any(|phrase| words.windows(phrase.len()).any(|run| run.iter().zip(*phrase).all(|(w, p)| w == p)))
}
pub(super) fn answers_yes_or_no(sentence: &str) -> bool {
words(sentence).iter().any(|word| ANSWER_WORDS.contains(&word.as_str()))
}
fn day_of(word: &str) -> Option<usize> {
let find = |word: &str| DAYS.iter().position(|names| names.contains(&word));
find(word).or_else(|| word.strip_suffix('s').and_then(find))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DayMention {
day: usize,
closed: bool,
}
fn day_mentions(text: &str) -> Vec<(DayMention, String)> {
let words = words(text);
let mut mentions = Vec::new();
let mut index = 0;
while let Some(word) = words.get(index) {
let start = index;
let previous_is_number = index
.checked_sub(1)
.and_then(|before| words.get(before))
.is_some_and(|before| is_number_like(before) || NUMBER_WORDS.contains(&before.as_str()));
let days: Vec<usize> = match (day_of(word), DAY_GROUPS.iter().find(|(group, _)| group == word)) {
(Some(_), _) if previous_is_number => Vec::new(),
(Some(first), _) => {
let last = words
.get(index + 1)
.filter(|joiner| RANGE_WORDS.contains(&joiner.as_str()))
.and_then(|_| words.get(index + 2))
.and_then(|next| day_of(next));
match last {
Some(last) => {
index += 2;
let span = (last + 7 - first) % 7;
(0..=span).map(|step| (first + step) % 7).collect()
}
None => vec![first],
}
}
(None, Some((_, group))) => group.to_vec(),
(None, None) => Vec::new(),
};
if !days.is_empty() {
let before = words.get(start.saturating_sub(3)..start).unwrap_or_default();
let after = words.get(index + 1..(index + 3).min(words.len())).unwrap_or_default();
let closed = before.iter().chain(after).any(|word| CLOSED_WORDS.contains(&word.as_str()));
for day in days {
mentions.push((DayMention { day, closed }, word.clone()));
}
}
index += 1;
}
mentions
}
#[derive(Debug, Default)]
pub(super) struct KnownDays {
open: u8,
closed: u8,
}
fn bit(day: usize) -> u8 {
u8::try_from(day % 7).map(|day| 1 << day).unwrap_or(0)
}
const EVERY_DAY: u8 = 0b111_1111;
impl KnownDays {
pub(super) fn of(text: &str) -> Self {
let mut known = Self::default();
for (mention, _) in day_mentions(text) {
if mention.closed {
known.closed |= bit(mention.day);
} else {
known.open |= bit(mention.day);
}
}
known.open &= !known.closed;
if known.open == 0 && known.closed != 0 {
known.open = EVERY_DAY & !known.closed;
}
known
}
fn holds(&self, mention: DayMention) -> bool {
let day = bit(mention.day);
if mention.closed {
self.closed & day != 0 || (self.open != 0 && self.open & day == 0)
} else {
self.open & day != 0
}
}
pub(super) fn check(&self, sentence: &str) -> (Option<String>, bool) {
let mut repeats = false;
for (mention, written) in day_mentions(sentence) {
if !self.holds(mention) {
return (Some(written), repeats);
}
repeats = true;
}
(None, repeats)
}
}
fn addresses(text: &str) -> Vec<String> {
text.split_whitespace()
.map(|word| {
word.trim_matches(|c: char| matches!(c, '.' | ',' | '!' | '?' | ')' | '(' | '"' | '\'' | ':' | ';'))
})
.filter(|word| {
let lower = word.to_lowercase();
lower.starts_with("http") || lower.starts_with("www.") || word.contains('@')
})
.map(str::to_lowercase)
.collect()
}
#[derive(Debug, Default)]
pub(super) struct KnownAddresses {
text: String,
}
impl KnownAddresses {
pub(super) fn of(text: &str) -> Self {
Self { text: text.to_lowercase() }
}
pub(super) fn first_unknown(&self, sentence: &str) -> Option<String> {
addresses(sentence).into_iter().find(|address| !self.text.contains(address.as_str()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn forms_of_a_word_share_a_stem() {
let share = |left: &str, right: &str| stems(left).iter().any(|stem| stems(right).contains(stem));
assert!(share("delivery", "deliver"));
assert!(share("delivers", "delivered"));
assert!(share("pengiriman", "pengirimannya"));
assert!(share("dikirim", "kirim"));
assert!(share("pengiriman", "kirim"));
assert!(share("menulis", "tulis"));
assert!(!share("parking", "pickup"));
}
#[test]
fn words_the_sources_do_not_hold_are_novel() {
let known = KnownWords::of("Laundry: 8k per kg, express 15k per kg, pickup between 9 and 18.");
let (held, novel) = known.sort("Yes, we offer free delivery for express laundry.");
assert_eq!(held, ["express", "laundry"]);
assert_eq!(novel, ["free", "delivery"]);
let (held, novel) = known.sort("Thank you for asking! Our express laundry service costs 15k per kilogram.");
assert_eq!(held, ["express", "laundry"]);
assert!(novel.is_empty(), "{novel:?}");
let (_, novel) =
KnownWords::of("nasi box 25k, tumpeng 350k").sort("Harga nasi box kami adalah 25.000 per box.");
assert!(novel.is_empty(), "{novel:?}");
}
#[test]
fn a_joined_pair_of_the_facts_is_no_stem() {
let (_, novel) =
KnownWords::of("our catering menu (nasi box 25k)").sort("Kami hanya menerima pembayaran tunai.");
assert_eq!(novel, ["tunai"]);
let (held, _) = KnownWords::of("free pick-up").sort("Pickup is free.");
assert_eq!(held, ["pickup", "free"]);
}
#[test]
fn open_and_closed_days_follow_the_sources() {
let clinic = KnownDays::of("open Monday to Saturday 9-20");
assert_eq!(clinic.check("Yes, we are open on Saturday."), (None, true));
assert_eq!(clinic.check("We are open on Sundays.").0.as_deref(), Some("sundays"));
assert_eq!(clinic.check("We are closed on Sunday."), (None, true));
assert_eq!(clinic.check("Kami buka Senin sampai Sabtu."), (None, true));
let bakery = KnownDays::of("opening hours (8 to 17, closed Sunday)");
assert_eq!(bakery.check("Yes, we are open on Saturday."), (None, true));
assert!(bakery.check("We are open on Sunday mornings.").0.is_some());
assert_eq!(bakery.check("Mon-Sat we bake fresh."), (None, true));
let nothing = KnownDays::of("prices are 8k per kg");
assert!(nothing.check("We are open every weekday.").0.is_some());
assert_eq!(nothing.check("Delivery takes 2 minggu."), (None, false));
assert_eq!(nothing.check("Pembayaran dalam dua minggu."), (None, false));
}
#[test]
fn addresses_must_be_written_in_the_sources() {
let known = KnownAddresses::of("Order at https://kue.example/order or mail halo@kue.example");
assert_eq!(known.first_unknown("Order at https://kue.example/order."), None);
assert_eq!(known.first_unknown("Write to sales@kue.example!").as_deref(), Some("sales@kue.example"));
assert_eq!(known.first_unknown("Follow @kue_official").as_deref(), Some("@kue_official"));
}
#[test]
fn a_yes_or_a_no_is_an_answer() {
assert!(answers_yes_or_no("Yes, we do."));
assert!(answers_yes_or_no("Tidak, kami tidak menyediakan itu."));
assert!(!answers_yes_or_no("Our cheesecake costs 120k."));
}
}