mod attribution;
mod claims;
mod numbers;
mod words;
use std::fmt;
use attribution::Attributions;
use claims::{KnownAddresses, KnownDays, KnownWords};
use numbers::KnownNumbers;
#[cfg(feature = "jinja")]
pub(crate) use numbers::grounded as grounded_numbers;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Sources {
facts: Vec<String>,
customer: Vec<String>,
}
impl Sources {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn fact(mut self, text: impl Into<String>) -> Self {
self.add_fact(text);
self
}
#[must_use]
pub fn customer(mut self, text: impl Into<String>) -> Self {
self.add_customer(text);
self
}
pub fn add_fact(&mut self, text: impl Into<String>) {
let text = text.into();
if !text.trim().is_empty() {
self.facts.push(text);
}
}
pub fn add_customer(&mut self, text: impl Into<String>) {
let text = text.into();
if !text.trim().is_empty() {
self.customer.push(text);
}
}
pub fn facts_text(&self) -> String {
self.facts.join("\n")
}
pub fn customer_text(&self) -> String {
self.customer.join("\n")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Reason {
Number(String),
Attribution { number: String, word: String },
Day(String),
Address(String),
Words(Vec<String>),
Premise(Vec<String>),
Answer,
}
impl Reason {
pub fn may_be_confirmed(&self) -> bool {
matches!(self, Self::Words(_) | Self::Answer)
}
}
impl fmt::Display for Reason {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Number(number) => write!(formatter, "the number {number} is not in the sources"),
Self::Attribution { number, word } => {
write!(formatter, "the sources give {number} to something else than {word}")
}
Self::Day(day) => write!(formatter, "the day {day} is not in the facts"),
Self::Address(address) => write!(formatter, "{address} is not in the facts"),
Self::Words(words) => write!(formatter, "not in the facts: {}", words.join(", ")),
Self::Premise(words) => write!(formatter, "only the customer wrote: {}", words.join(", ")),
Self::Answer => formatter.write_str("a yes or no the facts do not hold"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Verdict {
Supported,
NoClaim,
Unknown,
Unsupported(Reason),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sentence {
pub text: String,
gap: String,
pub verdict: Verdict,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsupported {
pub sentence: String,
pub reason: Reason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checked {
pub text: Option<String>,
pub unsupported: Vec<Unsupported>,
pub admits_unknown: bool,
}
impl Checked {
pub fn is_whole(&self) -> bool {
self.text.is_some() && self.unsupported.is_empty()
}
}
#[derive(Debug)]
pub struct Review {
sentences: Vec<Sentence>,
numbers: KnownNumbers,
}
impl Review {
pub fn of(reply: &str, sources: &Sources) -> Self {
let facts = sources.facts_text();
let numbers = KnownNumbers::with_customer(&facts, &sources.customer_text());
let known = Known {
numbers: &numbers,
attributions: Attributions::of(&facts, &sources.customer_text()),
words: KnownWords::of(&facts),
customer_words: KnownWords::of(&sources.customer_text()),
days: KnownDays::of(&facts),
addresses: KnownAddresses::of(&facts),
};
let sentences = split_sentences(reply)
.into_iter()
.map(|(text, gap)| {
let verdict = known.verdict(&text);
Sentence { text, gap, verdict }
})
.collect();
Self { sentences, numbers }
}
pub fn sentences(&self) -> &[Sentence] {
&self.sentences
}
pub fn to_verify(&self) -> Vec<(usize, &str)> {
self.sentences
.iter()
.enumerate()
.filter(
|(_, sentence)| matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed()),
)
.map(|(index, sentence)| (index, sentence.text.as_str()))
.collect()
}
pub fn confirm(&mut self, index: usize) {
if let Some(sentence) = self.sentences.get_mut(index)
&& matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed())
{
sentence.verdict = Verdict::Supported;
}
}
pub fn finish(self) -> Checked {
let mut kept = String::new();
let mut unsupported = Vec::new();
let mut holds_a_fact = false;
let mut admits_unknown = false;
for sentence in self.sentences {
match sentence.verdict {
Verdict::Unsupported(reason) => unsupported.push(Unsupported { sentence: sentence.text, reason }),
verdict => {
holds_a_fact |= verdict == Verdict::Supported;
admits_unknown |= verdict == Verdict::Unknown;
kept.push_str(&sentence.text);
kept.push_str(&sentence.gap);
}
}
}
let sendable = holds_a_fact || (unsupported.is_empty() && !admits_unknown);
let text = self.numbers.without_unknown_currencies(kept.trim());
Checked { text: (sendable && !text.is_empty()).then_some(text), unsupported, admits_unknown }
}
}
pub fn fact_sentences(sources: &Sources) -> Vec<String> {
sources.facts.iter().flat_map(|fact| split_sentences(&unwrapped(fact))).map(|(text, _)| text).collect()
}
fn unwrapped(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut lines = text.lines().peekable();
while let Some(line) = lines.next() {
out.push_str(line);
let Some(next) = lines.peek() else { break };
let ends = line.trim_end().ends_with(['.', '!', '?', ':', ';']) || line.trim().is_empty();
let starts = next
.trim_start()
.starts_with(|c: char| c.is_uppercase() || c.is_ascii_digit() || matches!(c, '-' | '*' | '•'));
out.push(if ends || starts { '\n' } else { ' ' });
}
out
}
pub fn shares_a_fact(sentence: &str, fact: &str) -> bool {
let words = KnownWords::of(fact);
let (held, _) = words.sort(sentence);
!held.is_empty() || KnownNumbers::of(fact).repeats_one(sentence)
}
pub fn check(reply: &str, sources: &Sources) -> Checked {
Review::of(reply, sources).finish()
}
struct Known<'a> {
numbers: &'a KnownNumbers,
attributions: Attributions,
words: KnownWords,
customer_words: KnownWords,
days: KnownDays,
addresses: KnownAddresses,
}
impl Known<'_> {
fn verdict(&self, sentence: &str) -> Verdict {
if let Some(address) = self.addresses.first_unknown(sentence) {
return Verdict::Unsupported(Reason::Address(address));
}
if let Some(number) = self.numbers.first_unknown(sentence) {
return Verdict::Unsupported(Reason::Number(number));
}
if let Some((number, word)) = self.attributions.first_misattributed(sentence) {
return Verdict::Unsupported(Reason::Attribution { number, word });
}
let (unknown_day, repeats_a_day) = self.days.check(sentence);
if let Some(day) = unknown_day {
return Verdict::Unsupported(Reason::Day(day));
}
let (held, novel) = self.words.sort(sentence);
let states_facts_only = novel.is_empty() && !held.is_empty();
if !states_facts_only
&& claims::admits_unknown(sentence)
&& novel.iter().all(|word| self.customer_words.holds(word))
{
return Verdict::Unknown;
}
if !novel.is_empty() {
let premise: Vec<String> = novel.iter().filter(|word| self.customer_words.holds(word)).cloned().collect();
if !premise.is_empty() {
return Verdict::Unsupported(Reason::Premise(premise));
}
return Verdict::Unsupported(Reason::Words(novel));
}
if !held.is_empty() || repeats_a_day || self.numbers.repeats_one(sentence) {
return Verdict::Supported;
}
if claims::answers_yes_or_no(sentence) {
return Verdict::Unsupported(Reason::Answer);
}
Verdict::NoClaim
}
}
const ABBREVIATIONS: &[&str] =
&["rp", "no", "dr", "drg", "mr", "mrs", "ms", "jl", "st", "tel", "telp", "hp", "wa", "approx", "vs"];
fn split_sentences(text: &str) -> Vec<(String, String)> {
let mut sentences = Vec::new();
let mut sentence = String::new();
let characters: Vec<char> = text.chars().collect();
let mut index = 0;
while let Some(&character) = characters.get(index) {
let next = characters.get(index + 1).copied();
let ends = match character {
'\n' => true,
'.' | '!' | '?' | '…' | '。' => {
let at_a_break = next.is_none_or(char::is_whitespace);
let short = character == '.' && {
let word: String = sentence.chars().rev().take_while(|c| !c.is_whitespace()).collect();
let word: String = word.chars().rev().collect::<String>().to_lowercase();
let letters = word.chars().filter(|c| c.is_alphabetic()).count();
let only_letters = word.chars().all(|c| c.is_alphabetic() || c == '.');
(only_letters && (letters <= 1 || word.contains('.'))) || ABBREVIATIONS.contains(&word.as_str())
};
at_a_break && !short
}
_ => false,
};
if character != '\n' {
sentence.push(character);
}
if ends {
let mut gap = String::new();
if character == '\n' {
gap.push('\n');
}
while let Some(space) = characters.get(index + 1).copied().filter(|c| c.is_whitespace()) {
gap.push(space);
index += 1;
}
if !sentence.trim().is_empty() {
sentences.push((sentence.trim_start().to_owned(), gap));
} else if let Some((_, last_gap)) = sentences.last_mut() {
last_gap.push_str(&gap);
}
sentence = String::new();
}
index += 1;
}
if !sentence.trim().is_empty() {
sentences.push((sentence.trim_start().to_owned(), String::new()));
}
sentences
}
#[cfg(test)]
mod tests;