Skip to main content

graphrt_core/grounding/
figures.rs

1//! The numbers check of a report: every number a text states must be one of the facts, as
2//! rounded for the text.
3//!
4//! Unlike [`super::check`], which reads a chat reply sentence by sentence, this check looks at
5//! numbers only and leaves the words to the writer: a report may say anything about the figures,
6//! as long as each figure is one of the facts. It reports the numbers that are not, and changes
7//! nothing.
8//!
9//! - **Rounding**: a number matches a fact that rounds to it at the precision it is written with.
10//!   `13.2%` matches `13.19`, `13%` matches `12.6`, `1.2 million` matches `1,234,567`, but
11//!   `13.21` does not match `13.2` (a figure more precise than the facts is made up).
12//!   [`Tolerance::Exact`] asks for the value itself.
13//! - **Shares**: with `ratios_as_percent`, `13.19%` matches the ratio `0.1319` and `0.13`
14//!   matches `13%`.
15//! - **Notation**: `1.234.567` and `1,234,567` are the same number, and so are `13,19` and
16//!   `13.19`. A number that can be read both ways (`1.234`) matches either reading. Multipliers
17//!   (`15k`, `15 rb`, `2 jt`, `1.5 million`, `3 miliar`) are applied. Signs are ignored:
18//!   "down 5%" states the figure `-5%` as `5%`.
19//! - **Words**: `0`, `1` and `2` written alone are words ("2 stores"), not figures. A digit glued
20//!   to letters before it (`Q3`, `H1`, `v2`) is a name, not a figure.
21//!
22//! Facts are texts, read the same way, or JSON values, whose numbers are taken as they are (a
23//! JSON `1.234` is one and a quarter, never a thousand).
24
25/// How close a number must be to a fact.
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27#[non_exhaustive]
28pub enum Tolerance {
29    /// The fact rounds to the number at the precision it is written with.
30    #[default]
31    Rounding,
32    /// The number is the fact.
33    Exact,
34}
35
36/// How numbers are compared.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub struct NumberRules {
39    pub tolerance: Tolerance,
40    /// A percentage matches the ratio it is (`13.19%` and `0.1319`), both ways.
41    pub ratios_as_percent: bool,
42}
43
44/// A number the facts do not hold, with the sentence it stands in.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct UnsupportedNumber {
47    /// The number as the text writes it (`13.2%`, `1,2 juta`).
48    pub number: String,
49    pub sentence: String,
50}
51
52/// The numbers some facts hold.
53#[derive(Clone, Debug, Default)]
54pub struct Figures {
55    /// Each value, and whether it was written as a percentage.
56    values: Vec<(f64, bool)>,
57}
58
59/// Multipliers a number may be written with, in the word right after it.
60const MULTIPLIERS: &[(&str, f64)] = &[
61    ("k", 1e3),
62    ("rb", 1e3),
63    ("ribu", 1e3),
64    ("thousand", 1e3),
65    ("jt", 1e6),
66    ("juta", 1e6),
67    ("mn", 1e6),
68    ("million", 1e6),
69    ("millions", 1e6),
70    ("miliar", 1e9),
71    ("milyar", 1e9),
72    ("billion", 1e9),
73    ("bn", 1e9),
74    ("triliun", 1e12),
75    ("trillion", 1e12),
76];
77
78/// Currency codes and signs written right before a number (`Rp15.000`, `US$5`, `IDR 2jt`):
79/// the letters do not make the number part of a name.
80const CURRENCY_PREFIXES: &[&str] = &[
81    "rp", "idr", "us", "usd", "eur", "sgd", "s", "myr", "rm", "gbp", "jpy", "aud", "a", "inr", "rs", "php", "thb",
82    "vnd", "cny", "rmb", "hkd", "hk", "cad", "c", "nzd", "nz", "chf", "brl", "r", "zar", "krw", "kes", "ksh", "ngn",
83];
84
85/// One number in a text: the readings it may have.
86#[derive(Clone, Debug)]
87pub(super) struct Written {
88    pub(super) text: String,
89    readings: Vec<Reading>,
90    percent: bool,
91    /// Written with digits alone: no separator, multiplier or percent sign (`7`, `2024`).
92    pub(super) plain: bool,
93    /// Byte offset in the text, for its sentence.
94    pub(super) at: usize,
95    /// Byte offset right after the number as written (its multiplier and `%` included).
96    pub(super) end: usize,
97}
98
99impl Written {
100    /// The value of a plain number (`Self::plain`), `None` for any other.
101    pub(super) fn plain_value(&self) -> Option<f64> {
102        match self.readings.as_slice() {
103            [reading] if self.plain => Some(reading.value),
104            _ => None,
105        }
106    }
107}
108
109/// One reading of a number: its value and the half unit of its last written digit.
110#[derive(Clone, Copy, Debug)]
111struct Reading {
112    value: f64,
113    half_unit: f64,
114}
115
116impl Figures {
117    pub fn new() -> Self {
118        Self::default()
119    }
120
121    /// Adds the numbers a text states.
122    pub fn add_text(&mut self, text: &str) {
123        for number in scan(text) {
124            for reading in &number.readings {
125                self.values.push((reading.value, number.percent));
126            }
127        }
128    }
129
130    /// Adds the numbers of a JSON value: its numbers as they are, its strings as texts.
131    pub fn add_json(&mut self, value: &serde_json::Value) {
132        match value {
133            serde_json::Value::Number(number) => {
134                if let Some(value) = number.as_f64() {
135                    self.values.push((value.abs(), false));
136                }
137            }
138            serde_json::Value::String(text) => self.add_text(text),
139            serde_json::Value::Array(items) => items.iter().for_each(|item| self.add_json(item)),
140            serde_json::Value::Object(fields) => fields.values().for_each(|item| self.add_json(item)),
141            serde_json::Value::Null | serde_json::Value::Bool(_) => {}
142        }
143    }
144
145    /// Whether the facts hold no number.
146    pub fn is_empty(&self) -> bool {
147        self.values.is_empty()
148    }
149
150    /// The numbers of `text` the facts do not hold, in order.
151    pub fn unsupported(&self, text: &str, rules: NumberRules) -> Vec<UnsupportedNumber> {
152        scan(text)
153            .into_iter()
154            .filter(|number| !self.holds(number, rules))
155            .map(|number| UnsupportedNumber { sentence: sentence_at(text, number.at), number: number.text })
156            .collect()
157    }
158
159    pub(super) fn holds(&self, number: &Written, rules: NumberRules) -> bool {
160        number.readings.iter().any(|reading| {
161            self.values.iter().any(|(fact, fact_percent)| {
162                let mut candidates = vec![(*fact, 1.0)];
163                if rules.ratios_as_percent {
164                    // A ratio fact read as a percentage, a percentage fact as a ratio.
165                    if number.percent && !fact_percent {
166                        candidates.push((fact * 100.0, 1.0));
167                    }
168                    if !number.percent && *fact_percent {
169                        candidates.push((fact / 100.0, 1.0));
170                    }
171                }
172                candidates.iter().any(|(fact, _)| close(*fact, *reading, rules.tolerance))
173            })
174        })
175    }
176}
177
178fn close(fact: f64, reading: Reading, tolerance: Tolerance) -> bool {
179    let room = match tolerance {
180        Tolerance::Rounding => reading.half_unit,
181        Tolerance::Exact => 0.0,
182    };
183    // A little more, for values that binary floating point cannot write exactly.
184    let slack = 1e-9 * reading.value.abs().max(1.0);
185    (fact.abs() - reading.value).abs() <= room + slack
186}
187
188/// The numbers of `text`.
189pub(super) fn scan(text: &str) -> Vec<Written> {
190    let chars: Vec<(usize, char)> = text.char_indices().collect();
191    let mut found = Vec::new();
192    let mut index = 0;
193    while let Some(&(at, c)) = chars.get(index) {
194        if !c.is_ascii_digit() {
195            index += 1;
196            continue;
197        }
198        // A digit glued to letters (`Q3`, `H1`, `v2`, `gpt5`) is part of a name, unless the
199        // letters are a currency (`Rp15.000`).
200        let in_a_name =
201            letters_before(&chars, index).is_some_and(|letters| !CURRENCY_PREFIXES.contains(&letters.as_str()));
202        let start = index;
203        while let Some(&(_, c)) = chars.get(index) {
204            let separator_between_digits = matches!(c, '.' | ',')
205                && chars.get(index + 1).is_some_and(|(_, next)| next.is_ascii_digit())
206                && index > start;
207            if c.is_ascii_digit() || separator_between_digits {
208                index += 1;
209            } else {
210                break;
211            }
212        }
213        let token: String = chars.get(start..index).unwrap_or_default().iter().map(|(_, c)| c).collect();
214        // Letters right after the digits (`15k`, `2jt`) or a word after a space (`15 ribu`).
215        let (word, word_end) = word_after(&chars, index);
216        if in_a_name {
217            index = index.max(word_end);
218            continue;
219        }
220        let multiplier =
221            word.as_deref().and_then(|word| MULTIPLIERS.iter().find(|(name, _)| *name == word).map(|(_, by)| *by));
222        let glued_letters = chars.get(index).is_some_and(|(_, c)| c.is_alphabetic());
223        // Letters glued to the digits that are not a multiplier (`3rd`, `2x`): still a number.
224        let percent = percent_after(&chars, index, word.as_deref());
225        let mut written = token.clone();
226        let mut end = index;
227        if let Some(word) = word.as_deref().filter(|_| multiplier.is_some()) {
228            written = if glued_letters { format!("{token}{word}") } else { format!("{token} {word}") };
229            end = word_end;
230        }
231        if percent {
232            written.push('%');
233        }
234        let readings: Vec<Reading> = readings_of(&token)
235            .into_iter()
236            .map(|reading| match multiplier {
237                Some(by) => Reading { value: reading.value * by, half_unit: reading.half_unit * by },
238                None => reading,
239            })
240            .collect();
241        let plain = !percent && multiplier.is_none() && !token.contains(['.', ',']);
242        let a_word = plain && readings.iter().all(|reading| reading.value <= 2.0);
243        if !readings.is_empty() && !a_word {
244            let end_at = match word.as_deref() {
245                _ if !percent => end,
246                Some("percent" | "persen" | "pct") => word_end,
247                _ => percent_end(&chars, end),
248            };
249            let end_byte = chars.get(end_at).map_or(text.len(), |(byte, _)| *byte);
250            found.push(Written { text: written, readings, percent, plain, at, end: end_byte });
251        }
252        index = end.max(index);
253    }
254    found
255}
256
257/// The letters glued before position `at` (`$` signs skipped), lowercase, if any.
258fn letters_before(chars: &[(usize, char)], at: usize) -> Option<String> {
259    let mut start = at;
260    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| *c == '$') {
261        start -= 1;
262    }
263    let end = start;
264    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| c.is_alphabetic()) {
265        start -= 1;
266    }
267    (start < end)
268        .then(|| chars.get(start..end).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect())
269}
270
271/// The word right after a number (glued or after spaces), lowercase, and where it ends.
272fn word_after(chars: &[(usize, char)], from: usize) -> (Option<String>, usize) {
273    let mut index = from;
274    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
275        index += 1;
276    }
277    let start = index;
278    while chars.get(index).is_some_and(|(_, c)| c.is_alphabetic()) {
279        index += 1;
280    }
281    if index == start {
282        return (None, from);
283    }
284    let word: String = chars.get(start..index).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect();
285    (Some(word), index)
286}
287
288/// Where the `%` after the number ends (the index after it), or `from` when the percent is a
289/// word that `from` already passed.
290fn percent_end(chars: &[(usize, char)], from: usize) -> usize {
291    let mut index = from;
292    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
293        index += 1;
294    }
295    if chars.get(index).is_some_and(|(_, c)| *c == '%') { index + 1 } else { from }
296}
297
298/// Whether a `%` or the word percent follows the number.
299fn percent_after(chars: &[(usize, char)], from: usize, word: Option<&str>) -> bool {
300    let mut index = from;
301    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
302        index += 1;
303    }
304    chars.get(index).is_some_and(|(_, c)| *c == '%') || matches!(word, Some("percent" | "persen" | "pct"))
305}
306
307/// The values `token` (digits with `.` and `,`) may mean.
308fn readings_of(token: &str) -> Vec<Reading> {
309    let separators: Vec<char> = token.chars().filter(|c| matches!(c, '.' | ',')).collect();
310    let groups: Vec<&str> = token.split(['.', ',']).collect();
311    let integer = |digits: &str| digits.parse::<f64>().ok();
312    let decimal = |whole: &str, fraction: &str| {
313        let value = format!("{whole}.{fraction}").parse::<f64>().ok()?;
314        let places = i32::try_from(fraction.len()).ok()?;
315        Some(Reading { value, half_unit: 0.5 * 10f64.powi(-places) })
316    };
317    let whole = |digits: String| integer(&digits).map(|value| Reading { value, half_unit: 0.5 });
318    let mut readings = Vec::new();
319    match separators.as_slice() {
320        [] => readings.extend(whole(token.to_owned())),
321        [_] => {
322            let (Some(left), Some(right)) = (groups.first(), groups.get(1)) else { return readings };
323            // `1.234` or `1,234`: a thousand and more, or one and a little.
324            if right.len() == 3 {
325                readings.extend(whole(format!("{left}{right}")));
326            }
327            readings.extend(decimal(left, right));
328        }
329        [first, rest @ ..] => {
330            let last = rest.last().copied().unwrap_or(*first);
331            let all_same = rest.iter().all(|separator| separator == first);
332            let inner_are_thousands = groups.iter().skip(1).take(groups.len().saturating_sub(2)).all(|g| g.len() == 3);
333            if all_same && groups.iter().skip(1).all(|group| group.len() == 3) {
334                // `1.234.567`
335                readings.extend(whole(groups.concat()));
336            } else if !all_same
337                && last != *first
338                && inner_are_thousands
339                && rest.iter().rev().skip(1).all(|s| s == first)
340            {
341                // `1.234,56` and `1,234.56`: the last separator is the decimal one.
342                let (Some(fraction), Some(head)) = (groups.last(), groups.get(..groups.len() - 1)) else {
343                    return readings;
344                };
345                readings.extend(decimal(&head.concat(), fraction));
346            }
347        }
348    }
349    readings
350}
351
352/// The sentence of `text` around byte offset `at`, trimmed.
353pub(super) fn sentence_at(text: &str, at: usize) -> String {
354    let (start, end) = sentence_span(text, at);
355    text.get(start..end).unwrap_or_default().trim().to_owned()
356}
357
358/// The byte span of the sentence of `text` around byte offset `at`: from the end of the
359/// sentence before it to the end of its own. A `.` between digits ends nothing.
360pub(super) fn sentence_span(text: &str, at: usize) -> (usize, usize) {
361    let ends_a_sentence = |index: usize, c: char| {
362        matches!(c, '.' | '!' | '?' | '\n')
363            && text
364                .get(index + c.len_utf8()..)
365                .is_none_or(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
366    };
367    let start = text
368        .char_indices()
369        .rfind(|(index, c)| *index < at && ends_a_sentence(*index, *c))
370        .map_or(0, |(index, c)| index + c.len_utf8());
371    let end = text
372        .char_indices()
373        .find(|(index, c)| *index >= at && ends_a_sentence(*index, *c))
374        .map_or(text.len(), |(index, c)| index + c.len_utf8());
375    (start, end)
376}
377
378#[cfg(test)]
379#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
380mod tests {
381    use super::*;
382
383    fn rules() -> NumberRules {
384        NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true }
385    }
386
387    fn unsupported(facts: &[&str], text: &str, rules: NumberRules) -> Vec<String> {
388        let mut known = Figures::new();
389        facts.iter().for_each(|fact| known.add_text(fact));
390        known.unsupported(text, rules).into_iter().map(|u| u.number).collect()
391    }
392
393    #[test]
394    fn a_rounded_number_matches_its_fact() {
395        let facts = ["revenue 1234567, growth 13.19, margin 12.6"];
396        assert!(unsupported(&facts, "Revenue was 1.2 million, up 13.2, margin 13.", rules()).is_empty());
397        assert!(unsupported(&facts, "Revenue reached 1,234,567 (13,19 growth).", rules()).is_empty());
398        // More precise than the facts, or another figure.
399        assert_eq!(unsupported(&facts, "Growth was 13.21 and 14.", rules()), ["13.21", "14"]);
400        let exact = NumberRules { tolerance: Tolerance::Exact, ratios_as_percent: false };
401        assert_eq!(unsupported(&facts, "Growth was 13.2, margin 12.6.", exact), ["13.2"]);
402    }
403
404    #[test]
405    fn percentages_match_ratios() {
406        let mut known = Figures::new();
407        known.add_json(&serde_json::json!({"conversion": 0.1319, "share": "45%", "orders": 1520}));
408        let rules = rules();
409        let found = |text: &str| known.unsupported(text, rules).into_iter().map(|u| u.number).collect::<Vec<_>>();
410        assert!(found("Conversion rose to 13.2% on 1,520 orders.").is_empty());
411        assert!(found("Konversi 13,19 persen, pangsa 0,45.").is_empty());
412        assert_eq!(found("Conversion was 14%."), ["14%"]);
413        let plain = NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: false };
414        assert_eq!(known.unsupported("Conversion was 13.2%.", plain).len(), 1);
415        // A JSON fact is the number it is: 1.234 is not a thousand.
416        let mut json = Figures::new();
417        json.add_json(&serde_json::json!(1.234));
418        assert_eq!(json.unsupported("It was 1234.", rules).len(), 1);
419        assert!(json.unsupported("It was 1,23.", rules).is_empty());
420    }
421
422    #[test]
423    fn multipliers_and_notations() {
424        let facts = ["sales 15000, budget 2500000, total 3100000000"];
425        assert!(
426            unsupported(&facts, "Sales were 15k (Rp15 ribu), budget 2,5 jt, total 3,1 miliar.", rules()).is_empty()
427        );
428        assert!(unsupported(&facts, "Budget: 2.5 million. Sales: 15.000 (US$15k).", rules()).is_empty());
429        // `m` is a metre as often as a million: a word, not a multiplier.
430        assert_eq!(unsupported(&facts, "The shelf is 4 m.", rules()), ["4"]);
431        assert_eq!(unsupported(&facts, "Sales were 16k.", rules()), ["16k"]);
432    }
433
434    #[test]
435    fn words_names_and_signs_are_not_figures() {
436        let facts = ["down 5.4"];
437        assert!(unsupported(&facts, "In Q3 the 2 stores of H1 fell 5.4%.", NumberRules::default()).is_empty());
438        assert!(unsupported(&facts, "It fell -5.4.", rules()).is_empty());
439        assert_eq!(unsupported(&facts, "3 stores fell.", rules()), ["3"]);
440    }
441
442    #[test]
443    fn the_sentence_of_each_number_is_reported() {
444        let mut known = Figures::new();
445        known.add_text("10");
446        let found = known.unsupported("Orders grew 12.5% to 10. That beat the plan of 9.", rules());
447        assert_eq!(found.len(), 2);
448        assert_eq!(found[0].number, "12.5%");
449        assert_eq!(found[0].sentence, "Orders grew 12.5% to 10.");
450        assert_eq!(found[1].sentence, "That beat the plan of 9.");
451    }
452}