perucompras-cli 0.1.0__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.
- perucompras_cli-0.1.0.dist-info/METADATA +429 -0
- perucompras_cli-0.1.0.dist-info/RECORD +50 -0
- perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
- perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
- perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
- piloto_ai_cli/__init__.py +51 -0
- piloto_ai_cli/__main__.py +5 -0
- piloto_ai_cli/api.py +394 -0
- piloto_ai_cli/attribute_text.py +106 -0
- piloto_ai_cli/attributes_service.py +250 -0
- piloto_ai_cli/auto_tag.py +65 -0
- piloto_ai_cli/backoff.py +25 -0
- piloto_ai_cli/cards.py +871 -0
- piloto_ai_cli/cli.py +602 -0
- piloto_ai_cli/connectors.py +106 -0
- piloto_ai_cli/database.py +491 -0
- piloto_ai_cli/enrichment.py +557 -0
- piloto_ai_cli/errors.py +92 -0
- piloto_ai_cli/excel.py +186 -0
- piloto_ai_cli/extraction.py +1316 -0
- piloto_ai_cli/health.py +398 -0
- piloto_ai_cli/health_workflow.py +1060 -0
- piloto_ai_cli/http_client.py +610 -0
- piloto_ai_cli/llm_client.py +259 -0
- piloto_ai_cli/llm_extraction.py +444 -0
- piloto_ai_cli/llm_output.py +90 -0
- piloto_ai_cli/pane.py +303 -0
- piloto_ai_cli/parsers.py +477 -0
- piloto_ai_cli/payload_store.py +227 -0
- piloto_ai_cli/pdf_parser.py +12 -0
- piloto_ai_cli/py.typed +0 -0
- piloto_ai_cli/query_compiler.py +1112 -0
- piloto_ai_cli/query_result.py +175 -0
- piloto_ai_cli/query_service.py +199 -0
- piloto_ai_cli/reextract.py +129 -0
- piloto_ai_cli/review.py +217 -0
- piloto_ai_cli/rules.py +67 -0
- piloto_ai_cli/run_log.py +230 -0
- piloto_ai_cli/schema/__init__.py +25 -0
- piloto_ai_cli/schema/contract-v1.schema.json +261 -0
- piloto_ai_cli/schema/contract.py +257 -0
- piloto_ai_cli/schema/migration_filters.py +59 -0
- piloto_ai_cli/schema/models.py +747 -0
- piloto_ai_cli/schema/snowflake_autogen.py +134 -0
- piloto_ai_cli/search_form.py +82 -0
- piloto_ai_cli/settings.py +174 -0
- piloto_ai_cli/snowflake_url.py +90 -0
- piloto_ai_cli/stamp_service.py +53 -0
- piloto_ai_cli/sync.py +1157 -0
- piloto_ai_cli/unit_converter.py +81 -0
|
@@ -0,0 +1,1316 @@
|
|
|
1
|
+
"""Canonical extraction inputs for fichas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Callable, Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from datetime import UTC, datetime, timedelta
|
|
12
|
+
from decimal import ROUND_HALF_EVEN, Decimal, InvalidOperation
|
|
13
|
+
from typing import Protocol, cast
|
|
14
|
+
from uuid import uuid4
|
|
15
|
+
|
|
16
|
+
from sqlalchemy import case, or_, select, update
|
|
17
|
+
from sqlalchemy.exc import IntegrityError
|
|
18
|
+
from sqlalchemy.orm import Session
|
|
19
|
+
|
|
20
|
+
from piloto_ai_cli.attribute_text import normalize_label, split_key_value_text
|
|
21
|
+
from piloto_ai_cli.database import upsert
|
|
22
|
+
from piloto_ai_cli.errors import ContractError, InvalidExtractionInputError
|
|
23
|
+
from piloto_ai_cli.excel import ExcelFicha
|
|
24
|
+
from piloto_ai_cli.http_client import collect_logged_request_ids, set_logged_request_id
|
|
25
|
+
from piloto_ai_cli.llm_client import LLMConfigurationError, LLMRequestError, LLMResponse
|
|
26
|
+
from piloto_ai_cli.llm_extraction import (
|
|
27
|
+
AttributeProposal,
|
|
28
|
+
ParsedExtraction,
|
|
29
|
+
ValueSource,
|
|
30
|
+
build_llm_prompt,
|
|
31
|
+
parse_llm_response,
|
|
32
|
+
)
|
|
33
|
+
from piloto_ai_cli.parsers import Feature
|
|
34
|
+
from piloto_ai_cli.payload_store import PayloadIntegrityError, PayloadStore
|
|
35
|
+
from piloto_ai_cli.rules import rule_set_version
|
|
36
|
+
from piloto_ai_cli.schema.models import (
|
|
37
|
+
Alias,
|
|
38
|
+
Attribute,
|
|
39
|
+
AttributeScope,
|
|
40
|
+
Extraction,
|
|
41
|
+
ExtractionConfig,
|
|
42
|
+
Ficha,
|
|
43
|
+
FichaAttribute,
|
|
44
|
+
SeedValue,
|
|
45
|
+
UnitRule,
|
|
46
|
+
)
|
|
47
|
+
from piloto_ai_cli.unit_converter import UnitConverter
|
|
48
|
+
|
|
49
|
+
# A complete quantity: the number may not continue another number ("0,5",
|
|
50
|
+
# "1/2") and the unit must end at whitespace, punctuation or the end of the
|
|
51
|
+
# value ("kg/m²" and "m2" are not plain units), so fragments of unsupported
|
|
52
|
+
# formats are left to the LLM instead of being stored with full confidence.
|
|
53
|
+
_QUANTITY_RE = re.compile(
|
|
54
|
+
r"(?<![\w.,/\-–—])(?P<number>[+-]?(?:\d+(?:\.\d+)?|\.\d+))\s*"
|
|
55
|
+
r"(?P<unit>[^\d\s/,:;]+)(?=$|[\s,:;])"
|
|
56
|
+
)
|
|
57
|
+
# A range ("5-10 kg", "5 – 10 kg", "5 a 10 kg") is not one quantity.
|
|
58
|
+
_RANGE_RE = re.compile(r"\d\s*(?:[-–—]|\b(?:a|to|hasta)\b)\s*[+-]?\.?\d", re.IGNORECASE)
|
|
59
|
+
_CONFIDENCE = Decimal("1.0")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, slots=True)
|
|
63
|
+
class RuleResidue:
|
|
64
|
+
"""One source value that the deterministic rules pass could not resolve."""
|
|
65
|
+
|
|
66
|
+
label: str
|
|
67
|
+
value: str
|
|
68
|
+
source: ValueSource
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True, slots=True)
|
|
72
|
+
class RulesPassResult:
|
|
73
|
+
"""Values and unresolved source pairs returned by one rules pass."""
|
|
74
|
+
|
|
75
|
+
extraction_id: str
|
|
76
|
+
residue: tuple[RuleResidue, ...]
|
|
77
|
+
cached: bool
|
|
78
|
+
# The input this pass resolved; a later pass on the same residue must use it
|
|
79
|
+
# too, even if a sync has since committed a new input for the ficha.
|
|
80
|
+
input_hash: str
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# How long a pending LLM attempt counts as a live claim; a pending row older than
|
|
84
|
+
# this is an abandoned run (e.g. a killed process). The provider call itself is
|
|
85
|
+
# bounded by a deadline shorter than the claim (_CLAIM_CALL_SHARE of it), so a
|
|
86
|
+
# slow call (retries, Retry-After waits, waiting for a request slot) is cancelled
|
|
87
|
+
# and recorded as failed before another run may treat its claim as abandoned:
|
|
88
|
+
# never two paid calls for one cache key. The deadline counts from the claim's
|
|
89
|
+
# started_at, and an attempt whose write phase ends after the claim expired is
|
|
90
|
+
# recorded as failed instead of ok, so its rows never land beside a second
|
|
91
|
+
# claimant's. 15 min leaves the call 12 min, above
|
|
92
|
+
# the worst case of the default retry policy (4 attempts of 120 s plus backoff).
|
|
93
|
+
DEFAULT_LLM_CLAIM_EXPIRY = timedelta(minutes=15)
|
|
94
|
+
_CLAIM_CALL_SHARE = 0.8
|
|
95
|
+
|
|
96
|
+
_LOGGER = logging.getLogger(__name__)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class _ClaimDeadlineExceeded(Exception):
|
|
100
|
+
"""The provider call outlived the share of the claim expiry it may use."""
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True, slots=True)
|
|
104
|
+
class LLMPassResult:
|
|
105
|
+
"""Outcome of one LLM pass, or its skip/cache decision."""
|
|
106
|
+
|
|
107
|
+
extraction_id: str | None
|
|
108
|
+
status: str
|
|
109
|
+
cached: bool
|
|
110
|
+
reason: str | None = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass(frozen=True, slots=True)
|
|
114
|
+
class ReextractionResult:
|
|
115
|
+
"""The new rules pass and the LLM pass of one re-extracted ficha."""
|
|
116
|
+
|
|
117
|
+
rules: RulesPassResult
|
|
118
|
+
llm: LLMPassResult
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class LLMProvider(Protocol):
|
|
122
|
+
"""Minimal async provider interface required by the extraction service.
|
|
123
|
+
|
|
124
|
+
A provider sends the prompt through ``write_request()`` and returns the
|
|
125
|
+
model's answer as plain text with its token usage and logged request id;
|
|
126
|
+
any provider-specific envelope is unwrapped there. How the answer wraps
|
|
127
|
+
its JSON is handled by the provider-neutral ``parse_llm_response``.
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def provider(self) -> str:
|
|
132
|
+
"""The provider's name, recorded on each LLM extraction (e.g. ``anthropic``)."""
|
|
133
|
+
...
|
|
134
|
+
|
|
135
|
+
async def post_llm(self, prompt: str) -> LLMResponse: ...
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@dataclass(frozen=True, slots=True)
|
|
139
|
+
class _SourcePair:
|
|
140
|
+
label: str
|
|
141
|
+
value: str
|
|
142
|
+
source: ValueSource
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True, slots=True)
|
|
146
|
+
class _ResolvedMember:
|
|
147
|
+
value_number: Decimal | None
|
|
148
|
+
value_unit: str | None
|
|
149
|
+
value_text: str | None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class ExtractService:
|
|
153
|
+
"""Run deterministic rules and a logged, versioned LLM pass."""
|
|
154
|
+
|
|
155
|
+
def __init__(
|
|
156
|
+
self,
|
|
157
|
+
session: Session,
|
|
158
|
+
payload_store: PayloadStore,
|
|
159
|
+
*,
|
|
160
|
+
llm_client: LLMProvider | None = None,
|
|
161
|
+
input_usd_per_mtok: Decimal | None = None,
|
|
162
|
+
output_usd_per_mtok: Decimal | None = None,
|
|
163
|
+
claim_expiry: timedelta = DEFAULT_LLM_CLAIM_EXPIRY,
|
|
164
|
+
now: Callable[[], datetime] | None = None,
|
|
165
|
+
) -> None:
|
|
166
|
+
self._session = session
|
|
167
|
+
self._payload_store = payload_store
|
|
168
|
+
self._llm_client = llm_client
|
|
169
|
+
self._input_usd_per_mtok = input_usd_per_mtok
|
|
170
|
+
self._output_usd_per_mtok = output_usd_per_mtok
|
|
171
|
+
if claim_expiry <= timedelta(0):
|
|
172
|
+
raise ValueError("claim_expiry must be positive")
|
|
173
|
+
self._claim_expiry = claim_expiry
|
|
174
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
175
|
+
|
|
176
|
+
def rules_pass(self, ficha: Ficha) -> RulesPassResult:
|
|
177
|
+
"""Resolve recognized values and return all source pairs left for the LLM."""
|
|
178
|
+
return self._rules_pass(ficha, force=False)
|
|
179
|
+
|
|
180
|
+
async def reextract(self, ficha: Ficha) -> ReextractionResult:
|
|
181
|
+
"""Re-run both passes under the current rules, prompt and model (``pc reextract``).
|
|
182
|
+
|
|
183
|
+
Unlike :meth:`llm_pass`, an ``ok`` extraction under the same cache key is
|
|
184
|
+
not reused: each pass writes a new attempt (the next ``attempt`` under an
|
|
185
|
+
unchanged key, or attempt 1 under a new rule-set or prompt version), and
|
|
186
|
+
older attempts stay as history. The LLM is still called only for the
|
|
187
|
+
residue the new rules pass leaves, and a live pending claim by another
|
|
188
|
+
run is still respected. The transaction contract is that of
|
|
189
|
+
:meth:`llm_pass`.
|
|
190
|
+
|
|
191
|
+
Without an LLM client (no provider configured, e.g. the ``ci-mock``
|
|
192
|
+
profile), a ficha whose rules pass leaves residue keeps its new rules
|
|
193
|
+
attempt and reports LLM status ``unavailable`` instead of failing, so a
|
|
194
|
+
scope run goes on to the next ficha.
|
|
195
|
+
"""
|
|
196
|
+
rules = self._rules_pass(ficha, force=True)
|
|
197
|
+
if rules.residue and self._llm_client is None:
|
|
198
|
+
self._session.commit() # keep the rules pass, as _llm_pass does
|
|
199
|
+
return ReextractionResult(
|
|
200
|
+
rules,
|
|
201
|
+
LLMPassResult(
|
|
202
|
+
None,
|
|
203
|
+
"unavailable",
|
|
204
|
+
False,
|
|
205
|
+
reason="residue left but no LLM provider is configured",
|
|
206
|
+
),
|
|
207
|
+
)
|
|
208
|
+
llm = await self._llm_pass(ficha, rules, force=True)
|
|
209
|
+
return ReextractionResult(rules, llm)
|
|
210
|
+
|
|
211
|
+
def _read_input_payload(self, input_hash: str) -> bytes:
|
|
212
|
+
"""The stored input payload; a corrupt one is the ficha's own failure."""
|
|
213
|
+
return read_input_payload(self._payload_store, input_hash)
|
|
214
|
+
|
|
215
|
+
def _rules_pass(self, ficha: Ficha, *, force: bool) -> RulesPassResult:
|
|
216
|
+
if ficha.input_hash is None:
|
|
217
|
+
raise ValueError(f"ficha {ficha.ficha_id!r} has no current extraction input")
|
|
218
|
+
|
|
219
|
+
input_hash = ficha.input_hash
|
|
220
|
+
canonical_input = _read_canonical_input(self._read_input_payload(input_hash))
|
|
221
|
+
version = rule_set_version(self._session)
|
|
222
|
+
aliases = self._session.scalars(select(Alias).where(Alias.status == "accepted")).all()
|
|
223
|
+
attributes = self._session.scalars(
|
|
224
|
+
select(Attribute).where(Attribute.status == "accepted")
|
|
225
|
+
).all()
|
|
226
|
+
attribute_by_id = {attribute.attribute_id: attribute for attribute in attributes}
|
|
227
|
+
aliases_by_label = {
|
|
228
|
+
normalize_label(alias.raw_label): alias.attribute_id
|
|
229
|
+
for alias in aliases
|
|
230
|
+
if alias.attribute_id in attribute_by_id
|
|
231
|
+
}
|
|
232
|
+
category = _input_category(canonical_input)
|
|
233
|
+
seeds = self._session.scalars(select(SeedValue).where(SeedValue.category == category)).all()
|
|
234
|
+
# A merge family shares its seeds: they are keyed by the family's live
|
|
235
|
+
# attribute, as the LLM pass shows them, so seeds written under either
|
|
236
|
+
# a merged attribute or the attribute it was merged into are used.
|
|
237
|
+
live = self._live_attributes()
|
|
238
|
+
|
|
239
|
+
def family(attribute_id: str) -> str:
|
|
240
|
+
root = live.get(attribute_id)
|
|
241
|
+
return root.attribute_id if root is not None else attribute_id
|
|
242
|
+
|
|
243
|
+
seed_values: dict[str, dict[str, str]] = {}
|
|
244
|
+
for seed in seeds:
|
|
245
|
+
seed_values.setdefault(family(seed.attribute_id), {})[
|
|
246
|
+
_normalize_value(seed.raw_value)
|
|
247
|
+
] = seed.raw_value
|
|
248
|
+
|
|
249
|
+
unit_rules = self._session.scalars(
|
|
250
|
+
select(UnitRule).where(UnitRule.status == "accepted")
|
|
251
|
+
).all()
|
|
252
|
+
converter = UnitConverter(unit_rules)
|
|
253
|
+
accepted_units = {rule.raw_unit: rule.raw_unit for rule in unit_rules}
|
|
254
|
+
spellings = {rule.raw_unit for rule in unit_rules}
|
|
255
|
+
accepted_units_folded = {
|
|
256
|
+
unit.casefold(): unit
|
|
257
|
+
for unit in spellings
|
|
258
|
+
if sum(other.casefold() == unit.casefold() for other in spellings) == 1
|
|
259
|
+
}
|
|
260
|
+
pairs = _source_pairs(canonical_input, tuple(aliases_by_label))
|
|
261
|
+
residue: list[RuleResidue] = []
|
|
262
|
+
resolved_by_attribute: dict[str, list[tuple[_ResolvedMember, _SourcePair]]] = {}
|
|
263
|
+
|
|
264
|
+
for pair in pairs:
|
|
265
|
+
attribute_id = aliases_by_label.get(normalize_label(pair.label))
|
|
266
|
+
attribute = attribute_by_id.get(attribute_id or "")
|
|
267
|
+
if attribute is None:
|
|
268
|
+
residue.append(RuleResidue(pair.label, pair.value, pair.source))
|
|
269
|
+
continue
|
|
270
|
+
members = _resolve_members(
|
|
271
|
+
attribute,
|
|
272
|
+
pair.value,
|
|
273
|
+
seed_values.get(family(attribute.attribute_id), {}),
|
|
274
|
+
converter,
|
|
275
|
+
category,
|
|
276
|
+
accepted_units,
|
|
277
|
+
accepted_units_folded,
|
|
278
|
+
)
|
|
279
|
+
if members is None:
|
|
280
|
+
residue.append(RuleResidue(pair.label, pair.value, pair.source))
|
|
281
|
+
continue
|
|
282
|
+
previous = resolved_by_attribute.get(attribute.attribute_id)
|
|
283
|
+
if previous is not None and attribute.kind != "set":
|
|
284
|
+
previous_values = [
|
|
285
|
+
(member.value_number, member.value_unit, member.value_text)
|
|
286
|
+
for member, _ in previous
|
|
287
|
+
]
|
|
288
|
+
current_values = [
|
|
289
|
+
(member.value_number, member.value_unit, member.value_text)
|
|
290
|
+
for member in members
|
|
291
|
+
]
|
|
292
|
+
if current_values != previous_values:
|
|
293
|
+
residue.append(RuleResidue(pair.label, pair.value, pair.source))
|
|
294
|
+
continue
|
|
295
|
+
if attribute.kind == "set":
|
|
296
|
+
seen = {
|
|
297
|
+
(member.value_number, member.value_unit, member.value_text)
|
|
298
|
+
for member, _ in previous or []
|
|
299
|
+
}
|
|
300
|
+
unique_members: list[_ResolvedMember] = []
|
|
301
|
+
for member in members:
|
|
302
|
+
key = (member.value_number, member.value_unit, member.value_text)
|
|
303
|
+
if key not in seen:
|
|
304
|
+
seen.add(key)
|
|
305
|
+
unique_members.append(member)
|
|
306
|
+
members = unique_members
|
|
307
|
+
if not members:
|
|
308
|
+
continue
|
|
309
|
+
resolved_by_attribute.setdefault(attribute.attribute_id, []).extend(
|
|
310
|
+
(member, pair) for member in members
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
# A forced pass (re-extraction) never reuses an earlier attempt.
|
|
314
|
+
cached_extraction = (
|
|
315
|
+
None
|
|
316
|
+
if force
|
|
317
|
+
else self._session.scalar(
|
|
318
|
+
select(Extraction)
|
|
319
|
+
.where(
|
|
320
|
+
Extraction.ficha_id == ficha.ficha_id,
|
|
321
|
+
Extraction.input_hash == input_hash,
|
|
322
|
+
Extraction.model == "rules",
|
|
323
|
+
Extraction.prompt_version == version,
|
|
324
|
+
Extraction.status == "ok",
|
|
325
|
+
)
|
|
326
|
+
.order_by(Extraction.attempt.desc())
|
|
327
|
+
.limit(1)
|
|
328
|
+
)
|
|
329
|
+
)
|
|
330
|
+
if cached_extraction is not None:
|
|
331
|
+
# Seeds can change without changing the cache key. Anything resolved
|
|
332
|
+
# now but absent from the cached extraction was never persisted, so
|
|
333
|
+
# it stays residue for the LLM pass instead of being lost.
|
|
334
|
+
# Compare complete typed members, so a set that gained a member
|
|
335
|
+
# keeps the source pair of the missing member in the residue.
|
|
336
|
+
persisted = {
|
|
337
|
+
(row.attribute_id, row.value_number, row.value_unit, row.value_text)
|
|
338
|
+
for row in self._session.scalars(
|
|
339
|
+
select(FichaAttribute).where(
|
|
340
|
+
FichaAttribute.extraction_id == cached_extraction.extraction_id
|
|
341
|
+
)
|
|
342
|
+
).all()
|
|
343
|
+
}
|
|
344
|
+
residue.extend(
|
|
345
|
+
RuleResidue(pair.label, pair.value, pair.source)
|
|
346
|
+
for pair in dict.fromkeys(
|
|
347
|
+
pair
|
|
348
|
+
for attribute_id, attribute_members in resolved_by_attribute.items()
|
|
349
|
+
for member, pair in attribute_members
|
|
350
|
+
if (attribute_id, member.value_number, member.value_unit, member.value_text)
|
|
351
|
+
not in persisted
|
|
352
|
+
)
|
|
353
|
+
)
|
|
354
|
+
return RulesPassResult(
|
|
355
|
+
cached_extraction.extraction_id, tuple(residue), True, input_hash
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
attempts = self._session.scalars(
|
|
359
|
+
select(Extraction.attempt).where(
|
|
360
|
+
Extraction.ficha_id == ficha.ficha_id,
|
|
361
|
+
Extraction.input_hash == input_hash,
|
|
362
|
+
Extraction.model == "rules",
|
|
363
|
+
Extraction.prompt_version == version,
|
|
364
|
+
)
|
|
365
|
+
).all()
|
|
366
|
+
attempt = max(attempts, default=0) + 1
|
|
367
|
+
extraction_id = str(uuid4())
|
|
368
|
+
now = self._now()
|
|
369
|
+
if now.tzinfo is None or now.utcoffset() is None:
|
|
370
|
+
raise ValueError("rules pass clock must return a timezone-aware datetime")
|
|
371
|
+
upsert(
|
|
372
|
+
self._session,
|
|
373
|
+
Extraction,
|
|
374
|
+
[
|
|
375
|
+
{
|
|
376
|
+
"extraction_id": extraction_id,
|
|
377
|
+
"ficha_id": ficha.ficha_id,
|
|
378
|
+
"input_hash": input_hash,
|
|
379
|
+
"attempt": attempt,
|
|
380
|
+
"model": "rules",
|
|
381
|
+
"prompt_version": version,
|
|
382
|
+
"status": "ok",
|
|
383
|
+
"request_id": None,
|
|
384
|
+
"input_tokens": None,
|
|
385
|
+
"output_tokens": None,
|
|
386
|
+
"cost_usd": None,
|
|
387
|
+
"started_at": now,
|
|
388
|
+
"finished_at": now,
|
|
389
|
+
}
|
|
390
|
+
],
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
# A concurrent pass for the same cache key can pick the same attempt;
|
|
394
|
+
# the upsert then keeps the row that won, so write children against the
|
|
395
|
+
# extraction id that is actually stored.
|
|
396
|
+
extraction_id = self._session.scalars(
|
|
397
|
+
select(Extraction.extraction_id).where(
|
|
398
|
+
Extraction.ficha_id == ficha.ficha_id,
|
|
399
|
+
Extraction.input_hash == input_hash,
|
|
400
|
+
Extraction.model == "rules",
|
|
401
|
+
Extraction.prompt_version == version,
|
|
402
|
+
Extraction.attempt == attempt,
|
|
403
|
+
)
|
|
404
|
+
).one()
|
|
405
|
+
|
|
406
|
+
value_rows: list[dict[str, object]] = []
|
|
407
|
+
scope_rows: dict[str, dict[str, object]] = {}
|
|
408
|
+
for attribute_id, attribute_members in resolved_by_attribute.items():
|
|
409
|
+
for position, (member, pair) in enumerate(attribute_members):
|
|
410
|
+
value_rows.append(
|
|
411
|
+
{
|
|
412
|
+
"extraction_id": extraction_id,
|
|
413
|
+
"attribute_id": attribute_id,
|
|
414
|
+
"position": position,
|
|
415
|
+
"ficha_id": ficha.ficha_id,
|
|
416
|
+
"kind": attribute_by_id[attribute_id].kind,
|
|
417
|
+
"value_number": member.value_number,
|
|
418
|
+
"value_unit": member.value_unit,
|
|
419
|
+
"value_text": member.value_text,
|
|
420
|
+
"raw_text": pair.value,
|
|
421
|
+
"source": "rule",
|
|
422
|
+
"confidence": _CONFIDENCE,
|
|
423
|
+
}
|
|
424
|
+
)
|
|
425
|
+
scope_rows[attribute_id] = {
|
|
426
|
+
"attribute_id": attribute_id,
|
|
427
|
+
"category": category,
|
|
428
|
+
"origin": "extraction",
|
|
429
|
+
"extraction_id": extraction_id,
|
|
430
|
+
"request_id": None,
|
|
431
|
+
"first_seen_at": now,
|
|
432
|
+
}
|
|
433
|
+
upsert(self._session, FichaAttribute, value_rows)
|
|
434
|
+
upsert(self._session, AttributeScope, scope_rows.values())
|
|
435
|
+
return RulesPassResult(extraction_id, tuple(residue), False, input_hash)
|
|
436
|
+
|
|
437
|
+
async def llm_pass(self, ficha: Ficha) -> LLMPassResult:
|
|
438
|
+
"""Extract only the residue left by rules and retain each attempt.
|
|
439
|
+
|
|
440
|
+
Transaction contract: every return path commits the rules pass (and the
|
|
441
|
+
attempt rows it wrote), so the caller never has to commit. An exception
|
|
442
|
+
raised before the claim leaves the session uncommitted for the caller to
|
|
443
|
+
roll back; one raised after it has already committed the attempt as failed.
|
|
444
|
+
"""
|
|
445
|
+
return await self._llm_pass(ficha, self.rules_pass(ficha), force=False)
|
|
446
|
+
|
|
447
|
+
async def _llm_pass(
|
|
448
|
+
self, ficha: Ficha, rules: RulesPassResult, *, force: bool
|
|
449
|
+
) -> LLMPassResult:
|
|
450
|
+
if not rules.residue:
|
|
451
|
+
self._session.commit() # keep the rules pass
|
|
452
|
+
return LLMPassResult(None, "skipped", False)
|
|
453
|
+
if self._llm_client is None:
|
|
454
|
+
raise ValueError("llm_client must be configured when extraction residue remains")
|
|
455
|
+
# One input for the whole pass: the one the rules pass resolved. Commits
|
|
456
|
+
# below expire the ficha, and re-reading its input_hash could pick up a
|
|
457
|
+
# newer input a sync committed meanwhile, mixing two inputs in one attempt.
|
|
458
|
+
input_hash = rules.input_hash
|
|
459
|
+
|
|
460
|
+
config = self._session.get(ExtractionConfig, "current")
|
|
461
|
+
if config is None:
|
|
462
|
+
raise ValueError("current extraction config is not set")
|
|
463
|
+
|
|
464
|
+
# A forced pass (re-extraction) never reuses an earlier attempt.
|
|
465
|
+
cached_extraction = (
|
|
466
|
+
None
|
|
467
|
+
if force
|
|
468
|
+
else self._session.scalar(
|
|
469
|
+
select(Extraction)
|
|
470
|
+
.where(
|
|
471
|
+
Extraction.ficha_id == ficha.ficha_id,
|
|
472
|
+
Extraction.input_hash == input_hash,
|
|
473
|
+
Extraction.model == config.llm_model,
|
|
474
|
+
Extraction.prompt_version == config.llm_prompt_version,
|
|
475
|
+
Extraction.status == "ok",
|
|
476
|
+
)
|
|
477
|
+
.order_by(Extraction.attempt.desc())
|
|
478
|
+
.limit(1)
|
|
479
|
+
)
|
|
480
|
+
)
|
|
481
|
+
if cached_extraction is not None:
|
|
482
|
+
cached_id = cached_extraction.extraction_id # read before commit expires it
|
|
483
|
+
self._session.commit() # keep the rules pass
|
|
484
|
+
return LLMPassResult(cached_id, "ok", True)
|
|
485
|
+
|
|
486
|
+
canonical_input = _read_canonical_input(self._read_input_payload(input_hash))
|
|
487
|
+
category = _input_category(canonical_input)
|
|
488
|
+
seeds = self._session.scalars(select(SeedValue).where(SeedValue.category == category)).all()
|
|
489
|
+
# The model only ever sees live attribute ids as usable: seeds and
|
|
490
|
+
# rules-pass values of a merged attribute are shown under its target,
|
|
491
|
+
# those of a rejected one are left out. Every other id (merge sources and
|
|
492
|
+
# rejected ones) is listed as taken, so the model never answers with, or
|
|
493
|
+
# re-proposes, an id the write path must refuse.
|
|
494
|
+
live = self._live_attributes()
|
|
495
|
+
seed_pairs = sorted(
|
|
496
|
+
{
|
|
497
|
+
(live[seed.attribute_id].attribute_id, seed.raw_value)
|
|
498
|
+
for seed in seeds
|
|
499
|
+
if seed.attribute_id in live
|
|
500
|
+
}
|
|
501
|
+
)
|
|
502
|
+
resolved_rows = self._session.scalars(
|
|
503
|
+
select(FichaAttribute)
|
|
504
|
+
.where(FichaAttribute.extraction_id == rules.extraction_id)
|
|
505
|
+
.order_by(FichaAttribute.attribute_id, FichaAttribute.position)
|
|
506
|
+
).all()
|
|
507
|
+
resolved_values = [
|
|
508
|
+
{
|
|
509
|
+
"attribute": (
|
|
510
|
+
live[row.attribute_id].attribute_id
|
|
511
|
+
if row.attribute_id in live
|
|
512
|
+
else row.attribute_id
|
|
513
|
+
),
|
|
514
|
+
"kind": row.kind,
|
|
515
|
+
"position": row.position,
|
|
516
|
+
"value_number": str(row.value_number) if row.value_number is not None else None,
|
|
517
|
+
"value_unit": row.value_unit,
|
|
518
|
+
"value_text": row.value_text,
|
|
519
|
+
}
|
|
520
|
+
for row in resolved_rows
|
|
521
|
+
]
|
|
522
|
+
# The catalog is every live attribute, from every category (decided by
|
|
523
|
+
# Mirko, 2026-11-20, option B for the pilot): the model may put a value
|
|
524
|
+
# on any of them, and a value under an attribute not yet scoped to this
|
|
525
|
+
# category adds its ``attribute_scope`` row, which is how applicability
|
|
526
|
+
# grows (proposal §3). Each id is shown under its live target, so merge
|
|
527
|
+
# sources and rejected attributes never appear here.
|
|
528
|
+
catalog_ids = {attribute.attribute_id for attribute in live.values()}
|
|
529
|
+
catalog = [
|
|
530
|
+
{
|
|
531
|
+
"attribute_id": attribute.attribute_id,
|
|
532
|
+
"kind": attribute.kind,
|
|
533
|
+
"canonical_unit": attribute.canonical_unit,
|
|
534
|
+
}
|
|
535
|
+
for attribute in sorted(
|
|
536
|
+
(live[attribute_id] for attribute_id in catalog_ids),
|
|
537
|
+
key=lambda attribute: attribute.attribute_id,
|
|
538
|
+
)
|
|
539
|
+
]
|
|
540
|
+
# Ids are global: the only ids outside the catalog are merge sources and
|
|
541
|
+
# rejected attributes, which the model must neither write to nor
|
|
542
|
+
# re-propose. This snapshot is also what the write path refuses: an id
|
|
543
|
+
# created only after the prompt was built (e.g. by a concurrent pass) is
|
|
544
|
+
# not taken and takes the normal existing-attribute path.
|
|
545
|
+
taken_ids = frozenset(self._session.scalars(select(Attribute.attribute_id)).all()) - (
|
|
546
|
+
catalog_ids
|
|
547
|
+
)
|
|
548
|
+
prompt = build_llm_prompt(
|
|
549
|
+
canonical_input,
|
|
550
|
+
[
|
|
551
|
+
{"attribute_id": attribute_id, "raw_value": raw_value}
|
|
552
|
+
for attribute_id, raw_value in seed_pairs
|
|
553
|
+
],
|
|
554
|
+
resolved_values,
|
|
555
|
+
config.llm_prompt_version,
|
|
556
|
+
attributes=catalog,
|
|
557
|
+
taken_attribute_ids=sorted(taken_ids),
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
now = self._now()
|
|
561
|
+
if now.tzinfo is None or now.utcoffset() is None:
|
|
562
|
+
raise ValueError("LLM pass clock must return a timezone-aware datetime")
|
|
563
|
+
cache_key = (
|
|
564
|
+
Extraction.ficha_id == ficha.ficha_id,
|
|
565
|
+
Extraction.input_hash == input_hash,
|
|
566
|
+
Extraction.model == config.llm_model,
|
|
567
|
+
Extraction.prompt_version == config.llm_prompt_version,
|
|
568
|
+
)
|
|
569
|
+
# The first claimant of a cache key wins. A live pending attempt is an
|
|
570
|
+
# earlier claimant still calling the provider: give way to it instead of
|
|
571
|
+
# paying for a second call. A pending row older than the claim expiry is
|
|
572
|
+
# an abandoned run (e.g. a killed process) and no longer blocks.
|
|
573
|
+
live_since = now - self._claim_expiry
|
|
574
|
+
earlier_claim = self._session.scalar(
|
|
575
|
+
select(Extraction.extraction_id)
|
|
576
|
+
.where(
|
|
577
|
+
*cache_key,
|
|
578
|
+
Extraction.status == "pending",
|
|
579
|
+
Extraction.started_at >= live_since,
|
|
580
|
+
)
|
|
581
|
+
.order_by(Extraction.started_at, Extraction.attempt)
|
|
582
|
+
.limit(1)
|
|
583
|
+
)
|
|
584
|
+
if earlier_claim is not None:
|
|
585
|
+
self._session.commit() # keep the rules pass
|
|
586
|
+
return LLMPassResult(earlier_claim, "pending", False)
|
|
587
|
+
# Keep the rules pass whatever happens to the claim: losing the race on
|
|
588
|
+
# the attempt key must roll back only the claim row.
|
|
589
|
+
self._session.commit()
|
|
590
|
+
known = self._session.execute(
|
|
591
|
+
select(Extraction.extraction_id, Extraction.attempt, Extraction.status).where(
|
|
592
|
+
*cache_key
|
|
593
|
+
)
|
|
594
|
+
).all()
|
|
595
|
+
attempt = max((row.attempt for row in known), default=0) + 1
|
|
596
|
+
# ``ok`` attempts already finished when this run decided to claim: for a
|
|
597
|
+
# forced pass they are history, not results to give way to.
|
|
598
|
+
ok_before_claim = [row.extraction_id for row in known if row.status == "ok"]
|
|
599
|
+
extraction_id = str(uuid4())
|
|
600
|
+
self._session.add(
|
|
601
|
+
Extraction(
|
|
602
|
+
extraction_id=extraction_id,
|
|
603
|
+
ficha_id=ficha.ficha_id,
|
|
604
|
+
input_hash=input_hash,
|
|
605
|
+
attempt=attempt,
|
|
606
|
+
model=config.llm_model,
|
|
607
|
+
# The client that makes the call, not the shared config row,
|
|
608
|
+
# which another run with another provider may have rewritten.
|
|
609
|
+
provider=self._llm_client.provider,
|
|
610
|
+
prompt_version=config.llm_prompt_version,
|
|
611
|
+
status="pending",
|
|
612
|
+
request_id=None,
|
|
613
|
+
input_tokens=None,
|
|
614
|
+
output_tokens=None,
|
|
615
|
+
cost_usd=None,
|
|
616
|
+
started_at=now,
|
|
617
|
+
finished_at=None,
|
|
618
|
+
)
|
|
619
|
+
)
|
|
620
|
+
# Commit the rules pass and the pending attempt before the provider call:
|
|
621
|
+
# the call is logged from its own session (a held write would lock it out
|
|
622
|
+
# on SQLite), and the pending row must survive a crash during the call.
|
|
623
|
+
try:
|
|
624
|
+
self._session.commit()
|
|
625
|
+
except IntegrityError:
|
|
626
|
+
# SQLite enforces the attempt key: another run claimed it first.
|
|
627
|
+
self._session.rollback()
|
|
628
|
+
return LLMPassResult(None, "pending", False)
|
|
629
|
+
# Snowflake does not enforce the attempt key, so two runs can both commit
|
|
630
|
+
# a claim. Proceed only if no other claim is visible after ours: another
|
|
631
|
+
# claim of the same attempt, another live pending attempt, or a finished
|
|
632
|
+
# ``ok`` one. Of two racing runs, the one that committed later always
|
|
633
|
+
# sees the earlier one and gives way, so a run that found itself alone
|
|
634
|
+
# (the first claimant) is never overtaken. If both commit before either
|
|
635
|
+
# reads, both give way and a later pass retries: never two paid calls.
|
|
636
|
+
# A forced pass claims past the earlier ``ok`` attempts, which stay as
|
|
637
|
+
# history: only an ``ok`` attempt that was not ``ok`` yet when this run
|
|
638
|
+
# read the attempts (a concurrent re-extraction that finished first,
|
|
639
|
+
# whatever its attempt number) is a result to give way to.
|
|
640
|
+
finished_claim = Extraction.status == "ok"
|
|
641
|
+
if force and ok_before_claim:
|
|
642
|
+
finished_claim = finished_claim & Extraction.extraction_id.not_in(ok_before_claim)
|
|
643
|
+
other_claim = self._session.execute(
|
|
644
|
+
select(Extraction.extraction_id, Extraction.status)
|
|
645
|
+
.where(
|
|
646
|
+
*cache_key,
|
|
647
|
+
Extraction.extraction_id != extraction_id,
|
|
648
|
+
or_(
|
|
649
|
+
Extraction.attempt == attempt,
|
|
650
|
+
finished_claim,
|
|
651
|
+
(Extraction.status == "pending") & (Extraction.started_at >= live_since),
|
|
652
|
+
),
|
|
653
|
+
)
|
|
654
|
+
# A finished ``ok`` attempt wins over any claim: it is a cache hit.
|
|
655
|
+
.order_by(
|
|
656
|
+
case((Extraction.status == "ok", 0), else_=1),
|
|
657
|
+
Extraction.started_at,
|
|
658
|
+
Extraction.attempt,
|
|
659
|
+
)
|
|
660
|
+
.limit(1)
|
|
661
|
+
).first()
|
|
662
|
+
if other_claim is not None:
|
|
663
|
+
other_id, other_status = other_claim
|
|
664
|
+
self._set_extraction(extraction_id, status="failed", finished_at=self._now())
|
|
665
|
+
self._session.commit()
|
|
666
|
+
if other_status == "ok":
|
|
667
|
+
# Another run finished this cache key meanwhile: a cache hit.
|
|
668
|
+
return LLMPassResult(other_id, "ok", True)
|
|
669
|
+
return LLMPassResult(other_id, "pending", False)
|
|
670
|
+
|
|
671
|
+
response: LLMResponse | None = None
|
|
672
|
+
request_id: str | None = None
|
|
673
|
+
# The call's share of the claim counts from the claim's started_at, not
|
|
674
|
+
# from the call's own start: the claim commit and the visibility check
|
|
675
|
+
# above already used part of it.
|
|
676
|
+
call_deadline = (
|
|
677
|
+
self._claim_expiry.total_seconds() * _CLAIM_CALL_SHARE
|
|
678
|
+
- (self._now() - now).total_seconds()
|
|
679
|
+
)
|
|
680
|
+
call_request_ids: list[str] = []
|
|
681
|
+
try:
|
|
682
|
+
with collect_logged_request_ids() as collected_request_ids:
|
|
683
|
+
call_request_ids = collected_request_ids
|
|
684
|
+
try:
|
|
685
|
+
async with asyncio.timeout(call_deadline):
|
|
686
|
+
response = await self._llm_client.post_llm(prompt)
|
|
687
|
+
except TimeoutError as error:
|
|
688
|
+
deadline_error = _ClaimDeadlineExceeded(
|
|
689
|
+
f"LLM call exceeded {call_deadline:.0f} s, the share of the claim "
|
|
690
|
+
"expiry it may use"
|
|
691
|
+
)
|
|
692
|
+
if call_request_ids:
|
|
693
|
+
# The cancelled call may already have logged requests
|
|
694
|
+
# (a sent request, or retries before a backoff wait).
|
|
695
|
+
set_logged_request_id(deadline_error, call_request_ids[-1])
|
|
696
|
+
raise deadline_error from error
|
|
697
|
+
# An empty id is no id: leave it None so the failure handler falls
|
|
698
|
+
# back to the request the call logged.
|
|
699
|
+
request_id = response.request_id or None
|
|
700
|
+
if request_id is None:
|
|
701
|
+
raise RuntimeError("LLM request was not logged")
|
|
702
|
+
self._set_extraction(extraction_id, request_id=request_id)
|
|
703
|
+
parsed = parse_llm_response(response.text)
|
|
704
|
+
self._write_llm_result(extraction_id, ficha, category, parsed, now, taken_ids)
|
|
705
|
+
if self._now() - now >= self._claim_expiry:
|
|
706
|
+
# The claim expired during the write phase: another run may
|
|
707
|
+
# already have claimed this key and be writing its own result.
|
|
708
|
+
# Discard this one rather than commit it as ok beside theirs.
|
|
709
|
+
raise _ClaimDeadlineExceeded(
|
|
710
|
+
"LLM pass finished after its claim expired; result discarded"
|
|
711
|
+
)
|
|
712
|
+
self._set_extraction(
|
|
713
|
+
extraction_id,
|
|
714
|
+
status="ok",
|
|
715
|
+
input_tokens=_token_count(response.input_tokens),
|
|
716
|
+
output_tokens=_token_count(response.output_tokens),
|
|
717
|
+
cost_usd=self._llm_cost(response),
|
|
718
|
+
finished_at=self._now(),
|
|
719
|
+
)
|
|
720
|
+
self._session.commit()
|
|
721
|
+
except BaseException as error:
|
|
722
|
+
# Discard any partial result rows; the pending attempt is committed.
|
|
723
|
+
# BaseException too: a cancellation (timeout, Ctrl-C) during the call
|
|
724
|
+
# must still close the attempt as failed, never leave it pending.
|
|
725
|
+
self._session.rollback()
|
|
726
|
+
if request_id is None:
|
|
727
|
+
failed_request_id = getattr(error, "request_id", None)
|
|
728
|
+
request_id = failed_request_id if isinstance(failed_request_id, str) else None
|
|
729
|
+
if request_id is None and call_request_ids:
|
|
730
|
+
# The error carries no id (e.g. a cancellation from outside, or
|
|
731
|
+
# Ctrl-C): point at the last request the call already logged.
|
|
732
|
+
request_id = call_request_ids[-1]
|
|
733
|
+
failure: dict[str, object] = {
|
|
734
|
+
"status": "failed",
|
|
735
|
+
"request_id": request_id,
|
|
736
|
+
"finished_at": self._now(),
|
|
737
|
+
}
|
|
738
|
+
if response is not None:
|
|
739
|
+
failure["input_tokens"] = _token_count(response.input_tokens)
|
|
740
|
+
failure["output_tokens"] = _token_count(response.output_tokens)
|
|
741
|
+
failure["cost_usd"] = self._llm_cost(response)
|
|
742
|
+
self._set_extraction(extraction_id, **failure)
|
|
743
|
+
self._session.commit()
|
|
744
|
+
if isinstance(error, LLMConfigurationError) or not isinstance(
|
|
745
|
+
error, (LLMRequestError, ValueError, _ClaimDeadlineExceeded)
|
|
746
|
+
):
|
|
747
|
+
# Not a problem of this ficha's request or response (a rejected
|
|
748
|
+
# credential, a cancellation, a database error or a bug): the
|
|
749
|
+
# attempt is recorded as failed, but the caller must see it
|
|
750
|
+
# instead of paying for the same failure on every ficha.
|
|
751
|
+
raise
|
|
752
|
+
_LOGGER.warning(
|
|
753
|
+
"LLM pass for ficha %s attempt %s failed: %s", ficha.ficha_id, attempt, error
|
|
754
|
+
)
|
|
755
|
+
return LLMPassResult(extraction_id, "failed", False, str(error))
|
|
756
|
+
|
|
757
|
+
return LLMPassResult(extraction_id, "ok", False)
|
|
758
|
+
|
|
759
|
+
def _live_attributes(self) -> dict[str, Attribute]:
|
|
760
|
+
"""Map every attribute id to its live attribute (following ``merged_into``).
|
|
761
|
+
|
|
762
|
+
Rejected attributes, and merges that end at a rejected or missing one,
|
|
763
|
+
have no live attribute and are left out.
|
|
764
|
+
"""
|
|
765
|
+
by_id = {
|
|
766
|
+
attribute.attribute_id: attribute
|
|
767
|
+
for attribute in self._session.scalars(select(Attribute)).all()
|
|
768
|
+
}
|
|
769
|
+
live: dict[str, Attribute] = {}
|
|
770
|
+
for attribute_id in by_id:
|
|
771
|
+
current = by_id[attribute_id]
|
|
772
|
+
seen = {attribute_id}
|
|
773
|
+
while current.merged_into is not None and current.merged_into not in seen:
|
|
774
|
+
seen.add(current.merged_into)
|
|
775
|
+
target = by_id.get(current.merged_into)
|
|
776
|
+
if target is None:
|
|
777
|
+
break
|
|
778
|
+
current = target
|
|
779
|
+
if current.merged_into is None and current.status != "rejected":
|
|
780
|
+
live[attribute_id] = current
|
|
781
|
+
return live
|
|
782
|
+
|
|
783
|
+
def _set_extraction(self, extraction_id: str, **values: object) -> None:
|
|
784
|
+
"""Update this attempt's own row by primary key."""
|
|
785
|
+
self._session.execute(
|
|
786
|
+
update(Extraction)
|
|
787
|
+
.where(Extraction.extraction_id == extraction_id)
|
|
788
|
+
.values(values)
|
|
789
|
+
.execution_options(synchronize_session=False)
|
|
790
|
+
)
|
|
791
|
+
|
|
792
|
+
def _llm_cost(self, response: LLMResponse) -> Decimal | None:
|
|
793
|
+
"""USD cost of one response from the configured per-million-token rates."""
|
|
794
|
+
input_tokens = _token_count(response.input_tokens)
|
|
795
|
+
output_tokens = _token_count(response.output_tokens)
|
|
796
|
+
if (
|
|
797
|
+
self._input_usd_per_mtok is None
|
|
798
|
+
or self._output_usd_per_mtok is None
|
|
799
|
+
or input_tokens is None
|
|
800
|
+
or output_tokens is None
|
|
801
|
+
):
|
|
802
|
+
# No rate configured, or usage the SDK's non-strict models let through
|
|
803
|
+
# without valid token counts: cost is unknown, never a raise here.
|
|
804
|
+
return None
|
|
805
|
+
cost = (
|
|
806
|
+
input_tokens * self._input_usd_per_mtok + output_tokens * self._output_usd_per_mtok
|
|
807
|
+
) / Decimal(1_000_000)
|
|
808
|
+
return cost.quantize(Decimal("0.000001"))
|
|
809
|
+
|
|
810
|
+
def _write_llm_result(
|
|
811
|
+
self,
|
|
812
|
+
extraction_id: str,
|
|
813
|
+
ficha: Ficha,
|
|
814
|
+
category: str,
|
|
815
|
+
parsed: ParsedExtraction,
|
|
816
|
+
now: datetime,
|
|
817
|
+
taken_ids: set[str] | frozenset[str] = frozenset(),
|
|
818
|
+
) -> None:
|
|
819
|
+
attributes = self._session.scalars(select(Attribute)).all()
|
|
820
|
+
attribute_by_id = {attribute.attribute_id: attribute for attribute in attributes}
|
|
821
|
+
for taken in parsed.proposals.new_attributes:
|
|
822
|
+
if taken.attribute_id in taken_ids:
|
|
823
|
+
# The prompt listed this id as taken (a merge source or a
|
|
824
|
+
# rejected attribute): it can never receive values again.
|
|
825
|
+
raise ValueError(
|
|
826
|
+
f"LLM response proposes new attribute {taken.attribute_id!r}, "
|
|
827
|
+
"an id already taken by a merged or rejected attribute"
|
|
828
|
+
)
|
|
829
|
+
new_attributes: dict[str, AttributeProposal] = {}
|
|
830
|
+
for new_proposal in parsed.proposals.new_attributes:
|
|
831
|
+
if new_proposal.attribute_id in attribute_by_id:
|
|
832
|
+
continue
|
|
833
|
+
previous_proposal = new_attributes.get(new_proposal.attribute_id)
|
|
834
|
+
if previous_proposal is not None and (
|
|
835
|
+
previous_proposal.kind != new_proposal.kind
|
|
836
|
+
or previous_proposal.canonical_unit != new_proposal.canonical_unit
|
|
837
|
+
or previous_proposal.display_name != new_proposal.display_name
|
|
838
|
+
):
|
|
839
|
+
raise ValueError(
|
|
840
|
+
f"LLM response proposes conflicting new attributes for "
|
|
841
|
+
f"{new_proposal.attribute_id!r}"
|
|
842
|
+
)
|
|
843
|
+
new_attributes[new_proposal.attribute_id] = new_proposal
|
|
844
|
+
attribute_ids = set(attribute_by_id) | set(new_attributes)
|
|
845
|
+
referenced_ids = {value.attribute for value in parsed.values}
|
|
846
|
+
referenced_ids.update(proposal.attribute_id for proposal in parsed.proposals.aliases)
|
|
847
|
+
missing_ids = referenced_ids - attribute_ids
|
|
848
|
+
if missing_ids:
|
|
849
|
+
raise ValueError(f"LLM response references unknown attributes: {sorted(missing_ids)}")
|
|
850
|
+
# A taken id is a merge source or a rejected attribute: a value or an
|
|
851
|
+
# alias under it would land on an attribute that can't receive values.
|
|
852
|
+
taken_references = referenced_ids & taken_ids
|
|
853
|
+
if taken_references:
|
|
854
|
+
raise ValueError(
|
|
855
|
+
"LLM response uses attribute ids taken by merged or rejected attributes: "
|
|
856
|
+
f"{sorted(taken_references)}"
|
|
857
|
+
)
|
|
858
|
+
_check_attribute_references(parsed, attribute_by_id, new_attributes)
|
|
859
|
+
for value in parsed.values:
|
|
860
|
+
if value.value_number is not None:
|
|
861
|
+
_check_column_range(
|
|
862
|
+
value.value_number, _VALUE_NUMBER_DIGITS, f"value for {value.attribute!r}"
|
|
863
|
+
)
|
|
864
|
+
for unit_proposal in parsed.proposals.unit_rules:
|
|
865
|
+
_check_column_range(
|
|
866
|
+
unit_proposal.factor,
|
|
867
|
+
_UNIT_FACTOR_DIGITS,
|
|
868
|
+
f"unit rule factor for {unit_proposal.raw_unit!r}",
|
|
869
|
+
nonzero=True,
|
|
870
|
+
)
|
|
871
|
+
|
|
872
|
+
upsert(
|
|
873
|
+
self._session,
|
|
874
|
+
Attribute,
|
|
875
|
+
[
|
|
876
|
+
{
|
|
877
|
+
"attribute_id": proposal.attribute_id,
|
|
878
|
+
"display_name": proposal.display_name,
|
|
879
|
+
"kind": proposal.kind,
|
|
880
|
+
"canonical_unit": proposal.canonical_unit,
|
|
881
|
+
"seeded_from_pane": False,
|
|
882
|
+
"status": "proposed",
|
|
883
|
+
"merged_into": None,
|
|
884
|
+
"proposed_by": extraction_id,
|
|
885
|
+
"accepted_at": None,
|
|
886
|
+
"created_at": now,
|
|
887
|
+
}
|
|
888
|
+
for proposal in new_attributes.values()
|
|
889
|
+
],
|
|
890
|
+
insert_only=True,
|
|
891
|
+
)
|
|
892
|
+
if new_attributes:
|
|
893
|
+
# The insert-only write keeps a row another writer committed after
|
|
894
|
+
# the read (pane seeding, or another pass proposing the same id), so
|
|
895
|
+
# check the values and aliases again against the rows now stored.
|
|
896
|
+
stored = self._session.scalars(
|
|
897
|
+
select(Attribute).where(Attribute.attribute_id.in_(list(new_attributes)))
|
|
898
|
+
).all()
|
|
899
|
+
_check_attribute_references(
|
|
900
|
+
parsed,
|
|
901
|
+
{**attribute_by_id, **{attribute.attribute_id: attribute for attribute in stored}},
|
|
902
|
+
{},
|
|
903
|
+
)
|
|
904
|
+
|
|
905
|
+
upsert(
|
|
906
|
+
self._session,
|
|
907
|
+
FichaAttribute,
|
|
908
|
+
[
|
|
909
|
+
{
|
|
910
|
+
"extraction_id": extraction_id,
|
|
911
|
+
"attribute_id": value.attribute,
|
|
912
|
+
"position": value.position,
|
|
913
|
+
"ficha_id": ficha.ficha_id,
|
|
914
|
+
"kind": value.kind,
|
|
915
|
+
"value_number": value.value_number,
|
|
916
|
+
"value_unit": value.value_unit,
|
|
917
|
+
"value_text": value.value_text,
|
|
918
|
+
"raw_text": value.raw_text,
|
|
919
|
+
"source": value.source,
|
|
920
|
+
"confidence": value.confidence,
|
|
921
|
+
}
|
|
922
|
+
for value in parsed.values
|
|
923
|
+
],
|
|
924
|
+
)
|
|
925
|
+
|
|
926
|
+
existing_aliases = {alias.raw_label for alias in self._session.scalars(select(Alias)).all()}
|
|
927
|
+
alias_rows: dict[str, dict[str, object]] = {}
|
|
928
|
+
for proposal in parsed.proposals.aliases:
|
|
929
|
+
raw_label = normalize_label(proposal.raw_label)
|
|
930
|
+
if raw_label in existing_aliases:
|
|
931
|
+
continue
|
|
932
|
+
alias_row: dict[str, object] = {
|
|
933
|
+
"alias_id": str(uuid4()),
|
|
934
|
+
"raw_label": raw_label,
|
|
935
|
+
"attribute_id": proposal.attribute_id,
|
|
936
|
+
"status": "proposed",
|
|
937
|
+
"proposed_by": extraction_id,
|
|
938
|
+
"accepted_at": None,
|
|
939
|
+
}
|
|
940
|
+
previous = alias_rows.get(raw_label)
|
|
941
|
+
if previous is not None and previous["attribute_id"] != proposal.attribute_id:
|
|
942
|
+
raise ValueError(f"LLM response proposes conflicting aliases for {raw_label!r}")
|
|
943
|
+
alias_rows[raw_label] = alias_row
|
|
944
|
+
# Insert-only, like every proposal: a row another writer committed since
|
|
945
|
+
# the read (an alias pane seeding accepted, say) keeps its review state.
|
|
946
|
+
upsert(self._session, Alias, alias_rows.values(), insert_only=True)
|
|
947
|
+
|
|
948
|
+
existing_unit_rules = {
|
|
949
|
+
(rule.raw_unit, rule.category) for rule in self._session.scalars(select(UnitRule)).all()
|
|
950
|
+
}
|
|
951
|
+
unit_rule_rows: dict[tuple[str, str], dict[str, object]] = {}
|
|
952
|
+
for unit_proposal in parsed.proposals.unit_rules:
|
|
953
|
+
key = (unit_proposal.raw_unit, unit_proposal.category)
|
|
954
|
+
if key in existing_unit_rules:
|
|
955
|
+
continue
|
|
956
|
+
unit_rule_row: dict[str, object] = {
|
|
957
|
+
"rule_id": str(uuid4()),
|
|
958
|
+
"raw_unit": unit_proposal.raw_unit,
|
|
959
|
+
"category": unit_proposal.category,
|
|
960
|
+
"canonical_unit": unit_proposal.canonical_unit,
|
|
961
|
+
"factor": unit_proposal.factor,
|
|
962
|
+
"status": "proposed",
|
|
963
|
+
"proposed_by": extraction_id,
|
|
964
|
+
"accepted_at": None,
|
|
965
|
+
}
|
|
966
|
+
previous = unit_rule_rows.get(key)
|
|
967
|
+
if previous is not None and (
|
|
968
|
+
previous["canonical_unit"] != unit_proposal.canonical_unit
|
|
969
|
+
or previous["factor"] != unit_proposal.factor
|
|
970
|
+
):
|
|
971
|
+
raise ValueError(f"LLM response proposes conflicting unit rules for {key!r}")
|
|
972
|
+
unit_rule_rows[key] = unit_rule_row
|
|
973
|
+
upsert(self._session, UnitRule, unit_rule_rows.values(), insert_only=True)
|
|
974
|
+
|
|
975
|
+
scope_rows = {
|
|
976
|
+
value.attribute: {
|
|
977
|
+
"attribute_id": value.attribute,
|
|
978
|
+
"category": category,
|
|
979
|
+
"origin": "extraction",
|
|
980
|
+
"extraction_id": extraction_id,
|
|
981
|
+
"request_id": None,
|
|
982
|
+
"first_seen_at": now,
|
|
983
|
+
}
|
|
984
|
+
for value in parsed.values
|
|
985
|
+
# An unknown value means the sources lack the attribute: it is no
|
|
986
|
+
# evidence that the attribute applies to the category (positive-only).
|
|
987
|
+
# A blank one is: the source lists the attribute, only without a value.
|
|
988
|
+
if value.kind != "unknown"
|
|
989
|
+
}
|
|
990
|
+
upsert(self._session, AttributeScope, scope_rows.values())
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _token_count(value: object) -> int | None:
|
|
994
|
+
"""A provider token count, or None when the response carried no valid one."""
|
|
995
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
|
996
|
+
return None
|
|
997
|
+
return value
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
# (precision, scale) of the numeric columns LLM numbers are written to; Snowflake
|
|
1001
|
+
# rejects a value whose integer part does not fit (SQLite does not check).
|
|
1002
|
+
_VALUE_NUMBER_DIGITS = (24, 6) # ficha_attribute.value_number
|
|
1003
|
+
_UNIT_FACTOR_DIGITS = (24, 12) # unit_rule.factor
|
|
1004
|
+
|
|
1005
|
+
|
|
1006
|
+
def _check_attribute_references(
|
|
1007
|
+
parsed: ParsedExtraction,
|
|
1008
|
+
attribute_by_id: Mapping[str, Attribute],
|
|
1009
|
+
new_attributes: Mapping[str, AttributeProposal],
|
|
1010
|
+
) -> None:
|
|
1011
|
+
"""Reject values and aliases that the attributes they reference cannot receive.
|
|
1012
|
+
|
|
1013
|
+
An id in ``attribute_by_id`` is checked against that stored attribute, any
|
|
1014
|
+
other one against its proposal in ``new_attributes``.
|
|
1015
|
+
"""
|
|
1016
|
+
# Values are stored in the attribute's own kind and canonical unit, which
|
|
1017
|
+
# queries compare against; anything else would silently answer wrong.
|
|
1018
|
+
for value in parsed.values:
|
|
1019
|
+
existing = attribute_by_id.get(value.attribute)
|
|
1020
|
+
if existing is not None and (
|
|
1021
|
+
existing.status == "rejected" or existing.merged_into is not None
|
|
1022
|
+
):
|
|
1023
|
+
raise ValueError(f"LLM response uses rejected or merged attribute {value.attribute!r}")
|
|
1024
|
+
if existing is not None:
|
|
1025
|
+
kind, unit = existing.kind, existing.canonical_unit
|
|
1026
|
+
else:
|
|
1027
|
+
new_attribute = new_attributes[value.attribute]
|
|
1028
|
+
kind, unit = new_attribute.kind, new_attribute.canonical_unit
|
|
1029
|
+
if value.kind not in ("blank", "unknown") and value.kind != kind:
|
|
1030
|
+
raise ValueError(
|
|
1031
|
+
f"LLM value for {value.attribute!r} has kind {value.kind!r}, "
|
|
1032
|
+
f"attribute kind is {kind!r}"
|
|
1033
|
+
)
|
|
1034
|
+
if value.value_number is not None and value.value_unit != unit:
|
|
1035
|
+
raise ValueError(
|
|
1036
|
+
f"LLM value for {value.attribute!r} is in {value.value_unit!r}, "
|
|
1037
|
+
f"canonical unit is {unit!r}"
|
|
1038
|
+
)
|
|
1039
|
+
# An alias holds its raw label for good, so it must point at an attribute
|
|
1040
|
+
# that can receive values, exactly like a value must.
|
|
1041
|
+
for alias_proposal in parsed.proposals.aliases:
|
|
1042
|
+
existing = attribute_by_id.get(alias_proposal.attribute_id)
|
|
1043
|
+
if existing is not None and (
|
|
1044
|
+
existing.status == "rejected" or existing.merged_into is not None
|
|
1045
|
+
):
|
|
1046
|
+
raise ValueError(
|
|
1047
|
+
f"LLM response proposes alias {alias_proposal.raw_label!r} for rejected "
|
|
1048
|
+
f"or merged attribute {alias_proposal.attribute_id!r}"
|
|
1049
|
+
)
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def _check_column_range(
|
|
1053
|
+
value: Decimal, digits: tuple[int, int], what: str, *, nonzero: bool = False
|
|
1054
|
+
) -> None:
|
|
1055
|
+
"""Reject an LLM number that is not finite or overflows its column.
|
|
1056
|
+
|
|
1057
|
+
The magnitude is checked before rounding: quantizing a number far above the
|
|
1058
|
+
column's range raises ``decimal.InvalidOperation``, which must surface as a
|
|
1059
|
+
``ValueError`` (a failed attempt), never stop the run. With ``nonzero`` a
|
|
1060
|
+
non-zero number that rounds to 0 at the column's scale is rejected too (a
|
|
1061
|
+
unit factor stored as 0 would turn every converted value into 0).
|
|
1062
|
+
"""
|
|
1063
|
+
precision, scale = digits
|
|
1064
|
+
if not value.is_finite():
|
|
1065
|
+
raise ValueError(f"LLM {what} is not a finite number")
|
|
1066
|
+
limit = Decimal(10) ** (precision - scale)
|
|
1067
|
+
too_large = ValueError(f"LLM {what} ({value}) does not fit NUMBER({precision}, {scale})")
|
|
1068
|
+
if abs(value) >= limit:
|
|
1069
|
+
raise too_large
|
|
1070
|
+
try:
|
|
1071
|
+
rounded = value.quantize(Decimal(1).scaleb(-scale), rounding=ROUND_HALF_EVEN)
|
|
1072
|
+
except InvalidOperation as error:
|
|
1073
|
+
raise too_large from error
|
|
1074
|
+
if abs(rounded) >= limit:
|
|
1075
|
+
raise too_large
|
|
1076
|
+
if nonzero and value != 0 and rounded == 0:
|
|
1077
|
+
raise ValueError(f"LLM {what} ({value}) rounds to 0 in NUMBER({precision}, {scale})")
|
|
1078
|
+
|
|
1079
|
+
|
|
1080
|
+
def read_input_payload(payload_store: PayloadStore, input_hash: str) -> bytes:
|
|
1081
|
+
"""A ficha's stored input payload.
|
|
1082
|
+
|
|
1083
|
+
A corrupt payload (its body no longer matches its digest) is that ficha's
|
|
1084
|
+
own failure (``InvalidExtractionInputError``). Any other storage error
|
|
1085
|
+
propagates, including a missing payload: payloads are never dropped
|
|
1086
|
+
(raw sources are kept, AGENTS.md), so a missing one means the store is
|
|
1087
|
+
misconfigured or unavailable, which must fail fast.
|
|
1088
|
+
"""
|
|
1089
|
+
try:
|
|
1090
|
+
return payload_store.get(input_hash)
|
|
1091
|
+
except PayloadIntegrityError as error:
|
|
1092
|
+
raise InvalidExtractionInputError(
|
|
1093
|
+
f"stored extraction input {input_hash} is corrupt"
|
|
1094
|
+
) from error
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def _read_canonical_input(body: bytes) -> dict[str, object]:
|
|
1098
|
+
try:
|
|
1099
|
+
value = json.loads(body)
|
|
1100
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as error:
|
|
1101
|
+
raise InvalidExtractionInputError("stored extraction input is not valid JSON") from error
|
|
1102
|
+
if not isinstance(value, dict):
|
|
1103
|
+
raise InvalidExtractionInputError("stored extraction input must be a JSON object")
|
|
1104
|
+
return cast(dict[str, object], value)
|
|
1105
|
+
|
|
1106
|
+
|
|
1107
|
+
def _input_category(canonical_input: dict[str, object]) -> str:
|
|
1108
|
+
excel = canonical_input.get("excel")
|
|
1109
|
+
if isinstance(excel, dict):
|
|
1110
|
+
category = excel.get("category")
|
|
1111
|
+
if isinstance(category, str):
|
|
1112
|
+
return category
|
|
1113
|
+
return ""
|
|
1114
|
+
|
|
1115
|
+
|
|
1116
|
+
def _source_pairs(
|
|
1117
|
+
canonical_input: dict[str, object], known_labels: tuple[str, ...]
|
|
1118
|
+
) -> list[_SourcePair]:
|
|
1119
|
+
pairs: list[_SourcePair] = []
|
|
1120
|
+
features = canonical_input.get("features")
|
|
1121
|
+
if isinstance(features, list):
|
|
1122
|
+
for feature in features:
|
|
1123
|
+
if isinstance(feature, dict):
|
|
1124
|
+
label, value = feature.get("label"), feature.get("value")
|
|
1125
|
+
if (
|
|
1126
|
+
isinstance(label, str)
|
|
1127
|
+
and isinstance(value, str)
|
|
1128
|
+
and label.strip()
|
|
1129
|
+
and value.strip()
|
|
1130
|
+
):
|
|
1131
|
+
pairs.append(_SourcePair(label, value, "card"))
|
|
1132
|
+
|
|
1133
|
+
for field, source in (("description", "description"), ("pdf_text", "pdf")):
|
|
1134
|
+
text = canonical_input.get(field)
|
|
1135
|
+
if isinstance(text, str):
|
|
1136
|
+
pairs.extend(
|
|
1137
|
+
_SourcePair(label, value, cast(ValueSource, source))
|
|
1138
|
+
for label, value in split_key_value_text(text, known_labels)
|
|
1139
|
+
)
|
|
1140
|
+
return pairs
|
|
1141
|
+
|
|
1142
|
+
|
|
1143
|
+
def _normalize_value(value: str) -> str:
|
|
1144
|
+
return " ".join(value.split()).casefold()
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
def _resolve_members(
|
|
1148
|
+
attribute: Attribute,
|
|
1149
|
+
raw_value: str,
|
|
1150
|
+
seeds: dict[str, str],
|
|
1151
|
+
converter: UnitConverter,
|
|
1152
|
+
category: str,
|
|
1153
|
+
accepted_units: dict[str, str],
|
|
1154
|
+
accepted_units_folded: dict[str, str],
|
|
1155
|
+
) -> list[_ResolvedMember] | None:
|
|
1156
|
+
if attribute.kind == "quantity":
|
|
1157
|
+
return _quantity_member(
|
|
1158
|
+
attribute, raw_value, converter, category, accepted_units, accepted_units_folded
|
|
1159
|
+
)
|
|
1160
|
+
if attribute.kind not in {"set", "categoric", "flag"}:
|
|
1161
|
+
return None
|
|
1162
|
+
|
|
1163
|
+
raw_members = [raw_value]
|
|
1164
|
+
# Unit-bearing sets are always split ("1 TB / 2 TB" is two quantities);
|
|
1165
|
+
# the whole-value seed shortcut is for textual sets only.
|
|
1166
|
+
if attribute.kind == "set" and (
|
|
1167
|
+
attribute.canonical_unit is not None or _normalize_value(raw_value) not in seeds
|
|
1168
|
+
):
|
|
1169
|
+
raw_members = [part.strip() for part in raw_value.split("/") if part.strip()]
|
|
1170
|
+
members: list[_ResolvedMember] = []
|
|
1171
|
+
for raw_member in raw_members:
|
|
1172
|
+
if attribute.kind == "set" and attribute.canonical_unit is not None:
|
|
1173
|
+
quantity = _quantity_member(
|
|
1174
|
+
attribute,
|
|
1175
|
+
raw_member,
|
|
1176
|
+
converter,
|
|
1177
|
+
category,
|
|
1178
|
+
accepted_units,
|
|
1179
|
+
accepted_units_folded,
|
|
1180
|
+
)
|
|
1181
|
+
if quantity is not None:
|
|
1182
|
+
members.extend(quantity)
|
|
1183
|
+
continue
|
|
1184
|
+
canonical_value = seeds.get(_normalize_value(raw_member))
|
|
1185
|
+
if canonical_value is None:
|
|
1186
|
+
return None
|
|
1187
|
+
if attribute.kind == "flag":
|
|
1188
|
+
normalized = canonical_value.strip().casefold().replace("í", "i")
|
|
1189
|
+
canonical_value = "sí" if normalized == "si" else "no" if normalized == "no" else ""
|
|
1190
|
+
if not canonical_value:
|
|
1191
|
+
return None
|
|
1192
|
+
members.append(_ResolvedMember(None, None, canonical_value))
|
|
1193
|
+
return members or None
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def _quantity_member(
|
|
1197
|
+
attribute: Attribute,
|
|
1198
|
+
raw_value: str,
|
|
1199
|
+
converter: UnitConverter,
|
|
1200
|
+
category: str,
|
|
1201
|
+
accepted_units: dict[str, str],
|
|
1202
|
+
accepted_units_folded: dict[str, str],
|
|
1203
|
+
) -> list[_ResolvedMember] | None:
|
|
1204
|
+
if attribute.canonical_unit is None:
|
|
1205
|
+
return None
|
|
1206
|
+
if _RANGE_RE.search(raw_value):
|
|
1207
|
+
return None
|
|
1208
|
+
matches = list(_QUANTITY_RE.finditer(raw_value))
|
|
1209
|
+
if len(matches) != 1:
|
|
1210
|
+
return None
|
|
1211
|
+
match = matches[0]
|
|
1212
|
+
try:
|
|
1213
|
+
value = Decimal(match["number"])
|
|
1214
|
+
except InvalidOperation:
|
|
1215
|
+
return None
|
|
1216
|
+
raw_unit = match["unit"].rstrip(".")
|
|
1217
|
+
# Exact spellings first, so "MB" stays MB even if a case-folded rule
|
|
1218
|
+
# ("Mb" -> MB) exists; then case-folded matches.
|
|
1219
|
+
unit = accepted_units.get(raw_unit)
|
|
1220
|
+
if unit is None and raw_unit == attribute.canonical_unit:
|
|
1221
|
+
unit = attribute.canonical_unit
|
|
1222
|
+
if unit is None:
|
|
1223
|
+
unit = accepted_units_folded.get(raw_unit.casefold())
|
|
1224
|
+
if unit is None and raw_unit.casefold() == attribute.canonical_unit.casefold():
|
|
1225
|
+
unit = attribute.canonical_unit
|
|
1226
|
+
if unit is None:
|
|
1227
|
+
return None
|
|
1228
|
+
try:
|
|
1229
|
+
canonical_value = converter.convert(
|
|
1230
|
+
value,
|
|
1231
|
+
unit,
|
|
1232
|
+
attribute.canonical_unit,
|
|
1233
|
+
category,
|
|
1234
|
+
)
|
|
1235
|
+
except ContractError:
|
|
1236
|
+
return None
|
|
1237
|
+
return [_ResolvedMember(canonical_value, attribute.canonical_unit, None)]
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
def store_extraction_input(
|
|
1241
|
+
ficha: ExcelFicha,
|
|
1242
|
+
features: list[Feature] | None,
|
|
1243
|
+
pdf_text: bytes | None,
|
|
1244
|
+
payload_store: PayloadStore,
|
|
1245
|
+
) -> str:
|
|
1246
|
+
"""Store a ficha's canonical extraction input and return its SHA-256 digest."""
|
|
1247
|
+
return payload_store.put(
|
|
1248
|
+
canonical_extraction_input(ficha, features, pdf_text), "application/json"
|
|
1249
|
+
)
|
|
1250
|
+
|
|
1251
|
+
|
|
1252
|
+
def canonical_extraction_input(
|
|
1253
|
+
ficha: ExcelFicha,
|
|
1254
|
+
features: list[Feature] | None,
|
|
1255
|
+
pdf_text: bytes | None,
|
|
1256
|
+
) -> bytes:
|
|
1257
|
+
"""Serialize a ficha's canonical extraction input (the bytes ``input_hash`` covers)."""
|
|
1258
|
+
excel_fields = {
|
|
1259
|
+
"agreement": ficha.agreement,
|
|
1260
|
+
"catalogue": ficha.catalogue,
|
|
1261
|
+
"category": ficha.category,
|
|
1262
|
+
"marca": ficha.marca,
|
|
1263
|
+
"nro_parte": ficha.nro_parte,
|
|
1264
|
+
"ficha_tecnica_url": ficha.ficha_tecnica_url,
|
|
1265
|
+
"imagen_url": ficha.imagen_url,
|
|
1266
|
+
}
|
|
1267
|
+
payload = {
|
|
1268
|
+
"description": ficha.description,
|
|
1269
|
+
"excel": excel_fields,
|
|
1270
|
+
"features": _canonical_features(features),
|
|
1271
|
+
"pdf_text": pdf_text.decode("utf-8") if pdf_text is not None else None,
|
|
1272
|
+
}
|
|
1273
|
+
return _encode_canonical_input(payload)
|
|
1274
|
+
|
|
1275
|
+
|
|
1276
|
+
def _canonical_features(features: list[Feature] | None) -> list[Feature] | None:
|
|
1277
|
+
if features is None:
|
|
1278
|
+
return None
|
|
1279
|
+
return sorted(features, key=lambda feature: (feature["label"], feature["value"]))
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def _encode_canonical_input(payload: Mapping[str, object]) -> bytes:
|
|
1283
|
+
"""Encode an extraction input with the canonical key and value ordering."""
|
|
1284
|
+
body = json.dumps(
|
|
1285
|
+
payload,
|
|
1286
|
+
ensure_ascii=False,
|
|
1287
|
+
separators=(",", ":"),
|
|
1288
|
+
sort_keys=True,
|
|
1289
|
+
allow_nan=False,
|
|
1290
|
+
).encode("utf-8")
|
|
1291
|
+
return body
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
def card_features_equal(left: list[Feature] | None, right: list[Feature] | None) -> bool:
|
|
1295
|
+
"""Return whether two card feature lists are equal in canonical order."""
|
|
1296
|
+
return _canonical_features(left) == _canonical_features(right)
|
|
1297
|
+
|
|
1298
|
+
|
|
1299
|
+
def rebuild_card_input(
|
|
1300
|
+
input_hash: str, features: list[Feature], payload_store: PayloadStore
|
|
1301
|
+
) -> tuple[str, int]:
|
|
1302
|
+
"""Store the canonical input with new card features; return its hash and size."""
|
|
1303
|
+
canonical_input = _read_canonical_input(read_input_payload(payload_store, input_hash))
|
|
1304
|
+
canonical_input["features"] = _canonical_features(features)
|
|
1305
|
+
body = _encode_canonical_input(canonical_input)
|
|
1306
|
+
return payload_store.put(body, "application/json"), len(body)
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
def rebuild_pdf_input(
|
|
1310
|
+
input_hash: str, pdf_text: bytes | None, payload_store: PayloadStore
|
|
1311
|
+
) -> tuple[str, int]:
|
|
1312
|
+
"""Store the canonical input with new PDF text; return its hash and size."""
|
|
1313
|
+
canonical_input = _read_canonical_input(read_input_payload(payload_store, input_hash))
|
|
1314
|
+
canonical_input["pdf_text"] = pdf_text.decode("utf-8") if pdf_text is not None else None
|
|
1315
|
+
body = _encode_canonical_input(canonical_input)
|
|
1316
|
+
return payload_store.put(body, "application/json"), len(body)
|