limen-common 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,64 @@
1
+ """Shared building blocks for the Limen libraries.
2
+
3
+ Each library of the Limen family (dpc-radar, egms-client, effis-client,
4
+ firms-client, glofas-ewds, ingv-shakemap, copernicus-ems, imageserver-export,
5
+ ispra-idrogeo, rainfall-thresholds, fwi-chain) wrote its own retry loop, data
6
+ folder, bounding box, quantile and reliability score, each a little different.
7
+ This package holds one of each, so the libraries agree:
8
+
9
+ - :mod:`limen_common.http`: one retry policy for HTTP (extra ``[http]``);
10
+ - :mod:`limen_common.paths`: where a library keeps its data, and writing a file
11
+ so that a crash never leaves half of it;
12
+ - :mod:`limen_common.geo`: a point and a box, always longitude first;
13
+ - :mod:`limen_common.stats`: one way to take a quantile, with missing values;
14
+ - :mod:`limen_common.danger`: the EFFIS fire danger classes, written once;
15
+ - :mod:`limen_common.reliability`: how far to trust a number, on one scale;
16
+ - :mod:`limen_common.record`: the open-data record ``opendata-record/v2``,
17
+ typed, with its JSON Schema and :func:`~limen_common.record.validate`
18
+ (extra ``[record]`` to check);
19
+ - :mod:`limen_common.check`: one answer checker, so a text quotes the facts
20
+ and nothing else;
21
+ - :mod:`limen_common.facts`: how facts write a time and round a number, and
22
+ the ``ANSWER_RULES`` every library shares;
23
+ - :mod:`limen_common.llms`: ``llms.txt``, ``llms-full.txt`` and the agent
24
+ skill for a library's site (extra ``[llms]`` for the API pages).
25
+
26
+ The convention behind all of them: ``None`` means "not measured". It is never
27
+ zero, never ``NaN`` and never a neutral guess. A function that cannot answer
28
+ says so; it does not invent a number.
29
+
30
+ Nothing here reads the clock: a function that needs "today" takes it.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from importlib.metadata import PackageNotFoundError, version
36
+
37
+ from limen_common.danger import EFFIS_FWI_CLASSES, effis_class
38
+ from limen_common.geo import ITALY, BBox, Point, haversine_m
39
+ from limen_common.paths import atomic_write, data_dir
40
+ from limen_common.reliability import Level, Reliability, weakest
41
+ from limen_common.stats import quantile, quantiles, rank
42
+
43
+ try:
44
+ __version__ = version("limen-common")
45
+ except PackageNotFoundError: # pragma: no cover - a source checkout without metadata
46
+ __version__ = "0.0.0"
47
+
48
+ __all__ = [
49
+ "EFFIS_FWI_CLASSES",
50
+ "ITALY",
51
+ "BBox",
52
+ "Level",
53
+ "Point",
54
+ "Reliability",
55
+ "__version__",
56
+ "atomic_write",
57
+ "data_dir",
58
+ "effis_class",
59
+ "haversine_m",
60
+ "quantile",
61
+ "quantiles",
62
+ "rank",
63
+ "weakest",
64
+ ]
limen_common/check.py ADDED
@@ -0,0 +1,603 @@
1
+ """Check a text against the facts it was written from: no number invented, swapped or flipped.
2
+
3
+ The facts of a library hold every number of an answer. A text for people,
4
+ written by a template or by a language model, should quote them and nothing
5
+ else. The checker was copied in every library with diverging signatures
6
+ (``check_text`` returned ``list[Misquote]`` in rainfall-thresholds and
7
+ ``list[str]`` in egms-client); this is the one signature they share:
8
+
9
+ check_text(text, facts, *, lang="en", question="", rules=RULES) -> list[Misquote]
10
+
11
+ What differs between libraries is data, not code: the units a text may write
12
+ and the key suffixes that name them, the words that say a number goes down
13
+ or up. They live in a :class:`Rules`; :data:`RULES` is the default and
14
+ :meth:`Rules.with_units` / :meth:`Rules.with_directions` add to it.
15
+
16
+ Four checks, from the loosest:
17
+
18
+ * :func:`check_text`: every number of the text is a figure of the facts, to
19
+ the decimals written (``145`` and ``145.2`` match 145.24; ``146`` does not),
20
+ in its unit. A fault is ``invented`` (no fact has it), ``unit`` (a fact of
21
+ another unit: 30.9 mm written as 30.9 mm/h) or ``rounded`` (close, but not
22
+ the fact rounded to the decimals written: 118.1 for 118.04). From 100, a
23
+ round number is allowed (``1,600`` for 1,603). A percentage matches a share
24
+ (``76%`` for 0.762) or a number of a ``_pct`` key.
25
+ * :func:`check_signs`: a number said to go down (*drops by 4.0*, *scende di
26
+ 4,0*, ``-4.0``) is a negative figure of the facts, and one said to go up a
27
+ positive one. Fault ``sign``.
28
+ * :func:`check_claims`: in the sentences of a template (:class:`Sentence`),
29
+ each number is the one of *its* fact. Fault ``swapped``.
30
+ * :func:`fill` writes a template, and refuses to return a text that would
31
+ fail :func:`check_text`.
32
+
33
+ Texts are in English (``lang="en"``: ``1,234.5``) or Italian (``lang="it"``:
34
+ ``1.234,5``). Dates, years and clock times are not checked, nor numbers that
35
+ are in the question. Digits inside a word (``E47N19``, ``L3``) are not
36
+ numbers. Pure: no network, no model.
37
+
38
+ The check knows that a number is a fact of the right unit, not that it is
39
+ said of the right thing: "Melito got 30.9 mm" passes when 30.9 mm is the
40
+ threshold. :func:`check_claims` covers that for template sentences only.
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import math
46
+ import re
47
+ from collections.abc import Callable, Iterator, Mapping, Sequence
48
+ from dataclasses import dataclass, field, replace
49
+ from typing import Any, Literal
50
+
51
+ __all__ = [
52
+ "RULES",
53
+ "Fault",
54
+ "Figure",
55
+ "Lang",
56
+ "Misquote",
57
+ "Number",
58
+ "Rules",
59
+ "Sentence",
60
+ "at",
61
+ "check_claims",
62
+ "check_signs",
63
+ "check_text",
64
+ "directions",
65
+ "figures",
66
+ "fill",
67
+ "numbers",
68
+ ]
69
+
70
+ Lang = Literal["en", "it"]
71
+ Fault = Literal["invented", "unit", "rounded", "sign", "swapped"]
72
+
73
+ #: A hyphen, a minus sign (U+2212) and an en dash, written before a number.
74
+ _MINUS = "-\u2212\u2013"
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class Rules:
79
+ """What a library adds to the checker, as data.
80
+
81
+ ``units``: a unit as a text writes it -> its canonical name
82
+ (``"millimetres per hour": "mm/h"``). ``key_units``: a fact key suffix ->
83
+ the unit it names (``("_mm_h", "mm/h")``; the longest suffix wins).
84
+ ``down`` and ``up``: per language, the words that say a number goes down
85
+ or up, as regular expressions. ``strings``: whether digits inside string
86
+ facts (``"release 2018-2022"``) count as figures.
87
+ """
88
+
89
+ units: Mapping[str, str] = field(default_factory=dict)
90
+ key_units: tuple[tuple[str, str], ...] = ()
91
+ down: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
92
+ up: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
93
+ strings: bool = True
94
+
95
+ def with_units(
96
+ self, units: Mapping[str, str] = {}, *, keys: Sequence[tuple[str, str]] = ()
97
+ ) -> Rules:
98
+ """These rules, with more units and key suffixes."""
99
+ return replace(self, units={**self.units, **units}, key_units=(*self.key_units, *keys))
100
+
101
+ def with_directions(
102
+ self, *, down: Mapping[str, Sequence[str]] = {}, up: Mapping[str, Sequence[str]] = {}
103
+ ) -> Rules:
104
+ """These rules, with more words of descent and rise."""
105
+
106
+ def join(
107
+ a: Mapping[str, tuple[str, ...]], b: Mapping[str, Sequence[str]]
108
+ ) -> dict[str, tuple[str, ...]]:
109
+ return {k: (*a.get(k, ()), *b.get(k, ())) for k in {*a, *b}}
110
+
111
+ return replace(self, down=join(self.down, down), up=join(self.up, up))
112
+
113
+ def unit_of_key(self, key: str) -> str | None:
114
+ """The unit a fact key names by its suffix, or ``None``."""
115
+ for suffix, unit in sorted(self.key_units, key=lambda p: len(p[0]), reverse=True):
116
+ if key.endswith(suffix):
117
+ return unit
118
+ return None
119
+
120
+
121
+ RULES = Rules(
122
+ units={
123
+ "mm/h": "mm/h",
124
+ "mm h-1": "mm/h",
125
+ "millimetres per hour": "mm/h",
126
+ "millimeters per hour": "mm/h",
127
+ "mm/year": "mm/a",
128
+ "mm/anno": "mm/a",
129
+ "mm/a": "mm/a",
130
+ "mm": "mm",
131
+ "millimetres": "mm",
132
+ "millimeters": "mm",
133
+ "millimetri": "mm",
134
+ "km²": "km2",
135
+ "km2": "km2",
136
+ "km": "km",
137
+ "ha": "ha",
138
+ "m³/s": "m3/s",
139
+ "m3/s": "m3/s",
140
+ "m": "m",
141
+ "metres": "m",
142
+ "meters": "m",
143
+ "metri": "m",
144
+ "hours": "h",
145
+ "hour": "h",
146
+ "ore": "h",
147
+ "h": "h",
148
+ "days": "d",
149
+ "day": "d",
150
+ "giorni": "d",
151
+ "°C": "Cel",
152
+ "%g": "%g",
153
+ "%": "%",
154
+ },
155
+ key_units=(
156
+ ("_mm_h", "mm/h"),
157
+ ("_mm_per_hour", "mm/h"),
158
+ ("_mm_per_year", "mm/a"),
159
+ ("_mm", "mm"),
160
+ ("_km2", "km2"),
161
+ ("_km", "km"),
162
+ ("_ha", "ha"),
163
+ ("_m3_s", "m3/s"),
164
+ ("_m", "m"),
165
+ ("_h", "h"),
166
+ ("_hours", "h"),
167
+ ("_days", "d"),
168
+ ("_c", "Cel"),
169
+ ("_pct", "%"),
170
+ ("_percent", "%"),
171
+ ("_pctg", "%g"),
172
+ ),
173
+ down={
174
+ "en": (
175
+ r"goes down",
176
+ r"going down",
177
+ r"went down",
178
+ r"drops?",
179
+ r"dropping",
180
+ r"dropped",
181
+ r"falls?",
182
+ r"falling",
183
+ r"fell",
184
+ r"decreases?",
185
+ r"decreasing",
186
+ r"down by",
187
+ r"lowers?",
188
+ r"lowering",
189
+ ),
190
+ "it": (
191
+ r"scende",
192
+ r"scendono",
193
+ r"cala",
194
+ r"calano",
195
+ r"diminuisce",
196
+ r"diminuiscono",
197
+ r"si abbassa",
198
+ r"si abbassano",
199
+ r"in calo",
200
+ r"in discesa",
201
+ ),
202
+ },
203
+ up={
204
+ "en": (
205
+ r"goes up",
206
+ r"going up",
207
+ r"went up",
208
+ r"rises?",
209
+ r"rising",
210
+ r"rose",
211
+ r"increases?",
212
+ r"increasing",
213
+ r"up by",
214
+ r"grows?",
215
+ r"growing",
216
+ ),
217
+ "it": (
218
+ r"sale",
219
+ r"salgono",
220
+ r"cresce",
221
+ r"crescono",
222
+ r"aumenta",
223
+ r"aumentano",
224
+ r"si alza",
225
+ r"si alzano",
226
+ r"in aumento",
227
+ r"in salita",
228
+ ),
229
+ },
230
+ )
231
+ """The default rules: the units of the Limen libraries and the plain words of
232
+ descent and rise. A library adds its own (``sinks``, ``subsidenza``, ``west``)
233
+ with :meth:`Rules.with_directions`."""
234
+
235
+
236
+ @dataclass(frozen=True, slots=True)
237
+ class Number:
238
+ """A number as written: its text, value, decimals, sign, percent and unit."""
239
+
240
+ text: str
241
+ value: float
242
+ decimals: int
243
+ sign: int # -1, +1 when written; 0 when not
244
+ percent: bool
245
+ unit: str | None
246
+ start: int
247
+ end: int
248
+
249
+
250
+ @dataclass(frozen=True, slots=True)
251
+ class Figure:
252
+ """A number of the facts: where it is (a dotted path), its value and its unit."""
253
+
254
+ key: str
255
+ value: float
256
+ unit: str | None
257
+
258
+
259
+ @dataclass(frozen=True, slots=True)
260
+ class Misquote:
261
+ """A number of the text that is not a fact as written.
262
+
263
+ ``said`` is the piece of text, ``fault`` what is wrong, ``unit`` the unit
264
+ written with it, ``key`` the fact it is closest to or said of (a dotted
265
+ path, ``""`` when none) and ``fact`` what that fact holds.
266
+ """
267
+
268
+ said: str
269
+ fault: Fault
270
+ unit: str | None = None
271
+ key: str = ""
272
+ fact: Any = None
273
+
274
+ def __str__(self) -> str:
275
+ if self.fault == "invented":
276
+ return f"«{self.said}»: no fact has this number"
277
+ if self.fault == "sign":
278
+ return f"«{self.said}»: the facts give it the other sign ({self.fact})"
279
+ return f"«{self.said}»: {self.fault}, {self.key} is {self.fact}"
280
+
281
+
282
+ _EN = r"(?<![\w.,])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)"
283
+ _IT = r"(?<![\w.,])(\d{1,3}(?:\.\d{3})+(?:,\d+)?|\d+(?:,\d+)?)"
284
+ _MONTHS = (
285
+ "january|february|march|april|may|june|july|august|september|october|november|december|"
286
+ "gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre"
287
+ )
288
+ _DATES = re.compile(
289
+ r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?(?:[+-]\d{2}:\d{2}|Z)?)?"
290
+ r"|\b\d{1,2}:\d{2}\b|\b\d{1,2}/\d{1,2}(?:/\d{2,4})?\b"
291
+ rf"|\b\d{{1,2}}\s+(?:{_MONTHS})(?:\s+\d{{4}})?\b|\b(?:19|20)\d{{2}}\b",
292
+ re.IGNORECASE,
293
+ )
294
+ _DIGITS = re.compile(r"\d+(?:\.\d+)?")
295
+
296
+
297
+ def _pattern(lang: Lang, rules: Rules) -> re.Pattern[str]:
298
+ units = "|".join(re.escape(u) for u in sorted(rules.units, key=len, reverse=True))
299
+ suffix = r"(?:st|nd|rd|th)?" if lang == "en" else r"(?:°|ª|º)?"
300
+ # The unit may touch the number (42mm); with no unit, the number ends at a word
301
+ # boundary, so digits inside an identifier (E47N19, L3) are not numbers.
302
+ tail = rf"(?:\s?(?P<unit>{units})(?![\w/²³])|(?!\w))" if units else r"(?P<unit>(?!))?(?!\w)"
303
+ return re.compile(rf"{_EN if lang == 'en' else _IT}{suffix}{tail}", re.IGNORECASE)
304
+
305
+
306
+ def _blank(text: str) -> str:
307
+ """Dates, times and years blanked out (same length, so positions hold)."""
308
+ return _DATES.sub(lambda m: " " * len(m.group()), text.replace("**", " "))
309
+
310
+
311
+ def numbers(text: str, lang: Lang = "en", *, rules: Rules = RULES) -> list[Number]:
312
+ """The numbers of a text, in order; dates, years and clock times left out."""
313
+ plain = _blank(text)
314
+ units = {k.lower(): v for k, v in rules.units.items()}
315
+ out = []
316
+ for m in _pattern(lang, rules).finditer(plain):
317
+ raw = m.group(1)
318
+ digits = raw.replace(".", "").replace(",", ".") if lang == "it" else raw.replace(",", "")
319
+ sign = 0
320
+ start = m.start()
321
+ if start and plain[start - 1] in _MINUS + "+":
322
+ before = plain[start - 2] if start >= 2 else " "
323
+ if not (before.isalnum() or before in "._/"):
324
+ sign = 1 if plain[start - 1] == "+" else -1
325
+ start -= 1
326
+ written = m.group("unit")
327
+ unit = units[written.lower()] if written else None
328
+ out.append(
329
+ Number(
330
+ text=text[start : m.end()].strip(),
331
+ value=float(digits),
332
+ decimals=len(digits.partition(".")[2]),
333
+ sign=sign,
334
+ percent=unit == "%",
335
+ unit=unit,
336
+ start=start,
337
+ end=m.end(),
338
+ )
339
+ )
340
+ return out
341
+
342
+
343
+ def figures(facts: Any, *, rules: Rules = RULES, path: str = "") -> Iterator[Figure]:
344
+ """Every number of a tree of facts, with its path and the unit its key names.
345
+
346
+ Booleans, ``None`` and ``NaN`` are not numbers. With ``rules.strings``, the
347
+ digits inside a string are figures too (unitless).
348
+ """
349
+ if isinstance(facts, bool) or facts is None:
350
+ return
351
+ if isinstance(facts, int | float):
352
+ if math.isfinite(facts):
353
+ yield Figure(path, float(facts), rules.unit_of_key(path.rsplit(".", 1)[-1]))
354
+ elif isinstance(facts, str):
355
+ if rules.strings:
356
+ yield from (Figure(path, float(d), None) for d in _DIGITS.findall(facts))
357
+ elif isinstance(facts, Mapping):
358
+ for key, value in facts.items():
359
+ yield from figures(value, rules=rules, path=f"{path}.{key}" if path else str(key))
360
+ elif isinstance(facts, list | tuple):
361
+ for i, value in enumerate(facts):
362
+ yield from figures(value, rules=rules, path=f"{path}.{i}" if path else str(i))
363
+
364
+
365
+ def at(facts: Any, key: str) -> Any:
366
+ """The fact at a dotted path (list positions as numbers); ``None`` when there is none."""
367
+ for part in key.split("."):
368
+ if isinstance(facts, Mapping) and part in facts:
369
+ facts = facts[part]
370
+ elif isinstance(facts, list | tuple) and part.isdigit() and int(part) < len(facts):
371
+ facts = facts[int(part)]
372
+ else:
373
+ return None
374
+ return facts
375
+
376
+
377
+ def _agrees(n: Number, fact: float) -> bool:
378
+ """Is ``fact`` the number ``n`` to the decimals written (sign aside)?"""
379
+ fact = abs(fact)
380
+ if round(fact, n.decimals) == n.value:
381
+ return True
382
+ if n.decimals == 0 and n.value >= 100:
383
+ # A round number: 1,600 for 1,603. Only from 100: below it, "20" for 15.3 would pass.
384
+ whole = str(int(n.value))
385
+ zeros = len(whole) - len(whole.rstrip("0"))
386
+ return zeros > 0 and round(fact, -zeros) == n.value
387
+ return False
388
+
389
+
390
+ def _share(n: Number, fact: float) -> bool:
391
+ """A percentage written for a share: 76% for 0.762."""
392
+ return n.percent and abs(fact) <= 1 and round(abs(fact) * 100, n.decimals) == n.value
393
+
394
+
395
+ def _fits(n: Number, f: Figure) -> bool:
396
+ """The unit written fits the fact: none written, the same, or a percentage of a share."""
397
+ return n.unit is None or f.unit == n.unit or (n.percent and f.unit is None)
398
+
399
+
400
+ def check_text(
401
+ text: str, facts: Any, *, lang: Lang = "en", question: str = "", rules: Rules = RULES
402
+ ) -> list[Misquote]:
403
+ """The numbers of ``text`` that are not facts of their unit. Empty: faithful.
404
+
405
+ Numbers written in ``question`` are allowed: an answer may repeat them.
406
+ """
407
+ known = list(figures(facts, rules=rules))
408
+ asked = {n.value for n in numbers(question, lang, rules=rules)}
409
+ found: list[Misquote] = []
410
+ for n in numbers(text, lang, rules=rules):
411
+ if n.value in asked:
412
+ continue
413
+ if any(_fits(n, f) and (_agrees(n, f.value) or _share(n, f.value)) for f in known):
414
+ continue
415
+ other = [f for f in known if f.unit not in (None, n.unit) and _agrees(n, f.value)]
416
+ if other:
417
+ found.append(Misquote(n.text, "unit", n.unit, other[0].key, other[0].value))
418
+ continue
419
+ step = 10.0 ** (-n.decimals) + 1e-9
420
+ near = [f for f in known if _fits(n, f) and abs(abs(f.value) - n.value) <= step]
421
+ if near:
422
+ found.append(Misquote(n.text, "rounded", n.unit, near[0].key, near[0].value))
423
+ continue
424
+ found.append(Misquote(n.text, "invented", n.unit))
425
+ return found
426
+
427
+
428
+ def directions(text: str, lang: Lang = "en", *, rules: Rules = RULES) -> list[int]:
429
+ """For each number of :func:`numbers`, the direction the text gives it.
430
+
431
+ -1 when a minus sign is written before it or a word of descent comes
432
+ right before it (*drops by*, *scende di*); +1 with ``+`` or a word of
433
+ rise; 0 otherwise, and for percentages.
434
+ """
435
+ plain = _blank(text)
436
+ link = (
437
+ r"(?:\s+(?:by|of|at|about|around|some|nearly|almost))*\s+"
438
+ if lang == "en"
439
+ else r"(?:\s+(?:di|a|circa|quasi|sui|intorno a|oltre))*\s+"
440
+ )
441
+ claims: dict[int, int] = {}
442
+ for words, sign in ((rules.down.get(lang, ()), -1), (rules.up.get(lang, ()), 1)):
443
+ if not words:
444
+ continue
445
+ verbs = "|".join(words)
446
+ for m in re.finditer(rf"\b(?:{verbs}){link}(?=[{_MINUS}+]?\d)", plain, re.IGNORECASE):
447
+ claims[m.end()] = sign
448
+ return [
449
+ 0 if n.percent else n.sign or claims.get(n.start, 0)
450
+ for n in numbers(text, lang, rules=rules)
451
+ ]
452
+
453
+
454
+ def check_signs(
455
+ text: str, facts: Any, *, lang: Lang = "en", rules: Rules = RULES
456
+ ) -> list[Misquote]:
457
+ """Numbers said to go down that the facts hold only as rising, and the reverse.
458
+
459
+ A number with no direction is not read. Strings in the facts (dates,
460
+ names) are left out: they have no sign.
461
+ """
462
+ numeric = list(figures(facts, rules=replace(rules, strings=False)))
463
+ out = []
464
+ for n, claimed in zip(
465
+ numbers(text, lang, rules=rules), directions(text, lang, rules=rules), strict=True
466
+ ):
467
+ if not claimed:
468
+ continue
469
+ # Only facts of the unit written: a -4 mm displacement says nothing of a 4 mm/a velocity.
470
+ matching = [f for f in numeric if _fits(n, f) and _agrees(n, f.value)]
471
+ if matching and not any(f.value == 0 or (f.value > 0) == (claimed > 0) for f in matching):
472
+ start = max(0, text.rfind(" ", 0, max(0, n.start - 12)))
473
+ said = text[start : n.end].strip()
474
+ found = matching[0]
475
+ out.append(Misquote(said, "sign", n.unit, found.key, found.value))
476
+ return out
477
+
478
+
479
+ # Templates: sentences that name their fact.
480
+
481
+
482
+ @dataclass(frozen=True, slots=True)
483
+ class Sentence:
484
+ """A sentence of a template: its text in each language, and when it applies.
485
+
486
+ Holes are ``{key|fmt}``: a dotted path into the facts and a format
487
+ (``signed``, ``one``, ``two``, ``five``, ``pct``, ``int``, ``date``).
488
+ ``{name}`` holes are words, given to :func:`fill` as ``words``.
489
+ """
490
+
491
+ en: str
492
+ it: str
493
+ when: Callable[[Mapping[str, Any]], bool] = lambda _: True
494
+
495
+
496
+ _HOLE = re.compile(r"\{(?P<key>[\w.]+)\|(?P<fmt>\w+)\}")
497
+ _WORD = re.compile(r"\{(\w+)\}")
498
+ _VALUE = r"([\u2212+\-]?[\d.,]*\d\s?%?)"
499
+
500
+
501
+ def _format(value: Any, fmt: str, lang: Lang) -> str:
502
+ if fmt == "date":
503
+ return str(value)
504
+ number = float(value)
505
+ text = {
506
+ "signed": f"{number:+.1f}" if round(number, 1) else "0.0",
507
+ "one": f"{number:.1f}",
508
+ "two": f"{number:.2f}",
509
+ "five": f"{number:.5f}",
510
+ "pct": f"{number * 100:.0f}%",
511
+ "int": f"{number:,.0f}",
512
+ }[fmt]
513
+ if lang == "it":
514
+ text = text.replace(",", "\0").replace(".", ",").replace("\0", ".")
515
+ text = text.replace("%", " %")
516
+ return text
517
+
518
+
519
+ def fill(
520
+ sentences: Sequence[Sentence],
521
+ facts: Mapping[str, Any],
522
+ lang: Lang = "en",
523
+ *,
524
+ words: Mapping[str, str] | None = None,
525
+ rules: Rules = RULES,
526
+ ) -> str:
527
+ """The answer in words, from a template: every number is one of the facts.
528
+
529
+ :class:`ValueError` if the text would quote a number the facts do not
530
+ hold (a bug of the template, never shipped): it is checked before it is
531
+ returned.
532
+ """
533
+ words = words or {}
534
+ out = []
535
+ for sentence in sentences:
536
+ if not sentence.when(facts):
537
+ continue
538
+ text = _HOLE.sub(
539
+ lambda m: _format(at(facts, m["key"]), m["fmt"], lang), getattr(sentence, lang)
540
+ )
541
+ out.append(_WORD.sub(lambda m: words[m[1]], text))
542
+ text = " ".join(out)
543
+ wrong = check_text(text, facts, lang=lang, rules=rules)
544
+ if wrong:
545
+ raise ValueError(f"the template quotes numbers not in the facts: {[str(w) for w in wrong]}")
546
+ return text
547
+
548
+
549
+ def check_claims(
550
+ text: str,
551
+ facts: Mapping[str, Any],
552
+ sentences: Sequence[Sentence],
553
+ *,
554
+ lang: Lang = "en",
555
+ rules: Rules = RULES,
556
+ ) -> list[Misquote]:
557
+ """In the sentences of a template, the numbers that are not the one of their fact.
558
+
559
+ A sentence written in other words is not read: a model that rephrases
560
+ goes through :func:`check_text` and :func:`check_signs` only.
561
+ """
562
+ out = []
563
+ plain = text.replace("**", "")
564
+ for sentence in sentences:
565
+ template = _WORD.sub(lambda m: "\0" + m[1], getattr(sentence, lang))
566
+ holes = list(_HOLE.finditer(template))
567
+ if not holes:
568
+ continue
569
+ pattern, last = "", 0
570
+ for hole in holes:
571
+ value = r"(\d{4}-\d\d-\d\d)" if hole["fmt"] == "date" else _VALUE
572
+ pattern += _loose(template[last : hole.start()]) + value
573
+ last = hole.end()
574
+ pattern += _loose(template[last:].rstrip("."))
575
+ for found in re.finditer(pattern, plain):
576
+ for token, hole in zip(found.groups(), holes, strict=True):
577
+ fact = at(facts, hole["key"])
578
+ if hole["fmt"] == "date":
579
+ ok = token.strip() == str(fact)
580
+ else:
581
+ ok = _equal(token, fact, hole["fmt"], lang, rules)
582
+ if not ok:
583
+ out.append(Misquote(found.group().strip(), "swapped", None, hole["key"], fact))
584
+ return out
585
+
586
+
587
+ def _loose(piece: str) -> str:
588
+ """A piece of template as a pattern: the words of a ``{name}`` match any words."""
589
+ parts = re.split(r"\0\w+", piece)
590
+ return r"[^.;:]*?".join(re.escape(p) for p in parts)
591
+
592
+
593
+ def _equal(token: str, fact: Any, fmt: str, lang: Lang, rules: Rules) -> bool:
594
+ if fact is None or isinstance(fact, bool):
595
+ return False
596
+ found = numbers(token.replace("\u2212", "-"), lang, rules=rules)
597
+ if len(found) != 1:
598
+ return False
599
+ n = found[0]
600
+ value = float(fact) * (100 if fmt == "pct" else 1)
601
+ if not _agrees(n, value):
602
+ return False
603
+ return not (n.sign and value and (n.sign > 0) != (value > 0))