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