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