1mod attribution;
28mod claims;
29mod numbers;
30mod words;
31
32use std::fmt;
33
34use attribution::Attributions;
35use claims::{KnownAddresses, KnownDays, KnownWords};
36use numbers::KnownNumbers;
37
38#[cfg(feature = "jinja")]
40pub(crate) use numbers::grounded as grounded_numbers;
41
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
44pub struct Sources {
45 facts: Vec<String>,
46 customer: Vec<String>,
47}
48
49impl Sources {
50 pub fn new() -> Self {
51 Self::default()
52 }
53
54 #[must_use]
56 pub fn fact(mut self, text: impl Into<String>) -> Self {
57 self.add_fact(text);
58 self
59 }
60
61 #[must_use]
63 pub fn customer(mut self, text: impl Into<String>) -> Self {
64 self.add_customer(text);
65 self
66 }
67
68 pub fn add_fact(&mut self, text: impl Into<String>) {
69 let text = text.into();
70 if !text.trim().is_empty() {
71 self.facts.push(text);
72 }
73 }
74
75 pub fn add_customer(&mut self, text: impl Into<String>) {
76 let text = text.into();
77 if !text.trim().is_empty() {
78 self.customer.push(text);
79 }
80 }
81
82 pub fn facts_text(&self) -> String {
84 self.facts.join("\n")
85 }
86
87 pub fn customer_text(&self) -> String {
89 self.customer.join("\n")
90 }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
95#[non_exhaustive]
96pub enum Reason {
97 Number(String),
99 Attribution { number: String, word: String },
102 Day(String),
104 Address(String),
106 Words(Vec<String>),
108 Premise(Vec<String>),
111 Answer,
113}
114
115impl Reason {
116 pub fn may_be_confirmed(&self) -> bool {
119 matches!(self, Self::Words(_) | Self::Answer)
120 }
121}
122
123impl fmt::Display for Reason {
124 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
125 match self {
126 Self::Number(number) => write!(formatter, "the number {number} is not in the sources"),
127 Self::Attribution { number, word } => {
128 write!(formatter, "the sources give {number} to something else than {word}")
129 }
130 Self::Day(day) => write!(formatter, "the day {day} is not in the facts"),
131 Self::Address(address) => write!(formatter, "{address} is not in the facts"),
132 Self::Words(words) => write!(formatter, "not in the facts: {}", words.join(", ")),
133 Self::Premise(words) => write!(formatter, "only the customer wrote: {}", words.join(", ")),
134 Self::Answer => formatter.write_str("a yes or no the facts do not hold"),
135 }
136 }
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub enum Verdict {
142 Supported,
144 NoClaim,
146 Unknown,
149 Unsupported(Reason),
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct Sentence {
156 pub text: String,
158 gap: String,
160 pub verdict: Verdict,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Unsupported {
166 pub sentence: String,
167 pub reason: Reason,
168}
169
170#[derive(Debug, Clone, PartialEq, Eq)]
172pub struct Checked {
173 pub text: Option<String>,
176 pub unsupported: Vec<Unsupported>,
178 pub admits_unknown: bool,
181}
182
183impl Checked {
184 pub fn is_whole(&self) -> bool {
186 self.text.is_some() && self.unsupported.is_empty()
187 }
188}
189
190#[derive(Debug)]
192pub struct Review {
193 sentences: Vec<Sentence>,
194 numbers: KnownNumbers,
195}
196
197impl Review {
198 pub fn of(reply: &str, sources: &Sources) -> Self {
200 let facts = sources.facts_text();
201 let numbers = KnownNumbers::with_customer(&facts, &sources.customer_text());
202 let known = Known {
203 numbers: &numbers,
204 attributions: Attributions::of(&facts, &sources.customer_text()),
205 words: KnownWords::of(&facts),
206 customer_words: KnownWords::of(&sources.customer_text()),
207 days: KnownDays::of(&facts),
208 addresses: KnownAddresses::of(&facts),
209 };
210 let sentences = split_sentences(reply)
211 .into_iter()
212 .map(|(text, gap)| {
213 let verdict = known.verdict(&text);
214 Sentence { text, gap, verdict }
215 })
216 .collect();
217 Self { sentences, numbers }
218 }
219
220 pub fn sentences(&self) -> &[Sentence] {
221 &self.sentences
222 }
223
224 pub fn to_verify(&self) -> Vec<(usize, &str)> {
226 self.sentences
227 .iter()
228 .enumerate()
229 .filter(
230 |(_, sentence)| matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed()),
231 )
232 .map(|(index, sentence)| (index, sentence.text.as_str()))
233 .collect()
234 }
235
236 pub fn confirm(&mut self, index: usize) {
239 if let Some(sentence) = self.sentences.get_mut(index)
240 && matches!(&sentence.verdict, Verdict::Unsupported(reason) if reason.may_be_confirmed())
241 {
242 sentence.verdict = Verdict::Supported;
243 }
244 }
245
246 pub fn finish(self) -> Checked {
247 let mut kept = String::new();
248 let mut unsupported = Vec::new();
249 let mut holds_a_fact = false;
250 let mut admits_unknown = false;
251 for sentence in self.sentences {
252 match sentence.verdict {
253 Verdict::Unsupported(reason) => unsupported.push(Unsupported { sentence: sentence.text, reason }),
254 verdict => {
255 holds_a_fact |= verdict == Verdict::Supported;
256 admits_unknown |= verdict == Verdict::Unknown;
257 kept.push_str(&sentence.text);
258 kept.push_str(&sentence.gap);
259 }
260 }
261 }
262 let sendable = holds_a_fact || (unsupported.is_empty() && !admits_unknown);
266 let text = self.numbers.without_unknown_currencies(kept.trim());
267 Checked { text: (sendable && !text.is_empty()).then_some(text), unsupported, admits_unknown }
268 }
269}
270
271pub fn fact_sentences(sources: &Sources) -> Vec<String> {
274 sources.facts.iter().flat_map(|fact| split_sentences(&unwrapped(fact))).map(|(text, _)| text).collect()
275}
276
277fn unwrapped(text: &str) -> String {
281 let mut out = String::with_capacity(text.len());
282 let mut lines = text.lines().peekable();
283 while let Some(line) = lines.next() {
284 out.push_str(line);
285 let Some(next) = lines.peek() else { break };
286 let ends = line.trim_end().ends_with(['.', '!', '?', ':', ';']) || line.trim().is_empty();
287 let starts = next
288 .trim_start()
289 .starts_with(|c: char| c.is_uppercase() || c.is_ascii_digit() || matches!(c, '-' | '*' | '•'));
290 out.push(if ends || starts { '\n' } else { ' ' });
291 }
292 out
293}
294
295pub fn shares_a_fact(sentence: &str, fact: &str) -> bool {
299 let words = KnownWords::of(fact);
300 let (held, _) = words.sort(sentence);
301 !held.is_empty() || KnownNumbers::of(fact).repeats_one(sentence)
302}
303
304pub fn check(reply: &str, sources: &Sources) -> Checked {
306 Review::of(reply, sources).finish()
307}
308
309struct Known<'a> {
310 numbers: &'a KnownNumbers,
311 attributions: Attributions,
312 words: KnownWords,
313 customer_words: KnownWords,
315 days: KnownDays,
316 addresses: KnownAddresses,
317}
318
319impl Known<'_> {
320 fn verdict(&self, sentence: &str) -> Verdict {
321 if let Some(address) = self.addresses.first_unknown(sentence) {
322 return Verdict::Unsupported(Reason::Address(address));
323 }
324 if let Some(number) = self.numbers.first_unknown(sentence) {
325 return Verdict::Unsupported(Reason::Number(number));
326 }
327 if let Some((number, word)) = self.attributions.first_misattributed(sentence) {
328 return Verdict::Unsupported(Reason::Attribution { number, word });
329 }
330 let (unknown_day, repeats_a_day) = self.days.check(sentence);
331 if let Some(day) = unknown_day {
332 return Verdict::Unsupported(Reason::Day(day));
333 }
334 let (held, novel) = self.words.sort(sentence);
335 let states_facts_only = novel.is_empty() && !held.is_empty();
336 if !states_facts_only
337 && claims::admits_unknown(sentence)
338 && novel.iter().all(|word| self.customer_words.holds(word))
339 {
340 return Verdict::Unknown;
341 }
342 if !novel.is_empty() {
343 let premise: Vec<String> = novel.iter().filter(|word| self.customer_words.holds(word)).cloned().collect();
344 if !premise.is_empty() {
345 return Verdict::Unsupported(Reason::Premise(premise));
346 }
347 return Verdict::Unsupported(Reason::Words(novel));
348 }
349 if !held.is_empty() || repeats_a_day || self.numbers.repeats_one(sentence) {
350 return Verdict::Supported;
351 }
352 if claims::answers_yes_or_no(sentence) {
353 return Verdict::Unsupported(Reason::Answer);
354 }
355 Verdict::NoClaim
356 }
357}
358
359const ABBREVIATIONS: &[&str] =
361 &["rp", "no", "dr", "drg", "mr", "mrs", "ms", "jl", "st", "tel", "telp", "hp", "wa", "approx", "vs"];
362
363fn split_sentences(text: &str) -> Vec<(String, String)> {
367 let mut sentences = Vec::new();
368 let mut sentence = String::new();
369 let characters: Vec<char> = text.chars().collect();
370 let mut index = 0;
371 while let Some(&character) = characters.get(index) {
372 let next = characters.get(index + 1).copied();
373 let ends = match character {
374 '\n' => true,
375 '.' | '!' | '?' | '…' | '。' => {
376 let at_a_break = next.is_none_or(char::is_whitespace);
377 let short = character == '.' && {
379 let word: String = sentence.chars().rev().take_while(|c| !c.is_whitespace()).collect();
380 let word: String = word.chars().rev().collect::<String>().to_lowercase();
381 let letters = word.chars().filter(|c| c.is_alphabetic()).count();
382 let only_letters = word.chars().all(|c| c.is_alphabetic() || c == '.');
383 (only_letters && (letters <= 1 || word.contains('.'))) || ABBREVIATIONS.contains(&word.as_str())
384 };
385 at_a_break && !short
386 }
387 _ => false,
388 };
389 if character != '\n' {
390 sentence.push(character);
391 }
392 if ends {
393 let mut gap = String::new();
394 if character == '\n' {
395 gap.push('\n');
396 }
397 while let Some(space) = characters.get(index + 1).copied().filter(|c| c.is_whitespace()) {
398 gap.push(space);
399 index += 1;
400 }
401 if !sentence.trim().is_empty() {
402 sentences.push((sentence.trim_start().to_owned(), gap));
403 } else if let Some((_, last_gap)) = sentences.last_mut() {
404 last_gap.push_str(&gap);
405 }
406 sentence = String::new();
407 }
408 index += 1;
409 }
410 if !sentence.trim().is_empty() {
411 sentences.push((sentence.trim_start().to_owned(), String::new()));
412 }
413 sentences
414}
415
416#[cfg(test)]
417mod tests;