gooddata-eval 1.81.1.dev6__py3-none-any.whl → 1.81.1.dev8__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,280 @@
1
+ # (C) 2026 GoodData Corporation. All rights reserved.
2
+ """Whether a forecast answer names a value the forecast predicted.
3
+
4
+ ``execute_forecast`` returns parallel lists in ``data``: ``attribute`` names the period, ``origin``
5
+ holds the actual values and ``prediction`` the forecast. The forecast line starts from the last
6
+ actual value: a row that repeats the last actual period, with that value as its prediction and
7
+ both bounds. The periods after it carry a prediction only, and those are the values a grounded
8
+ answer names. ``data.points`` holds the same rows but keeps only the oldest ``max_points`` of them,
9
+ so a long history can leave every prediction out of it.
10
+
11
+ The answer is read as text. A number counts as a value when the value rounds to it at the last
12
+ digit the answer wrote: ``5.54M`` names 5,541,967.50, ``5.5 million`` too, ``5.55M`` does not,
13
+ and ``6M`` names nothing because one digit agrees with too many values. Both the English and the Czech way of writing a
14
+ number are read (``1,234.5`` and ``1 234,5``), and a percentage also matches a ratio
15
+ (``48.1%`` names 0.481).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import re
22
+ from dataclasses import dataclass
23
+ from typing import Any
24
+
25
+ # A number of one digit agrees with too many values to name one.
26
+ _MIN_DIGITS = 2
27
+ # How many predicted values a detail lists.
28
+ _LISTED = 5
29
+ _SCALES = {
30
+ "k": 1e3,
31
+ "thousand": 1e3,
32
+ "thousands": 1e3,
33
+ "tis": 1e3,
34
+ "tisíc": 1e3,
35
+ "tisíce": 1e3,
36
+ "m": 1e6,
37
+ "mn": 1e6,
38
+ "mil": 1e6,
39
+ "mln": 1e6,
40
+ "million": 1e6,
41
+ "millions": 1e6,
42
+ "milion": 1e6,
43
+ "milionu": 1e6,
44
+ "miliony": 1e6,
45
+ "milionů": 1e6,
46
+ "b": 1e9,
47
+ "bn": 1e9,
48
+ "billion": 1e9,
49
+ "billions": 1e9,
50
+ "bln": 1e9,
51
+ "mld": 1e9,
52
+ "miliard": 1e9,
53
+ "miliarda": 1e9,
54
+ "miliardu": 1e9,
55
+ "miliardy": 1e9,
56
+ }
57
+ _GROUP_SPACES = "   "
58
+ # A grouped number (5,541,967.50 or 5 541 967,50), else a plain one (193, 5.54, 1,5).
59
+ _NUMBER = re.compile(
60
+ rf"(?<![\w.,])(?P<num>\d{{1,3}}(?:[,.{_GROUP_SPACES}]\d{{3}})+(?:[.,]\d+)?(?!\d)|\d+(?:[.,]\d+)?(?!\d))"
61
+ r"(?:\s?(?P<pct>%)|\s?(?P<word>[^\W\d_]+))?"
62
+ )
63
+ # A date or a timestamp: 2025-10, 2025-10-17, 2025-10-17T14:30:00Z, 2025-10-17 14:30+02:00.
64
+ _ISO_DATE = re.compile(
65
+ r"\b\d{4}-\d{2}(?:-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)?(?![\d:])"
66
+ )
67
+ _MONTHS = (
68
+ r"(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec|january|february|march|april|june|july|august"
69
+ r"|september|october|november|december|ledna|února|března|dubna|května|června|července|srpna|září|října"
70
+ r"|listopadu|prosince|leden|únor|březen|duben|květen|červen|červenec|srpen|říjen|listopad|prosinec)"
71
+ )
72
+ # A date written with a month name: "October 17, 2025", "17. října 2025", "October 2025". Its day and
73
+ # year are not values, whatever follows them.
74
+ _WRITTEN_DATE = re.compile(
75
+ # A day is one or two digits that no group or decimal follows: "October 5,541,967.50" is a value.
76
+ rf"\b{_MONTHS}\.?\s+\d{{1,2}}(?:st|nd|rd|th)?\b(?![.,]\d)(?:,?\s+\d{{4}}\b)?"
77
+ rf"|(?<![\d.,])\d{{1,2}}\.?\s+{_MONTHS}\b(?:\s+\d{{4}}\b)?"
78
+ rf"|\b{_MONTHS}\.?\s+\d{{4}}\b",
79
+ re.IGNORECASE,
80
+ )
81
+ _YEAR = re.compile(r"(?:19|20)\d\d")
82
+ # A bare year is a date only after one of these words: "2045 orders" is a value, "October 2025" is not.
83
+ # Words that may follow a year in a date ("in 2025 Q4", "2025 rok"), which leave it a date.
84
+ _DATE_WORD = re.compile(r"q[1-4]|h[12]|fy|year|years|rok|roku|roce|and|a|to|do", re.IGNORECASE)
85
+ # A year followed by one of these is a period, whatever precedes it. The word reader stops at a digit,
86
+ # so "2025 Q4" gives "q".
87
+ _PERIOD_AFTER_YEAR = re.compile(r"q|h|q[1-4]|h[12]|fy", re.IGNORECASE)
88
+ _BEFORE_YEAR = re.compile(
89
+ r"\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec|january|february|march|april|june|july|august"
90
+ r"|september|october|november|december|q[1-4]|h[12]|fy|in|of|year|since|until|through|to|from|by|and"
91
+ r"|ledna|února|března|dubna|května|června|července|srpna|září|října|listopadu|prosince|leden|únor|březen"
92
+ r"|duben|květen|červen|červenec|srpen|říjen|listopad|prosinec|v|roce|rok|roku|od|do|a)\.?,?\s*$",
93
+ re.IGNORECASE,
94
+ )
95
+ # A date written in numbers: 17. 10. 2025, 17. 10., 17.10.2025, 10/17/2025. Without the space or the
96
+ # year, "48.1." would be a value at the end of a sentence.
97
+ _NUMERIC_DATE = re.compile(
98
+ r"(?<![\d.,])(?:\d{1,2}\.\s\d{1,2}\.(?:\s?\d{4}\b)?|\d{1,2}\.\d{1,2}\.\d{4}\b)|\b\d{1,2}/\d{1,2}/\d{2,4}\b"
99
+ )
100
+ # A number followed by one of these counts periods, as in "the next 14 days": the horizon, not a value.
101
+ _SPAN_WORD = re.compile(
102
+ r"days?|weeks?|months?|quarters?|years?|periods?|den|dny|dní|dnů|týden|týdny|týdnů|měsíc|měsíce|měsíců"
103
+ r"|čtvrtletí|roky|let|období",
104
+ re.IGNORECASE,
105
+ )
106
+ # What follows a confidence level: "95% confidence", "95 % CI", "interval spolehlivosti 95 %" is not.
107
+ _CONFIDENCE_AFTER = re.compile(r"\s?%?\s*(?:confidence|ci\b|prediction interval|spolehlivost)", re.IGNORECASE)
108
+ # English: comma or space groups, dot decimals. Czech: dot or space groups, comma decimals.
109
+ _READINGS = (
110
+ (re.compile(rf"\d{{1,3}}(?:[,{_GROUP_SPACES}]\d{{3}})*(?:\.\d+)?|\d+(?:\.\d+)?"), f",{_GROUP_SPACES}", "."),
111
+ (re.compile(rf"\d{{1,3}}(?:[.{_GROUP_SPACES}]\d{{3}})*(?:,\d+)?|\d+(?:,\d+)?"), f".{_GROUP_SPACES}", ","),
112
+ )
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class _Number:
117
+ text: str
118
+ value: float
119
+ # The place of the last digit written, scaled: 0.01 for "5.54", 10,000 for "5.54M".
120
+ unit: float
121
+ percent: bool
122
+
123
+
124
+ def _readings(token: str) -> list[tuple[float, float, int]]:
125
+ """(value, unit of the last significant digit, significant digits) for each way the token can be read.
126
+
127
+ The zeros that end a whole number are rounding: "5,540,000" is written to the ten thousand, so
128
+ its unit is 10,000 and it has three significant digits.
129
+ """
130
+ out: list[tuple[float, float, int]] = []
131
+ for pattern, groups, decimal in _READINGS:
132
+ if not pattern.fullmatch(token):
133
+ continue
134
+ plain = token.translate({ord(c): None for c in groups}).replace(decimal, ".")
135
+ whole, _, fraction = plain.partition(".")
136
+ if fraction:
137
+ unit = 10.0 ** -len(fraction)
138
+ significant = len((whole + fraction).lstrip("0"))
139
+ else:
140
+ trailing = len(whole) - len(whole.rstrip("0"))
141
+ unit = 10.0**trailing
142
+ significant = len(whole.strip("0"))
143
+ reading = (float(plain), unit, significant)
144
+ if reading not in out:
145
+ out.append(reading)
146
+ return out
147
+
148
+
149
+ def answer_numbers(text: str) -> list[_Number]:
150
+ """The numbers an answer writes, each in every reading it allows.
151
+
152
+ Left out: dates (2025-10, October 17, 17. 10. 2025, October 2025, a year after a preposition such
153
+ as "in 2025"), a span of time ("the next 14 days"), a confidence level ("95% confidence") and
154
+ numbers of one significant digit.
155
+ """
156
+ numbers: list[_Number] = []
157
+ text = _NUMERIC_DATE.sub(" ", _WRITTEN_DATE.sub(" ", _ISO_DATE.sub(" ", text)))
158
+ for match in _NUMBER.finditer(text):
159
+ token = match.group("num")
160
+ word = (match.group("word") or "").casefold()
161
+ scale = _SCALES.get(word, 1.0)
162
+ percent = match.group("pct") is not None
163
+ before = text[max(0, match.start() - 16) : match.start()]
164
+ # "rise to 2045 orders" names a count: a year-like number followed by a noun is a value.
165
+ counted = bool(word) and not _DATE_WORD.fullmatch(word)
166
+ dated = bool(_PERIOD_AFTER_YEAR.fullmatch(word)) or (bool(_BEFORE_YEAR.search(before)) and not counted)
167
+ if scale == 1.0 and not percent and _YEAR.fullmatch(token) and dated:
168
+ continue
169
+ if scale == 1.0 and not percent and _SPAN_WORD.fullmatch(word):
170
+ continue
171
+ if _CONFIDENCE_AFTER.match(text, match.end("pct") if percent else match.end("num")):
172
+ continue
173
+ written = match.group(0).strip() if scale != 1.0 or percent else token
174
+ numbers.extend(
175
+ _Number(written, value * scale, unit * scale, percent)
176
+ for value, unit, significant in _readings(token)
177
+ if significant >= _MIN_DIGITS
178
+ )
179
+ return numbers
180
+
181
+
182
+ def _agrees(number: _Number, value: float) -> bool:
183
+ """Whether the number is the value rounded to the number's last digit (signs aside)."""
184
+ targets = (abs(value), abs(value) * 100) if number.percent else (abs(value),)
185
+ return any(abs(number.value - t) <= number.unit / 2 * (1 + 1e-9) for t in targets)
186
+
187
+
188
+ def _numbers_of(data: dict[str, Any], key: str) -> list[Any]:
189
+ values = data.get(key)
190
+ return values if isinstance(values, list) else []
191
+
192
+
193
+ def _finite(value: Any) -> float | None:
194
+ if isinstance(value, bool) or not isinstance(value, int | float):
195
+ return None
196
+ try:
197
+ number = float(value)
198
+ except OverflowError: # an int too large for a float
199
+ return None
200
+ return number if math.isfinite(number) else None
201
+
202
+
203
+ def forecast_values(execute_result: Any) -> dict[str, list[float]]:
204
+ """The predicted values after the last actual period, their bounds, and the starting point.
205
+
206
+ ``predicted`` and ``bounds`` are the periods the forecast adds; ``anchor`` is the prediction
207
+ the last actual period carries, which the line starts from and which is not a forecast.
208
+ """
209
+ data = execute_result.get("data") if isinstance(execute_result, dict) else None
210
+ if not isinstance(data, dict):
211
+ return {"predicted": [], "bounds": [], "anchor": []}
212
+ attribute = _numbers_of(data, "attribute")
213
+ origin = _numbers_of(data, "origin")
214
+ prediction = _numbers_of(data, "prediction")
215
+ lower = _numbers_of(data, "lower_bound")
216
+ upper = _numbers_of(data, "upper_bound")
217
+
218
+ def at(values: list[Any], index: int) -> Any:
219
+ return values[index] if index < len(values) else None
220
+
221
+ actual_periods = {
222
+ period
223
+ for index, period in enumerate(attribute)
224
+ if isinstance(period, str) and _finite(at(origin, index)) is not None
225
+ }
226
+ predicted: list[float] = []
227
+ bounds: list[float] = []
228
+ anchor: list[float] = []
229
+ for index, raw in enumerate(prediction):
230
+ value = _finite(raw)
231
+ if value is None:
232
+ continue
233
+ # The starting point repeats the last actual period, as a row of its own or on the actual
234
+ # row. Without periods to compare, it is the first predicted row when its interval has no
235
+ # width: a flat series has rows of no width after it too, and those are forecasts.
236
+ period = at(attribute, index)
237
+ starts_line = (
238
+ _finite(at(origin, index)) is not None
239
+ or (isinstance(period, str) and period in actual_periods)
240
+ or (
241
+ not actual_periods
242
+ and not predicted
243
+ and not anchor
244
+ and _finite(at(lower, index)) == value == _finite(at(upper, index))
245
+ )
246
+ )
247
+ if starts_line:
248
+ anchor.append(value)
249
+ continue
250
+ predicted.append(value)
251
+ for side in (lower, upper):
252
+ bound = _finite(at(side, index))
253
+ if bound is not None:
254
+ bounds.append(bound)
255
+ return {"predicted": predicted, "bounds": bounds, "anchor": anchor}
256
+
257
+
258
+ def _named(numbers: list[_Number], values: list[float]) -> list[str]:
259
+ return list(dict.fromkeys(n.text for n in numbers if any(_agrees(n, v) for v in values)))
260
+
261
+
262
+ def check_answer_grounded(execute_result: Any, answer: str) -> tuple[bool, dict[str, Any]]:
263
+ """Whether the answer names a value the forecast predicted for a period after the actuals.
264
+
265
+ The bounds and the starting point are reported but not required: an answer may leave the
266
+ interval out, and may mention the last actual value as context.
267
+ """
268
+ if not (isinstance(execute_result, dict) and execute_result.get("success") is True):
269
+ return False, {"reason": "no forecast ran"}
270
+ values = forecast_values(execute_result)
271
+ if not values["predicted"]:
272
+ return False, {"reason": "the forecast returned no predicted value"}
273
+ numbers = answer_numbers(answer)
274
+ named = _named(numbers, values["predicted"])
275
+ return bool(named), {
276
+ "predicted": values["predicted"][:_LISTED],
277
+ "named": named,
278
+ "bounds_named": _named(numbers, values["bounds"]),
279
+ "anchor_named": _named(numbers, values["anchor"]),
280
+ }
@@ -9,7 +9,7 @@ import logging
9
9
  import os
