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