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)]
87struct Written {
88    text: String,
89    readings: Vec<Reading>,
90    percent: bool,
91    /// Byte offset in the text, for its sentence.
92    at: usize,
93}
94
95/// One reading of a number: its value and the half unit of its last written digit.
96#[derive(Clone, Copy, Debug)]
97struct Reading {
98    value: f64,
99    half_unit: f64,
100}
101
102impl Figures {
103    pub fn new() -> Self {
104        Self::default()
105    }
106
107    /// Adds the numbers a text states.
108    pub fn add_text(&mut self, text: &str) {
109        for number in scan(text) {
110            for reading in &number.readings {
111                self.values.push((reading.value, number.percent));
112            }
113        }
114    }
115
116    /// Adds the numbers of a JSON value: its numbers as they are, its strings as texts.
117    pub fn add_json(&mut self, value: &serde_json::Value) {
118        match value {
119            serde_json::Value::Number(number) => {
120                if let Some(value) = number.as_f64() {
121                    self.values.push((value.abs(), false));
122                }
123            }
124            serde_json::Value::String(text) => self.add_text(text),
125            serde_json::Value::Array(items) => items.iter().for_each(|item| self.add_json(item)),
126            serde_json::Value::Object(fields) => fields.values().for_each(|item| self.add_json(item)),
127            serde_json::Value::Null | serde_json::Value::Bool(_) => {}
128        }
129    }
130
131    /// Whether the facts hold no number.
132    pub fn is_empty(&self) -> bool {
133        self.values.is_empty()
134    }
135
136    /// The numbers of `text` the facts do not hold, in order.
137    pub fn unsupported(&self, text: &str, rules: NumberRules) -> Vec<UnsupportedNumber> {
138        scan(text)
139            .into_iter()
140            .filter(|number| !self.holds(number, rules))
141            .map(|number| UnsupportedNumber { sentence: sentence_at(text, number.at), number: number.text })
142            .collect()
143    }
144
145    fn holds(&self, number: &Written, rules: NumberRules) -> bool {
146        number.readings.iter().any(|reading| {
147            self.values.iter().any(|(fact, fact_percent)| {
148                let mut candidates = vec![(*fact, 1.0)];
149                if rules.ratios_as_percent {
150                    // A ratio fact read as a percentage, a percentage fact as a ratio.
151                    if number.percent && !fact_percent {
152                        candidates.push((fact * 100.0, 1.0));
153                    }
154                    if !number.percent && *fact_percent {
155                        candidates.push((fact / 100.0, 1.0));
156                    }
157                }
158                candidates.iter().any(|(fact, _)| close(*fact, *reading, rules.tolerance))
159            })
160        })
161    }
162}
163
164fn close(fact: f64, reading: Reading, tolerance: Tolerance) -> bool {
165    let room = match tolerance {
166        Tolerance::Rounding => reading.half_unit,
167        Tolerance::Exact => 0.0,
168    };
169    // A little more, for values that binary floating point cannot write exactly.
170    let slack = 1e-9 * reading.value.abs().max(1.0);
171    (fact.abs() - reading.value).abs() <= room + slack
172}
173
174/// The numbers of `text`.
175fn scan(text: &str) -> Vec<Written> {
176    let chars: Vec<(usize, char)> = text.char_indices().collect();
177    let mut found = Vec::new();
178    let mut index = 0;
179    while let Some(&(at, c)) = chars.get(index) {
180        if !c.is_ascii_digit() {
181            index += 1;
182            continue;
183        }
184        // A digit glued to letters (`Q3`, `H1`, `v2`, `gpt5`) is part of a name, unless the
185        // letters are a currency (`Rp15.000`).
186        let in_a_name =
187            letters_before(&chars, index).is_some_and(|letters| !CURRENCY_PREFIXES.contains(&letters.as_str()));
188        let start = index;
189        while let Some(&(_, c)) = chars.get(index) {
190            let separator_between_digits = matches!(c, '.' | ',')
191                && chars.get(index + 1).is_some_and(|(_, next)| next.is_ascii_digit())
192                && index > start;
193            if c.is_ascii_digit() || separator_between_digits {
194                index += 1;
195            } else {
196                break;
197            }
198        }
199        let token: String = chars.get(start..index).unwrap_or_default().iter().map(|(_, c)| c).collect();
200        // Letters right after the digits (`15k`, `2jt`) or a word after a space (`15 ribu`).
201        let (word, word_end) = word_after(&chars, index);
202        if in_a_name {
203            index = index.max(word_end);
204            continue;
205        }
206        let multiplier =
207            word.as_deref().and_then(|word| MULTIPLIERS.iter().find(|(name, _)| *name == word).map(|(_, by)| *by));
208        let glued_letters = chars.get(index).is_some_and(|(_, c)| c.is_alphabetic());
209        // Letters glued to the digits that are not a multiplier (`3rd`, `2x`): still a number.
210        let percent = percent_after(&chars, index, word.as_deref());
211        let mut written = token.clone();
212        let mut end = index;
213        if let Some(word) = word.as_deref().filter(|_| multiplier.is_some()) {
214            written = if glued_letters { format!("{token}{word}") } else { format!("{token} {word}") };
215            end = word_end;
216        }
217        if percent {
218            written.push('%');
219        }
220        let readings: Vec<Reading> = readings_of(&token)
221            .into_iter()
222            .map(|reading| match multiplier {
223                Some(by) => Reading { value: reading.value * by, half_unit: reading.half_unit * by },
224                None => reading,
225            })
226            .collect();
227        let a_word = !percent
228            && multiplier.is_none()
229            && !token.contains(['.', ','])
230            && readings.iter().all(|reading| reading.value <= 2.0);
231        if !readings.is_empty() && !a_word {
232            found.push(Written { text: written, readings, percent, at });
233        }
234        index = end.max(index);
235    }
236    found
237}
238
239/// The letters glued before position `at` (`$` signs skipped), lowercase, if any.
240fn letters_before(chars: &[(usize, char)], at: usize) -> Option<String> {
241    let mut start = at;
242    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| *c == '$') {
243        start -= 1;
244    }
245    let end = start;
246    while start > 0 && chars.get(start - 1).is_some_and(|(_, c)| c.is_alphabetic()) {
247        start -= 1;
248    }
249    (start < end)
250        .then(|| chars.get(start..end).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect())
251}
252
253/// The word right after a number (glued or after spaces), lowercase, and where it ends.
254fn word_after(chars: &[(usize, char)], from: usize) -> (Option<String>, usize) {
255    let mut index = from;
256    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
257        index += 1;
258    }
259    let start = index;
260    while chars.get(index).is_some_and(|(_, c)| c.is_alphabetic()) {
261        index += 1;
262    }
263    if index == start {
264        return (None, from);
265    }
266    let word: String = chars.get(start..index).unwrap_or_default().iter().flat_map(|(_, c)| c.to_lowercase()).collect();
267    (Some(word), index)
268}
269
270/// Whether a `%` or the word percent follows the number.
271fn percent_after(chars: &[(usize, char)], from: usize, word: Option<&str>) -> bool {
272    let mut index = from;
273    while chars.get(index).is_some_and(|(_, c)| *c == ' ' || *c == '\u{a0}') {
274        index += 1;
275    }
276    chars.get(index).is_some_and(|(_, c)| *c == '%') || matches!(word, Some("percent" | "persen" | "pct"))
277}
278
279/// The values `token` (digits with `.` and `,`) may mean.
280fn readings_of(token: &str) -> Vec<Reading> {
281    let separators: Vec<char> = token.chars().filter(|c| matches!(c, '.' | ',')).collect();
282    let groups: Vec<&str> = token.split(['.', ',']).collect();
283    let integer = |digits: &str| digits.parse::<f64>().ok();
284    let decimal = |whole: &str, fraction: &str| {
285        let value = format!("{whole}.{fraction}").parse::<f64>().ok()?;
286        let places = i32::try_from(fraction.len()).ok()?;
287        Some(Reading { value, half_unit: 0.5 * 10f64.powi(-places) })
288    };
289    let whole = |digits: String| integer(&digits).map(|value| Reading { value, half_unit: 0.5 });
290    let mut readings = Vec::new();
291    match separators.as_slice() {
292        [] => readings.extend(whole(token.to_owned())),
293        [_] => {
294            let (Some(left), Some(right)) = (groups.first(), groups.get(1)) else { return readings };
295            // `1.234` or `1,234`: a thousand and more, or one and a little.
296            if right.len() == 3 {
297                readings.extend(whole(format!("{left}{right}")));
298            }
299            readings.extend(decimal(left, right));
300        }
301        [first, rest @ ..] => {
302            let last = rest.last().copied().unwrap_or(*first);
303            let all_same = rest.iter().all(|separator| separator == first);
304            let inner_are_thousands = groups.iter().skip(1).take(groups.len().saturating_sub(2)).all(|g| g.len() == 3);
305            if all_same && groups.iter().skip(1).all(|group| group.len() == 3) {
306                // `1.234.567`
307                readings.extend(whole(groups.concat()));
308            } else if !all_same
309                && last != *first
310                && inner_are_thousands
311                && rest.iter().rev().skip(1).all(|s| s == first)
312            {
313                // `1.234,56` and `1,234.56`: the last separator is the decimal one.
314                let (Some(fraction), Some(head)) = (groups.last(), groups.get(..groups.len() - 1)) else {
315                    return readings;
316                };
317                readings.extend(decimal(&head.concat(), fraction));
318            }
319        }
320    }
321    readings
322}
323
324/// The sentence of `text` around byte offset `at`: from the end of the sentence before it to
325/// the end of its own. A `.` between digits ends nothing.
326fn sentence_at(text: &str, at: usize) -> String {
327    let ends_a_sentence = |index: usize, c: char| {
328        matches!(c, '.' | '!' | '?' | '\n')
329            && text
330                .get(index + c.len_utf8()..)
331                .is_none_or(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
332    };
333    let start = text
334        .char_indices()
335        .rfind(|(index, c)| *index < at && ends_a_sentence(*index, *c))
336        .map_or(0, |(index, c)| index + c.len_utf8());
337    let end = text
338        .char_indices()
339        .find(|(index, c)| *index >= at && ends_a_sentence(*index, *c))
340        .map_or(text.len(), |(index, c)| index + c.len_utf8());
341    text.get(start..end).unwrap_or_default().trim().to_owned()
342}
343
344#[cfg(test)]
345#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
346mod tests {
347    use super::*;
348
349    fn rules() -> NumberRules {
350        NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: true }
351    }
352
353    fn unsupported(facts: &[&str], text: &str, rules: NumberRules) -> Vec<String> {
354        let mut known = Figures::new();
355        facts.iter().for_each(|fact| known.add_text(fact));
356        known.unsupported(text, rules).into_iter().map(|u| u.number).collect()
357    }
358
359    #[test]
360    fn a_rounded_number_matches_its_fact() {
361        let facts = ["revenue 1234567, growth 13.19, margin 12.6"];
362        assert!(unsupported(&facts, "Revenue was 1.2 million, up 13.2, margin 13.", rules()).is_empty());
363        assert!(unsupported(&facts, "Revenue reached 1,234,567 (13,19 growth).", rules()).is_empty());
364        // More precise than the facts, or another figure.
365        assert_eq!(unsupported(&facts, "Growth was 13.21 and 14.", rules()), ["13.21", "14"]);
366        let exact = NumberRules { tolerance: Tolerance::Exact, ratios_as_percent: false };
367        assert_eq!(unsupported(&facts, "Growth was 13.2, margin 12.6.", exact), ["13.2"]);
368    }
369
370    #[test]
371    fn percentages_match_ratios() {
372        let mut known = Figures::new();
373        known.add_json(&serde_json::json!({"conversion": 0.1319, "share": "45%", "orders": 1520}));
374        let rules = rules();
375        let found = |text: &str| known.unsupported(text, rules).into_iter().map(|u| u.number).collect::<Vec<_>>();
376        assert!(found("Conversion rose to 13.2% on 1,520 orders.").is_empty());
377        assert!(found("Konversi 13,19 persen, pangsa 0,45.").is_empty());
378        assert_eq!(found("Conversion was 14%."), ["14%"]);
379        let plain = NumberRules { tolerance: Tolerance::Rounding, ratios_as_percent: false };
380        assert_eq!(known.unsupported("Conversion was 13.2%.", plain).len(), 1);
381        // A JSON fact is the number it is: 1.234 is not a thousand.
382        let mut json = Figures::new();
383        json.add_json(&serde_json::json!(1.234));
384        assert_eq!(json.unsupported("It was 1234.", rules).len(), 1);
385        assert!(json.unsupported("It was 1,23.", rules).is_empty());
386    }
387
388    #[test]
389    fn multipliers_and_notations() {
390        let facts = ["sales 15000, budget 2500000, total 3100000000"];
391        assert!(
392            unsupported(&facts, "Sales were 15k (Rp15 ribu), budget 2,5 jt, total 3,1 miliar.", rules()).is_empty()
393        );
394        assert!(unsupported(&facts, "Budget: 2.5 million. Sales: 15.000 (US$15k).", rules()).is_empty());
395        // `m` is a metre as often as a million: a word, not a multiplier.
396        assert_eq!(unsupported(&facts, "The shelf is 4 m.", rules()), ["4"]);
397        assert_eq!(unsupported(&facts, "Sales were 16k.", rules()), ["16k"]);
398    }
399
400    #[test]
401    fn words_names_and_signs_are_not_figures() {
402        let facts = ["down 5.4"];
403        assert!(unsupported(&facts, "In Q3 the 2 stores of H1 fell 5.4%.", NumberRules::default()).is_empty());
404        assert!(unsupported(&facts, "It fell -5.4.", rules()).is_empty());
405        assert_eq!(unsupported(&facts, "3 stores fell.", rules()), ["3"]);
406    }
407
408    #[test]
409    fn the_sentence_of_each_number_is_reported() {
410        let mut known = Figures::new();
411        known.add_text("10");
412        let found = known.unsupported("Orders grew 12.5% to 10. That beat the plan of 9.", rules());
413        assert_eq!(found.len(), 2);
414        assert_eq!(found[0].number, "12.5%");
415        assert_eq!(found[0].sentence, "Orders grew 12.5% to 10.");
416        assert_eq!(found[1].sentence, "That beat the plan of 9.");
417    }
418}