10
10
  import threading
11
11
  import time
12
- from collections.abc import Iterator
12
+ from collections.abc import Generator
13
13
  from contextlib import contextmanager
14
14
  from datetime import UTC, datetime, timedelta
15
15
  from typing import TYPE_CHECKING, Any
@@ -395,7 +395,7 @@ def observe(
395
395
  conversation_id: str | None = None,
396
396
  item_input: Any = None,
397
397
  output: Any = None,
398
- ) -> Iterator[ScoreTarget | None]:
398
+ ) -> Generator[ScoreTarget | None, None, None]:
399
399
  """Export gd-eval's experiment root span for one run and yield where to score it.
400
400
 
401
401
  A run belongs to a Langfuse experiment through the attributes on that span, so the span
@@ -557,7 +557,7 @@ _PENDING_SCORES: contextvars.ContextVar[list[dict[str, Any]] | None] = contextva
557
557
 
558
558
 
559
559
  @contextmanager
560
- def collect_scores(langfuse: HttpxLangfuseClient) -> Iterator[None]:
560
+ def collect_scores(langfuse: HttpxLangfuseClient) -> Generator[None, None, None]:
561
561
  """Hold every ``score_safe`` write made in the block and send them as one batch at its end.
562
562
 
563
563
  The batch is sent even when the drain was cancelled meanwhile, without retrying, so the