basal-engine 3.0.3__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.
Files changed (111) hide show
  1. basal/__init__.py +7 -0
  2. basal/adapter.py +420 -0
  3. basal/adapters.py +8 -0
  4. basal/agree.py +393 -0
  5. basal/attach.py +160 -0
  6. basal/attn512.py +132 -0
  7. basal/auth.py +194 -0
  8. basal/bench.py +367 -0
  9. basal/blockquant.py +227 -0
  10. basal/calibrate.py +2198 -0
  11. basal/chat.py +175 -0
  12. basal/cli.py +70 -0
  13. basal/client.py +8 -0
  14. basal/decision_log.py +189 -0
  15. basal/decision_rules.py +569 -0
  16. basal/decisions.py +158 -0
  17. basal/derive.py +98 -0
  18. basal/disconnect.py +85 -0
  19. basal/engine.py +6023 -0
  20. basal/evidence.py +133 -0
  21. basal/examples/choice.jsonl +8 -0
  22. basal/examples/complex.jsonl +5 -0
  23. basal/examples/labelled_tickets.jsonl +500 -0
  24. basal/examples/local_backend.py +34 -0
  25. basal/examples/noul.jsonl +8 -0
  26. basal/examples/questions.jsonl +20 -0
  27. basal/examples/score.jsonl +8 -0
  28. basal/examples/selfcheck_basal-omni-pico-Q8_0.json +1 -0
  29. basal/examples/selfcheck_basal-omni-pico.json +1 -0
  30. basal/examples/types_demo.py +74 -0
  31. basal/facts.py +497 -0
  32. basal/feedback.py +234 -0
  33. basal/file_identity.py +39 -0
  34. basal/finetune.py +321 -0
  35. basal/fit_decisions.py +944 -0
  36. basal/fla_configs.json +1822 -0
  37. basal/fold.py +206 -0
  38. basal/fonts/OFL-DMSans.txt +93 -0
  39. basal/fonts/OFL-SpaceGrotesk.txt +93 -0
  40. basal/fonts/dm-sans-latin-ext.woff2 +0 -0
  41. basal/fonts/dm-sans-latin.woff2 +0 -0
  42. basal/fonts/space-grotesk-latin-ext.woff2 +0 -0
  43. basal/fonts/space-grotesk-latin.woff2 +0 -0
  44. basal/fp8block.py +100 -0
  45. basal/gdn_graph.py +1792 -0
  46. basal/gemma4.py +726 -0
  47. basal/gemma4_graph.py +931 -0
  48. basal/gguf_export.py +497 -0
  49. basal/identity.py +217 -0
  50. basal/int8block.py +50 -0
  51. basal/interpolate.py +330 -0
  52. basal/jsonl.py +172 -0
  53. basal/lean.py +204 -0
  54. basal/llama_attn.py +252 -0
  55. basal/llama_attn_kernels.py +266 -0
  56. basal/llama_graph.py +587 -0
  57. basal/llama_kernels.py +593 -0
  58. basal/loadtest.py +189 -0
  59. basal/mcp_server.py +432 -0
  60. basal/media.py +138 -0
  61. basal/metrics.py +16 -0
  62. basal/mlx_attn_kernels.py +1057 -0
  63. basal/mlx_forward.py +326 -0
  64. basal/mlx_kernels.py +543 -0
  65. basal/mlx_metal.py +510 -0
  66. basal/navcut.py +283 -0
  67. basal/navigate.py +646 -0
  68. basal/navtree.py +397 -0
  69. basal/nvfp4.py +245 -0
  70. basal/ordercheck.py +165 -0
  71. basal/pdf.py +183 -0
  72. basal/prepared.py +355 -0
  73. basal/presets.py +8 -0
  74. basal/prompt.py +462 -0
  75. basal/rank.py +373 -0
  76. basal/readout.py +121 -0
  77. basal/request.py +327 -0
  78. basal/response_cache.py +105 -0
  79. basal/router.py +1551 -0
  80. basal/router_ui.html +902 -0
  81. basal/router_ui.py +277 -0
  82. basal/run.py +376 -0
  83. basal/selfcheck.py +215 -0
  84. basal/server.py +5279 -0
  85. basal/sets.py +214 -0
  86. basal/signals.py +28 -0
  87. basal/state_disk.py +942 -0
  88. basal/strix.py +505 -0
  89. basal/synth.py +92 -0
  90. basal/tasks.py +848 -0
  91. basal/textio.py +21 -0
  92. basal/think.py +390 -0
  93. basal/tools.py +171 -0
  94. basal/tpu.py +336 -0
  95. basal/tpu_kernels.py +129 -0
  96. basal/trace.py +125 -0
  97. basal/ui.html +861 -0
  98. basal/ui.py +526 -0
  99. basal/varloop.py +813 -0
  100. basal/varloop_graph.py +1377 -0
  101. basal/varloop_kernels.py +907 -0
  102. basal/viz.html +660 -0
  103. basal/viz.py +375 -0
  104. basal/vllm_unified.py +100 -0
  105. basal_engine-3.0.3.dist-info/METADATA +416 -0
  106. basal_engine-3.0.3.dist-info/RECORD +111 -0
  107. basal_engine-3.0.3.dist-info/WHEEL +5 -0
  108. basal_engine-3.0.3.dist-info/entry_points.txt +21 -0
  109. basal_engine-3.0.3.dist-info/licenses/LICENSE +202 -0
  110. basal_engine-3.0.3.dist-info/licenses/NOTICE +34 -0
  111. basal_engine-3.0.3.dist-info/top_level.txt +1 -0
basal/facts.py ADDED
@@ -0,0 +1,497 @@
1
+ """Fact injection: helper facts computed from a Polish state and appended to it, so the
2
+ model reads the arithmetic instead of doing it. The same function runs in training (on 50% of items) and in the
3
+ engine (`"facts": "auto"`), so the model works with or without them. Only arithmetic and calendar facts are added —
4
+ never a rule or an answer:
5
+ - every date in the text: weekday, and whether it is a Saturday or a statutory day off (with the holiday name);
6
+ - day gaps between consecutive dates (in order of appearance);
7
+ - "today minus N days" for "N dni temu" when the text states today's date;
8
+ - date + duration for the durations the text mentions ("14 dni", "2 tygodnie", "6 miesięcy", "5 lat"), for the
9
+ first dates (calendar arithmetic only: no shifting for days off — that is a rule);
10
+ - net/gross amounts for the VAT rates mentioned (23%, 8%, 5%), for the first amounts in zł; an amount
11
+ without a thousands separator ("2026,00 zł") is read whole, an exchange rate ("kurs … 4,31 zł") is skipped, and a
12
+ percentage is a VAT rate only with "VAT" / "podatek od towarów" in its sentence (not "5% wartości sporu").
13
+ Money arithmetic, appended after the facts above, at most MAX_TOTAL lines in all:
14
+ - an amount in euro × the exchange rate the text states ("2 000 000 euro × 4,3770 zł = 8 754 000,00 zł"); with
15
+ several different rates only where the sentence of the euro amount names exactly one;
16
+ - budget minus what was spent ("budżet 5 000,00 zł − wykorzystano 3 750,00 zł = 1 250,00 zł");
17
+ - quantity × unit price ("3 × 465,50 zł = 1 396,50 zł") and the total of the lines of one list;
18
+ - a quantity-tiered price list: the tier the ordered quantity falls in and its value ("20 ≤ 98 ≤ 99; 98 × 156,60 zł
19
+ = 15 346,80 zł"), plus the delivery fee the text names ("15 346,80 zł + 39,00 zł = 15 385,80 zł");
20
+ - net/gross of the amounts the text labels "netto"/"brutto" (and of computed totals), for the one VAT rate stated,
21
+ where the VAT line above does not already give it ("26 016,26 zł netto × 1,23 = 32 000,00 zł brutto");
22
+ - comparisons of those amounts with each other and with the other zł amounts of the text (at most MAX_COMPARE;
23
+ unit prices, fees, rates and the operands of a remainder are left out): "9 654 410,27 zł > 8 754 000,00 zł".
24
+ Symbols only (>, <, =): never "przekracza", "mieści się", "w terminie" — which amount matters is the model's call.
25
+
26
+ from basal.facts import inject
27
+ state2 = inject(state) # the same function adds the facts in training
28
+ """
29
+ import re
30
+ from bisect import bisect_left, bisect_right
31
+ from datetime import date, timedelta
32
+ from decimal import ROUND_HALF_UP, Decimal, localcontext
33
+
34
+ MONTHS = ["stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca", "lipca", "sierpnia", "września",
35
+ "października", "listopada", "grudnia"]
36
+ WEEKDAYS = ["poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota", "niedziela"]
37
+ HEADER = "Fakty pomocnicze (wyliczone automatycznie, bez oceny prawnej):"
38
+ MAX_DATES, MAX_DURATIONS, MAX_AMOUNTS = 6, 3, 3
39
+ MAX_CHARS = 1_000_000 # basal-serve's "facts": "auto" reads a state of at most this many characters (HTTP 422 beyond)
40
+
41
+ DATE_TXT = re.compile(r"\b(\d{1,2}) (" + "|".join(MONTHS) + r") (\d{4})(?: r\.)?")
42
+ DATE_NUM = re.compile(r"\b(\d{1,2})\.(\d{1,2})\.(\d{4})\b")
43
+ DATE_ISO = re.compile(r"\b(\d{4})-(\d{2})-(\d{2})\b")
44
+ DURATION = re.compile(r"\b(\d{1,3}) (dni|dnia|dzień|tygodni|tygodnie|tydzień|miesięcy|miesiące|miesiąc|lat|lata|rok)\b")
45
+ DUR_WORD = re.compile(r"\b(tydzień|tygodnia|miesiąc|miesiąca|rok|roku)\b")
46
+ YEAR_BEFORE = re.compile(r"\d{4}(?:-\d{2}-\d{2})?\s+$") # "2025 roku", "2025-03-03 roku": part of a date
47
+ AGO = re.compile(r"\b(\d{1,3}) (dni|dzień) temu\b")
48
+ TODAY = re.compile(r"\b(?:[Dd]ziś|[Dd]zisiaj)(?: jest| mamy|:)? ")
49
+ # every space separator (Unicode Zs: NBSP, the en / em / figure / thin / hair spaces, the narrow NBSP, ...): a
50
+ # thousands separator, or the gap between an amount and its currency
51
+ ZS = r"[ \u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]"
52
+ # Not the start of an amount: a digit group whose group before it is itself a group of the same run ("… 111 111").
53
+ # The run's earlier group reads the same groups to the same end, so the amount was found there or does not exist;
54
+ # without this, every group of a long run with no "zł" after it rescanned the run to its end (quadratic: 40 kB of
55
+ # "111 " took 14 s).
56
+ IN_RUN = r"(?!(?<=" + ZS + r"\d{3}" + ZS + r")\d{3})" # (every pattern's groups: ZS)
57
+ AMOUNT = re.compile(r"(?<![\d,.])\b(" + IN_RUN + r"\d{1,3}(?:" + ZS + r"\d{3})+(?:,\d{2})?"
58
+ r"|\d{1,3}(?:\.\d{3})+(?:,\d{2})?|\d+(?:,\d{2})?)" + ZS + r"zł\b")
59
+ VAT = re.compile(r"(?<![\d,.])\b(23|8|5) ?%")
60
+ VAT_CTX = re.compile(r"\bVAT\b|\bpodat\w* od towarów")
61
+
62
+ # money arithmetic
63
+ MAX_TOTAL, MAX_COMPARE, MAX_PLAIN, MAX_EURO = 12, 6, 3, 3
64
+ AMT = IN_RUN + r"\d{1,3}(?:" + ZS + r"\d{3})*(?:,\d{2})?"
65
+ STATED = re.compile(r"(?<![\d,.])\b(" + IN_RUN + r"\d{1,3}(?:" + ZS + r"\d{3})+(?:,\d{2})?"
66
+ r"|\d{1,3}(?:\.\d{3})+(?:,\d{2})?|\d+(?:,\d{2})?)" + ZS + r"?(?:zł|PLN)\b")
67
+ EURO_AMT = r"(?<![\d,])\b(" + IN_RUN + r"\d{1,3}(?:" + ZS + r"\d{3})*(?:,\d{1,2})?)" + ZS + r"?(?:euro\b|EUR\b|€)"
68
+ EURO = re.compile(EURO_AMT)
69
+ RATE = r"(\d{1,2},\d{2,4})" + ZS + r"?(?:zł|PLN)\b"
70
+ RATE_ANY = re.compile(r"(?<![\d,])\b" + RATE)
71
+ RATE_PER = re.compile(r"(?<![\d,])\b" + RATE + ZS + r"?(?:za|/)" + ZS + r"?(?:1" + ZS + r")?(?:euro\b|EUR\b|€)")
72
+ RATE_EQ = re.compile(r"\b1" + ZS + r"?(?:euro\b|EUR\b|€)" + ZS + r"?=" + ZS + r"?" + RATE)
73
+ EURO_X_RATE = re.compile(EURO_AMT + ZS + r"?[×*]" + ZS + r"?" + RATE)
74
+ KURS = re.compile(r"\b[Kk]urs\w*")
75
+ BOUND = re.compile(r"[.;!?](?=\s+[A-ZĄĆĘŁŃÓŚŹŻ„\"(])|\n")
76
+ LABEL = re.compile(ZS + r"?\(?(netto|brutto)\b")
77
+ BUDGET = re.compile(r"\b[Bb]udżet\w*")
78
+ USED = re.compile(r"\b(wykorzystano|wydano|wydatkowano|zużyto|zaangażowano|rozdysponowano)\b")
79
+ UNIT = r"(?:szt\.|sztuk[ia]?|usł\.|godz\.|kg|op\.|opak\.|kpl\.|os\.)"
80
+ PRODUCT = re.compile(r"(?<![\d,])(?<!\d" + ZS + r")\b(\d{1,4})" + ZS + r"?(?:" + UNIT + ZS + r"?)?×" + ZS + r"?(?=\d)")
81
+ TIER = re.compile(r"(?<![\d,])\b(" + AMT + r") zł(?: netto| brutto)?(?: za (?:sztukę|szt\.))?(?: przy (?:zamówieniu|zakupie))?"
82
+ r" (poniżej|do|od|powyżej|co najmniej|min\.) (\d{1,5})"
83
+ r"(?: do (\d{1,5})|" + ZS + r"?[–-]" + ZS + r"?(\d{1,5}))? (?:szt\.|sztuk)")
84
+ QTY = re.compile(r"(?<![\d,])(?<!\d" + ZS + r")\b(\d{1,5})" + ZS + r"(?:szt\.|sztuk[ia]?\b)")
85
+ QTY_PRE = ("poniżej ", "od ", "do ", "powyżej ", "najmniej ", "min. ", "–", "-")
86
+ EQ_NEXT = re.compile(r"\s*=") # "1 EUR =": the euro of a rate
87
+ TIMES_NEXT = re.compile(ZS + r"?×") # "5 szt. × 12,00 zł": a product line, not the ordered quantity
88
+ FEE = re.compile(r"\b(?:[Dd]ostawa|[Ww]ysyłka|[Tt]ransport|[Pp]rzesyłka|[Kk]oszty? (?:dostawy|wysyłki|transportu|przesyłki))\b")
89
+
90
+
91
+ def _easter(y):
92
+ a, b, c = y % 19, y // 100, y % 100
93
+ d, e = b // 4, b % 4
94
+ f = (b + 8) // 25
95
+ g = (b - f + 1) // 3
96
+ h = (19 * a + b - d - g + 15) % 30
97
+ i, k = c // 4, c % 4
98
+ l = (32 + 2 * e + 2 * i - h - k) % 7
99
+ m = (a + 11 * h + 22 * l) // 451
100
+ mo = (h + l - 7 * m + 114) // 31
101
+ return date(y, mo, (h + l - 7 * m + 114) % 31 + 1)
102
+
103
+
104
+ def holidays(y):
105
+ """Statutory days off in Poland (ustawa z 18 stycznia 1951 r.; 24 December from 2025)."""
106
+ e = _easter(y)
107
+ h = {date(y, 1, 1): "Nowy Rok", date(y, 1, 6): "Trzech Króli", e: "Wielkanoc",
108
+ e + timedelta(days=1): "Poniedziałek Wielkanocny", date(y, 5, 1): "Święto Pracy",
109
+ date(y, 5, 3): "Święto Konstytucji 3 Maja", e + timedelta(days=49): "Zielone Świątki",
110
+ e + timedelta(days=60): "Boże Ciało", date(y, 8, 15): "Wniebowzięcie NMP",
111
+ date(y, 11, 1): "Wszystkich Świętych", date(y, 11, 11): "Święto Niepodległości",
112
+ date(y, 12, 25): "Boże Narodzenie", date(y, 12, 26): "drugi dzień Bożego Narodzenia"}
113
+ if y >= 2025:
114
+ h[date(y, 12, 24)] = "Wigilia Bożego Narodzenia"
115
+ return h
116
+
117
+
118
+ def fmt(d):
119
+ return f"{d.day} {MONTHS[d.month - 1]} {d.year} r."
120
+
121
+
122
+ def add_months(d, k):
123
+ y, m = divmod(d.year * 12 + d.month - 1 + k, 12)
124
+ m += 1
125
+ last = (date(y + (m == 12), m % 12 + 1, 1) - timedelta(days=1)).day
126
+ return date(y, m, min(d.day, last))
127
+
128
+
129
+ def _dates(text):
130
+ """Dates in order of first appearance, deduplicated."""
131
+ found = []
132
+ for rx, conv in ((DATE_TXT, lambda g: (int(g[2]), MONTHS.index(g[1]) + 1, int(g[0]))),
133
+ (DATE_NUM, lambda g: (int(g[2]), int(g[1]), int(g[0]))),
134
+ (DATE_ISO, lambda g: (int(g[0]), int(g[1]), int(g[2])))):
135
+ for m in rx.finditer(text):
136
+ try:
137
+ found.append((m.start(), date(*conv(m.groups()))))
138
+ except ValueError:
139
+ pass
140
+ return list(dict.fromkeys(d for _, d in sorted(found)))
141
+
142
+
143
+ def _durations(text):
144
+ out = {} # (n, unit) in order of first appearance
145
+ for m in DURATION.finditer(text):
146
+ n, u = int(m.group(1)), m.group(2)
147
+ unit = "d" if u.startswith("d") else "w" if u.startswith("ty") else "m" if u.startswith("mie") else "y"
148
+ if not text[m.end():m.end() + 5].startswith(" temu"):
149
+ out.setdefault((n, unit))
150
+ for m in DUR_WORD.finditer(text): # "w terminie tygodnia", "miesiąca", "roku" = 1 unit
151
+ if YEAR_BEFORE.search(text[max(0, m.start() - 20):m.start()]):
152
+ continue
153
+ out.setdefault((1, {"ty": "w", "mi": "m", "ro": "y"}[m.group(1)[:2]]))
154
+ return list(out)[:MAX_DURATIONS]
155
+
156
+
157
+ def _plus(d, n, unit):
158
+ """d + n units, or None when the result is outside date.min..date.max (year 1..9999)."""
159
+ try:
160
+ if unit == "d":
161
+ return d + timedelta(days=n)
162
+ if unit == "w":
163
+ return d + timedelta(weeks=n)
164
+ if unit == "m":
165
+ return add_months(d, n)
166
+ try:
167
+ return d.replace(year=d.year + n)
168
+ except ValueError:
169
+ return d.replace(year=d.year + n, day=28)
170
+ except (OverflowError, ValueError):
171
+ return None
172
+
173
+
174
+ UNIT_PL = {"d": ("dzień", "dni"), "w": ("tydzień", "tygodnie"), "m": ("miesiąc", "miesiące"), "y": ("rok", "lata")}
175
+
176
+
177
+ def _pl_amount(x):
178
+ with localcontext() as c: # long amounts (> 26 digits) would exceed the default precision of quantize
179
+ c.prec = 60
180
+ q = x.quantize(Decimal("0.01"), ROUND_HALF_UP)
181
+ s = f"{q:,.2f}".replace(",", " ").replace(".", ",")
182
+ return f"{s} zł"
183
+
184
+
185
+ def _dec(raw):
186
+ return Decimal(re.sub(ZS, "", raw).replace(".", "").replace(",", "."))
187
+
188
+
189
+ def _q(x):
190
+ with localcontext() as c:
191
+ c.prec = 60
192
+ return x.quantize(Decimal("0.01"), ROUND_HALF_UP)
193
+
194
+
195
+ def _pl_num(x):
196
+ """A number in Polish notation without a unit: 2 000 000, 139 000,50."""
197
+ s = f"{x:,.0f}" if x == x.to_integral_value() else f"{_q(x):,.2f}"
198
+ return s.replace(",", " ").replace(".", ",")
199
+
200
+
201
+ def _cut(text, a, n):
202
+ """Window of n characters from a, up to the end of the sentence."""
203
+ w = text[a:a + n]
204
+ b = BOUND.search(w)
205
+ return w[:b.start()] if b else w
206
+
207
+
208
+ def _rates(text):
209
+ """Exchange rates the text states, as [(position, "4,3770")] (1 < rate < 10): "kurs … 4,3770 zł", "4,2586 zł za
210
+ 1 euro", "1 EUR = 4,31 zł", "216 000 euro × 4,31 zł"; and the explicit euro × rate pairs {euro position: rate}."""
211
+ rates = []
212
+ for m in KURS.finditer(text):
213
+ rates += [(m.end() + r.start(1), r.group(1)) for r in RATE_ANY.finditer(_cut(text, m.end(), 160))]
214
+ for rx in (RATE_PER, RATE_EQ):
215
+ rates += [(m.start(1), m.group(1)) for m in rx.finditer(text)]
216
+ explicit = {m.start(1): (m.start(2), m.group(2)) for m in EURO_X_RATE.finditer(text)}
217
+ rates += list(explicit.values())
218
+ rates = [(p, r) for p, r in rates if 1 < _dec(r) < 10]
219
+ kept = set(rates)
220
+ return rates, {k: v for k, v in explicit.items() if v in kept}
221
+
222
+
223
+ def _vat_rates(text):
224
+ """The VAT rates a text states: 23, 8 or 5% (not a decimal like 13,5%) with "VAT" or "podatek od towarów (i usług)"
225
+ in the same sentence; "5% wartości przedmiotu sporu" or "stopa referencyjna 5%" is not a VAT rate."""
226
+ bounds = [m.start() for m in BOUND.finditer(text)]
227
+ ctx = [(m.start(), m.end()) for m in VAT_CTX.finditer(text)] # (they cannot overlap: these are all of them)
228
+ has = {} # sentence -> it names VAT (a context match lies inside it)
229
+ out = set()
230
+ for m in VAT.finditer(text):
231
+ i = bisect_left(bounds, m.start())
232
+ if i not in has:
233
+ a, b = bounds[i - 1] + 1 if i else 0, bounds[i] if i < len(bounds) else len(text)
234
+ j = bisect_left(ctx, (a,))
235
+ has[i] = j < len(ctx) and ctx[j][1] <= b
236
+ if has[i]:
237
+ out.add(int(m.group(1)))
238
+ return out
239
+
240
+
241
+ def _money(text, covered):
242
+ """Money arithmetic of a state: (computation lines, comparison lines). `covered`: amounts whose net/gross the VAT
243
+ line of facts() already gives."""
244
+ bounds = [m.start() for m in BOUND.finditer(text)]
245
+
246
+ def sent(pos):
247
+ return bisect_left(bounds, pos)
248
+
249
+ # stated zł amounts; use: None (free), "rate", "alias" (a stated equivalent of a conversion), "op" (an operand:
250
+ # unit price, fee, budget, spending), "subj" (a labelled amount or a lone line price, compared via the pool)
251
+ st = [dict(s=m.start(), v=_dec(m.group(1)), use=None, lab=(LABEL.match(text, m.end()) or [None, None])[1])
252
+ for m in STATED.finditer(text)]
253
+ at = {a["s"]: a for a in st} # (in text order: lookups by position, not scans of every amount per lookup)
254
+ starts = [a["s"] for a in st]
255
+
256
+ def stated_at(pos):
257
+ return at.get(pos)
258
+
259
+ def first_free(a, n):
260
+ lim = a + len(_cut(text, a, n))
261
+ for i in range(bisect_left(starts, a), bisect_left(starts, lim)):
262
+ if st[i]["use"] is None:
263
+ return st[i]
264
+ return None
265
+
266
+ calc, refs, subjects = [], [], []
267
+
268
+ # 1. euro × the stated exchange rate
269
+ rates, explicit = _rates(text)
270
+ for p, _ in rates:
271
+ a = stated_at(p)
272
+ if a:
273
+ a["use"] = "rate"
274
+ distinct = {}
275
+ for _, r in rates:
276
+ distinct.setdefault(_dec(r), r)
277
+ eur, seen = [], set()
278
+ for m in EURO.finditer(text):
279
+ if text[max(0, m.start() - 3):m.start()] == "za " or EQ_NEXT.match(text, m.end()):
280
+ continue # the "za 1 euro" / "1 EUR =" of a rate
281
+ if _dec(m.group(1)) not in seen:
282
+ seen.add(_dec(m.group(1)))
283
+ eur.append((m.start(), _dec(m.group(1))))
284
+ for p, v in eur[:MAX_EURO]:
285
+ if p in explicit:
286
+ r = explicit[p][1]
287
+ elif len(distinct) == 1:
288
+ r = next(iter(distinct.values()))
289
+ else:
290
+ near = {_dec(r): r for pos, r in rates if sent(pos) == sent(p)}
291
+ if len(near) != 1:
292
+ continue
293
+ r = next(iter(near.values()))
294
+ c = _q(v * _dec(r))
295
+ calc.append(f"{_pl_num(v)} euro × {r} zł = {_pl_amount(c)}")
296
+ for a in st:
297
+ if a["use"] is None and a["v"] == c and sent(a["s"]) == sent(p):
298
+ a["use"] = "alias"
299
+ refs.append(c)
300
+
301
+ # 2. budget minus spending
302
+ m = BUDGET.search(text)
303
+ b = first_free(m.end(), 80) if m else None
304
+ if b:
305
+ used, taken = [], set()
306
+ for u in USED.finditer(text):
307
+ x = first_free(u.end(), 40) if sent(u.start()) in (sent(b["s"]), sent(b["s"]) + 1) else None
308
+ if x and x is not b and x["s"] not in taken:
309
+ used.append((u.group(1), x))
310
+ taken.add(x["s"])
311
+ if used:
312
+ r = b["v"] - sum(x["v"] for _, x in used)
313
+ calc.append(f"budżet {_pl_amount(b['v'])} − " + " − ".join(f"{w} {_pl_amount(x['v'])}" for w, x in used)
314
+ + f" = {_pl_amount(r)}")
315
+ for x in [b] + [x for _, x in used]:
316
+ x["use"] = "op"
317
+ refs.append(_q(r))
318
+
319
+ # 3. quantity × unit price, and the total of the lines of one list (one sentence)
320
+ lists = {}
321
+ for m in PRODUCT.finditer(text):
322
+ a = stated_at(m.end())
323
+ if a and a["use"] is None and int(m.group(1)) > 0:
324
+ lists.setdefault(sent(m.start()), []).append((int(m.group(1)), a))
325
+ for items in list(lists.values())[:2]:
326
+ items = items[:5]
327
+ labs = {a["lab"] for _, a in items}
328
+ lab = labs.pop() if len(labs) == 1 else None
329
+ if len(items) == 1 and items[0][0] == 1: # "1 szt. × P": the price is the total
330
+ items[0][1]["use"] = "subj"
331
+ subjects.append((items[0][1]["v"], lab, items[0][1]))
332
+ continue
333
+ tots = []
334
+ for n, a in items:
335
+ if n > 1:
336
+ calc.append(f"{n} × {_pl_amount(a['v'])} = {_pl_amount(n * a['v'])}")
337
+ tots.append(n * a["v"])
338
+ a["use"] = "op"
339
+ if len(tots) > 1:
340
+ calc.append(" + ".join(_pl_amount(t) for t in tots) + f" = {_pl_amount(sum(tots))}")
341
+ subjects.append((sum(tots), lab, None))
342
+
343
+ # 4. a quantity-tiered price list and the ordered quantity
344
+ tiers = list(TIER.finditer(text))
345
+ if len(tiers) >= 2:
346
+ spans = [(m.start(), m.end()) for m in tiers]
347
+
348
+ def in_tier(pos):
349
+ i = bisect_right(spans, (pos, float("inf"))) - 1
350
+ return i >= 0 and pos < spans[i][1]
351
+ qs = {int(m.group(1)) for m in QTY.finditer(text)
352
+ if not in_tier(m.start()) and not TIMES_NEXT.match(text, m.end())
353
+ and not text.endswith(QTY_PRE, 0, m.start())}
354
+ if len(qs) == 1:
355
+ q, hits = qs.pop(), []
356
+ for m in tiers:
357
+ kind, x, y = m.group(2), int(m.group(3)), m.group(4) or m.group(5)
358
+ if kind == "poniżej":
359
+ ok, cond = q < x, f"{q} < {x}"
360
+ elif kind == "do":
361
+ ok, cond = q <= x, f"{q} ≤ {x}"
362
+ elif kind == "powyżej":
363
+ ok, cond = q > x, f"{q} > {x}"
364
+ elif y:
365
+ ok, cond = x <= q <= int(y), f"{x} ≤ {q} ≤ {y}"
366
+ else:
367
+ ok, cond = q >= x, f"{q} ≥ {x}"
368
+ if ok:
369
+ hits.append((cond, _dec(m.group(1))))
370
+ if len(hits) == 1:
371
+ cond, p = hits[0]
372
+ calc.append(f"{cond}; {q} × {_pl_amount(p)} = {_pl_amount(q * p)}")
373
+ subjects.append((q * p, None, None))
374
+ for m in tiers:
375
+ a = stated_at(m.start(1))
376
+ if a and a["use"] is None:
377
+ a["use"] = "op"
378
+
379
+ # 5. the delivery fee added to the one total
380
+ if len(subjects) == 1:
381
+ for m in FEE.finditer(text):
382
+ f = first_free(m.end(), 30)
383
+ if f:
384
+ t = subjects[0][0]
385
+ calc.append(f"{_pl_amount(t)} + {_pl_amount(f['v'])} = {_pl_amount(t + f['v'])}")
386
+ f["use"] = "op"
387
+ break
388
+
389
+ # 6. net/gross of the labelled amounts and totals, for the one VAT rate stated
390
+ for a in st:
391
+ if a["use"] is None and a["lab"]:
392
+ a["use"] = "subj"
393
+ subjects.append((a["v"], a["lab"], a))
394
+ vr = _vat_rates(text)
395
+ k = 1 + Decimal(vr.pop()) / 100 if len(vr) == 1 else None
396
+ pool = [] # (value, kind 0 subject / 1 other stated amount / 2 reference, group: no comparison inside a group)
397
+ for g, (v, lab, src) in enumerate(subjects):
398
+ pool.append((_q(v), 0, g))
399
+ if k and lab:
400
+ kk = str(k).replace(".", ",")
401
+ d = v * k if lab == "netto" else v / k
402
+ if src is None or src["v"] not in covered:
403
+ calc.append(f"{_pl_amount(v)} {lab} {'×' if lab == 'netto' else '÷'} {kk} = {_pl_amount(d)} "
404
+ f"{'brutto' if lab == 'netto' else 'netto'}")
405
+ pool.append((_q(d), 0, g))
406
+ pool += [(v, 2, -1 - i) for i, v in enumerate(refs)]
407
+ pool += [(a["v"], 1, -100 - i) for i, a in enumerate(st) if a["use"] is None]
408
+
409
+ # 7. comparisons (symbols only)
410
+ first = {}
411
+ for x in pool:
412
+ first.setdefault((x[0], x[1]), x) # the first of each (value, kind), in pool order
413
+ uniq = list(first.values())
414
+ comps = []
415
+ for _, i, j in _first_pairs(uniq, MAX_COMPARE):
416
+ x, y = (uniq[i], uniq[j]) if uniq[i][1] <= uniq[j][1] else (uniq[j], uniq[i])
417
+ op = ">" if x[0] > y[0] else "<" if x[0] < y[0] else "="
418
+ comps.append(f"{_pl_amount(x[0])} {op} {_pl_amount(y[0])}")
419
+ return calc, comps
420
+
421
+
422
+ def _first_pairs(uniq, k):
423
+ """The first k of the sorted (n, i, j), i < j, n = how many of the two are other stated amounts (kind 1), of the
424
+ pairs of different groups (pairs of two kind-1 amounts only when there are at most MAX_PLAIN of them), without
425
+ building every pair: a text with thousands of amounts made all of their pairs (quadratic time and memory)."""
426
+ plain = [i for i, x in enumerate(uniq) if x[1] == 1]
427
+ other = [i for i, x in enumerate(uniq) if x[1] != 1]
428
+ out = []
429
+ for n in (0, 1, 2):
430
+ if n == 2 and len(plain) > MAX_PLAIN:
431
+ break
432
+ for i, x in enumerate(uniq):
433
+ need = n - (x[1] == 1) # how many kind-1 amounts j adds
434
+ if need not in (0, 1):
435
+ continue
436
+ js = plain if need else other
437
+ for t in range(bisect_right(js, i), len(js)):
438
+ j = js[t]
439
+ if x[2] != uniq[j][2]:
440
+ out.append((n, i, j))
441
+ if len(out) == k:
442
+ return out
443
+ return out
444
+
445
+
446
+ def facts(text):
447
+ """The helper facts for a state, as a list of lines (empty if nothing to compute)."""
448
+ lines = []
449
+ ds = _dates(text)[:MAX_DATES]
450
+ for d in ds:
451
+ tag = WEEKDAYS[d.weekday()]
452
+ h = holidays(d.year).get(d)
453
+ if h:
454
+ tag += f"; dzień ustawowo wolny od pracy ({h})"
455
+ lines.append(f"{fmt(d)} to {tag}")
456
+ for a, b in zip(ds, ds[1:]):
457
+ n = (b - a).days
458
+ lines.append(f"Od {fmt(a)} do {fmt(b)}: {abs(n)} dni ({'później' if n >= 0 else 'wcześniej'})")
459
+ m = TODAY.search(text)
460
+ if m:
461
+ today = _dates(text[m.end():m.end() + 40])
462
+ if today:
463
+ for n in list(dict.fromkeys(int(g.group(1)) for g in AGO.finditer(text)))[:MAX_DURATIONS]:
464
+ try:
465
+ before = today[0] - timedelta(days=n)
466
+ except OverflowError: # before year 1: no fact rather than an HTTP 500
467
+ continue
468
+ lines.append(f"{n} dni przed {fmt(today[0])} to {fmt(before)}")
469
+ durs = _durations(text)
470
+ for d in ds[:3]:
471
+ for n, unit in durs:
472
+ one, many = UNIT_PL[unit]
473
+ end = _plus(d, n, unit)
474
+ if end is None: # outside year 1..9999: no fact rather than an HTTP 500
475
+ continue
476
+ lines.append(f"{fmt(d)} + {n} {one if n == 1 else many} (kalendarzowo) = {fmt(end)} "
477
+ f"({WEEKDAYS[end.weekday()]})")
478
+ rates = sorted(_vat_rates(text), reverse=True)
479
+ covered = set()
480
+ rate_at = {p for p, _ in _rates(text)[0]} # an exchange rate is not an amount to put VAT on
481
+ for raw in [m.group(1) for m in AMOUNT.finditer(text) if m.start() not in rate_at][:MAX_AMOUNTS]:
482
+ x = _dec(raw)
483
+ for r in rates:
484
+ k = 1 + Decimal(r) / 100
485
+ kk = str(k).replace(".", ",")
486
+ lines.append(f"{_pl_amount(x)} × {kk} = {_pl_amount(x * k)}; {_pl_amount(x)} ÷ {kk} = {_pl_amount(x / k)}")
487
+ covered.add(x)
488
+ calc, comps = _money(text, covered)
489
+ room = max(0, MAX_TOTAL - len(lines))
490
+ calc = calc[:room]
491
+ return lines + calc + comps[:min(MAX_COMPARE, room - len(calc))]
492
+
493
+
494
+ def inject(state):
495
+ """State with the helper facts appended (unchanged if there is nothing to compute)."""
496
+ ls = facts(state)
497
+ return state if not ls else state + "\n\n" + HEADER + "\n" + "\n".join(f"- {x}" for x in ls)