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,557 @@
|
|
|
1
|
+
"""Lazy enrichment: PDF text and extraction for the fichas a query still needs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Callable, Collection
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from datetime import UTC, datetime, timedelta
|
|
9
|
+
from typing import Any, cast
|
|
10
|
+
|
|
11
|
+
from sqlalchemy import (
|
|
12
|
+
Column,
|
|
13
|
+
CursorResult,
|
|
14
|
+
MetaData,
|
|
15
|
+
String,
|
|
16
|
+
Table,
|
|
17
|
+
case,
|
|
18
|
+
func,
|
|
19
|
+
null,
|
|
20
|
+
or_,
|
|
21
|
+
select,
|
|
22
|
+
update,
|
|
23
|
+
)
|
|
24
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
25
|
+
from sqlalchemy.sql import Select
|
|
26
|
+
|
|
27
|
+
from piloto_ai_cli.backoff import backoff, validate_backoff
|
|
28
|
+
from piloto_ai_cli.connectors import get_pdf_response
|
|
29
|
+
from piloto_ai_cli.database import upsert
|
|
30
|
+
from piloto_ai_cli.errors import InvalidExtractionInputError
|
|
31
|
+
from piloto_ai_cli.extraction import ExtractService, read_input_payload, rebuild_pdf_input
|
|
32
|
+
from piloto_ai_cli.http_client import HttpClient
|
|
33
|
+
from piloto_ai_cli.llm_client import LLMConfigurationError
|
|
34
|
+
from piloto_ai_cli.payload_store import PayloadStore
|
|
35
|
+
from piloto_ai_cli.pdf_parser import parse_pdf_text
|
|
36
|
+
from piloto_ai_cli.query_compiler import QueryCompiler
|
|
37
|
+
from piloto_ai_cli.schema.contract import STRUCTURAL_FIELDS, ValidatedContract
|
|
38
|
+
from piloto_ai_cli.schema.models import SCHEMA, Ficha, Payload, Pdf, RequestLog
|
|
39
|
+
|
|
40
|
+
_INPUT_HASH_ATTEMPTS = 3
|
|
41
|
+
_LOGGER = logging.getLogger(__name__)
|
|
42
|
+
_PDF_TEXT_CONTENT_TYPE = "text/plain; charset=utf-8"
|
|
43
|
+
|
|
44
|
+
_FICHA_VALUE = Table(
|
|
45
|
+
"v_ficha_value",
|
|
46
|
+
MetaData(),
|
|
47
|
+
Column("ficha_id", String()),
|
|
48
|
+
Column("attribute_id", String()),
|
|
49
|
+
schema=SCHEMA,
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, slots=True)
|
|
54
|
+
class Enrichment:
|
|
55
|
+
"""What one enrichment call did.
|
|
56
|
+
|
|
57
|
+
``selected`` are the fichas that got per-ficha work, untried ones first
|
|
58
|
+
(oldest pending first), then those due for a retry; those not already
|
|
59
|
+
``counted`` by the caller are what counts against ``max_items``.
|
|
60
|
+
``finished`` are those left with no pending PDF or extraction; the rest
|
|
61
|
+
stay pending, with their failed attempt recorded.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
selected: tuple[str, ...]
|
|
65
|
+
finished: tuple[str, ...]
|
|
66
|
+
pdf_requests: int
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True)
|
|
70
|
+
class _AttemptRecord:
|
|
71
|
+
"""A ficha's enrichment attempt record, as it was before an attempt."""
|
|
72
|
+
|
|
73
|
+
attempted_at: datetime | None
|
|
74
|
+
attempt_stamp: datetime | None
|
|
75
|
+
failures: int
|
|
76
|
+
retry_at: datetime | None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class _FetchedPdf:
|
|
81
|
+
text_sha256: str | None # None: the PDF has no extractable text
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class EnrichmentService:
|
|
85
|
+
"""Fetch PDFs and run the rules and LLM passes only where a query needs them."""
|
|
86
|
+
|
|
87
|
+
def __init__(
|
|
88
|
+
self,
|
|
89
|
+
session_factory: sessionmaker[Session],
|
|
90
|
+
client: HttpClient,
|
|
91
|
+
payload_store: PayloadStore,
|
|
92
|
+
extractor: Callable[[Session], ExtractService],
|
|
93
|
+
query_compiler: QueryCompiler,
|
|
94
|
+
*,
|
|
95
|
+
retry_base: timedelta,
|
|
96
|
+
retry_cap: timedelta,
|
|
97
|
+
now: Callable[[], datetime] | None = None,
|
|
98
|
+
) -> None:
|
|
99
|
+
"""``retry_base`` and ``retry_cap`` come from ``Settings.enrichment_retry_*``."""
|
|
100
|
+
validate_backoff(retry_base, retry_cap)
|
|
101
|
+
self._session_factory = session_factory
|
|
102
|
+
self._retry_base = retry_base
|
|
103
|
+
self._retry_cap = retry_cap
|
|
104
|
+
self._client = client
|
|
105
|
+
self._payload_store = payload_store
|
|
106
|
+
self._extractor = extractor
|
|
107
|
+
self._query_compiler = query_compiler
|
|
108
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
109
|
+
|
|
110
|
+
async def enrich(
|
|
111
|
+
self,
|
|
112
|
+
contract: ValidatedContract,
|
|
113
|
+
needs: Collection[str],
|
|
114
|
+
max_items: int,
|
|
115
|
+
*,
|
|
116
|
+
counted: Collection[str] = (),
|
|
117
|
+
) -> Enrichment:
|
|
118
|
+
"""Enrich up to ``max_items`` fichas the query still needs.
|
|
119
|
+
|
|
120
|
+
A ficha is selected when it is in the contract's scope, no predicate
|
|
121
|
+
rules it out on its current values (``QueryCompiler.still_matching``),
|
|
122
|
+
a needed attribute has no current value for it, and its PDF or its
|
|
123
|
+
extraction is still pending. Structural needs (agreement, catalogue,
|
|
124
|
+
category, department) come from the Excel and never need enrichment.
|
|
125
|
+
Each selected ficha is finished or left pending: its state is written
|
|
126
|
+
as each step completes, so an interruption leaves it pending.
|
|
127
|
+
|
|
128
|
+
Each attempt is recorded on the ficha when it starts. One that doesn't
|
|
129
|
+
finish the ficha (a failed PDF download or LLM pass, an error) counts
|
|
130
|
+
as a consecutive failure under the ficha's ``row_stamp``; the ficha is
|
|
131
|
+
then retried only after an exponential backoff, and only after every
|
|
132
|
+
untried ficha, so failures can't take ``max_items`` from fichas that
|
|
133
|
+
could finish. A finished attempt or a newer ``row_stamp`` resets it.
|
|
134
|
+
A rejected LLM credential or an unusable provider setup
|
|
135
|
+
(``LLMConfigurationError``) is a configuration error: the attempt
|
|
136
|
+
record is put back as it was and the error stops the call, so a wrong
|
|
137
|
+
key never puts fichas on backoff.
|
|
138
|
+
|
|
139
|
+
``max_items`` counts fichas across the whole sync call: ``counted`` are
|
|
140
|
+
the fichas the call already gave per-ficha work (its part-number
|
|
141
|
+
lookups). They don't take a second slot, so at most ``max_items``
|
|
142
|
+
distinct fichas get per-ficha work in the call.
|
|
143
|
+
"""
|
|
144
|
+
if max_items < 0:
|
|
145
|
+
raise ValueError("max_items must not be negative")
|
|
146
|
+
attributes = _attribute_needs(needs)
|
|
147
|
+
if not attributes or max_items == 0:
|
|
148
|
+
return Enrichment((), (), 0)
|
|
149
|
+
|
|
150
|
+
already_counted = sorted(set(counted))
|
|
151
|
+
budget = max_items - len(already_counted)
|
|
152
|
+
now = self._now()
|
|
153
|
+
with self._session_factory() as session:
|
|
154
|
+
# Fichas already counted cost no slot: every one that needs work is
|
|
155
|
+
# selected, then the rest of the budget goes to the others.
|
|
156
|
+
free = (
|
|
157
|
+
session.scalars(
|
|
158
|
+
self._candidates(contract, attributes, now).where(
|
|
159
|
+
Ficha.ficha_id.in_(already_counted)
|
|
160
|
+
)
|
|
161
|
+
).all()
|
|
162
|
+
if already_counted
|
|
163
|
+
else []
|
|
164
|
+
)
|
|
165
|
+
new = (
|
|
166
|
+
session.scalars(
|
|
167
|
+
self._candidates(contract, attributes, now)
|
|
168
|
+
.where(Ficha.ficha_id.not_in(already_counted))
|
|
169
|
+
.limit(budget)
|
|
170
|
+
).all()
|
|
171
|
+
if budget > 0
|
|
172
|
+
else []
|
|
173
|
+
)
|
|
174
|
+
selected = (*free, *new)
|
|
175
|
+
|
|
176
|
+
finished: list[str] = []
|
|
177
|
+
pdf_requests = 0
|
|
178
|
+
for ficha_id in selected:
|
|
179
|
+
# Recorded before any work, so an attempt cut off by an error counts.
|
|
180
|
+
failures, previous = self._record_attempt(ficha_id)
|
|
181
|
+
try:
|
|
182
|
+
done, requested = await self._enrich_ficha(ficha_id)
|
|
183
|
+
except LLMConfigurationError:
|
|
184
|
+
# A rejected LLM credential or an unusable provider setup is a
|
|
185
|
+
# configuration error, not this ficha's failure: the attempt
|
|
186
|
+
# doesn't count against its backoff, and the error stops the run.
|
|
187
|
+
self._restore_attempt(ficha_id, previous)
|
|
188
|
+
raise
|
|
189
|
+
pdf_requests += int(requested)
|
|
190
|
+
if done:
|
|
191
|
+
self._record_success(ficha_id)
|
|
192
|
+
finished.append(ficha_id)
|
|
193
|
+
else:
|
|
194
|
+
_LOGGER.info(
|
|
195
|
+
"ficha %s: enrichment attempt failed (%d in a row under this stamp); "
|
|
196
|
+
"retried after %s",
|
|
197
|
+
ficha_id,
|
|
198
|
+
failures,
|
|
199
|
+
self._backoff(failures),
|
|
200
|
+
)
|
|
201
|
+
return Enrichment(selected, tuple(finished), pdf_requests)
|
|
202
|
+
|
|
203
|
+
def _backoff(self, failures: int) -> timedelta:
|
|
204
|
+
"""The wait after ``failures`` consecutive failures: base doubled, capped."""
|
|
205
|
+
return backoff(failures, self._retry_base, self._retry_cap)
|
|
206
|
+
|
|
207
|
+
def retry_after(self, failures: int) -> timedelta:
|
|
208
|
+
"""Enrichment's retry policy, shared with the sync's rules pass for new inputs."""
|
|
209
|
+
return self._backoff(failures)
|
|
210
|
+
|
|
211
|
+
def _record_attempt(self, ficha_id: str) -> tuple[int, _AttemptRecord]:
|
|
212
|
+
"""Record an attempt as failed until it finishes.
|
|
213
|
+
|
|
214
|
+
Return the failure count and the attempt record it replaced. The count
|
|
215
|
+
runs under the ficha's current ``row_stamp``: an attempt under a newer
|
|
216
|
+
stamp starts again from 1.
|
|
217
|
+
"""
|
|
218
|
+
now = self._now()
|
|
219
|
+
with self._session_factory.begin() as session:
|
|
220
|
+
current = session.execute(
|
|
221
|
+
select(
|
|
222
|
+
Ficha.row_stamp,
|
|
223
|
+
Ficha.enrichment_attempted_at,
|
|
224
|
+
Ficha.enrichment_attempt_stamp,
|
|
225
|
+
Ficha.enrichment_failures,
|
|
226
|
+
Ficha.enrichment_retry_at,
|
|
227
|
+
).where(Ficha.ficha_id == ficha_id)
|
|
228
|
+
).one()
|
|
229
|
+
previous = _AttemptRecord(
|
|
230
|
+
current.enrichment_attempted_at,
|
|
231
|
+
current.enrichment_attempt_stamp,
|
|
232
|
+
current.enrichment_failures,
|
|
233
|
+
current.enrichment_retry_at,
|
|
234
|
+
)
|
|
235
|
+
same_stamp = current.enrichment_attempt_stamp == current.row_stamp
|
|
236
|
+
failures = (current.enrichment_failures if same_stamp else 0) + 1
|
|
237
|
+
session.execute(
|
|
238
|
+
update(Ficha)
|
|
239
|
+
.where(Ficha.ficha_id == ficha_id)
|
|
240
|
+
.values(
|
|
241
|
+
enrichment_attempted_at=now,
|
|
242
|
+
enrichment_attempt_stamp=current.row_stamp,
|
|
243
|
+
enrichment_failures=failures,
|
|
244
|
+
enrichment_retry_at=now + self._backoff(failures),
|
|
245
|
+
)
|
|
246
|
+
.execution_options(synchronize_session=False)
|
|
247
|
+
)
|
|
248
|
+
return failures, previous
|
|
249
|
+
|
|
250
|
+
def _restore_attempt(self, ficha_id: str, previous: _AttemptRecord) -> None:
|
|
251
|
+
"""Put back the attempt record an attempt that must not count replaced."""
|
|
252
|
+
with self._session_factory.begin() as session:
|
|
253
|
+
session.execute(
|
|
254
|
+
update(Ficha)
|
|
255
|
+
.where(Ficha.ficha_id == ficha_id)
|
|
256
|
+
.values(
|
|
257
|
+
enrichment_attempted_at=previous.attempted_at,
|
|
258
|
+
enrichment_attempt_stamp=previous.attempt_stamp,
|
|
259
|
+
enrichment_failures=previous.failures,
|
|
260
|
+
enrichment_retry_at=previous.retry_at,
|
|
261
|
+
)
|
|
262
|
+
.execution_options(synchronize_session=False)
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
def _record_success(self, ficha_id: str) -> None:
|
|
266
|
+
"""Clear the failure count and the retry time of a finished ficha."""
|
|
267
|
+
with self._session_factory.begin() as session:
|
|
268
|
+
session.execute(
|
|
269
|
+
update(Ficha)
|
|
270
|
+
.where(Ficha.ficha_id == ficha_id)
|
|
271
|
+
.values(enrichment_failures=0, enrichment_retry_at=None)
|
|
272
|
+
.execution_options(synchronize_session=False)
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
def needs_resolved(self, contract: ValidatedContract, needs: Collection[str]) -> bool:
|
|
276
|
+
"""Whether every needed attribute is resolved for the query's fichas.
|
|
277
|
+
|
|
278
|
+
True when no ficha in the contract's scope that is still matching has
|
|
279
|
+
a needed attribute without a current value while its PDF or its
|
|
280
|
+
extraction is still pending, whatever its retry backoff: enrichment
|
|
281
|
+
has nothing left to learn for this query. Structural needs are always
|
|
282
|
+
resolved. No request; one read.
|
|
283
|
+
"""
|
|
284
|
+
attributes = _attribute_needs(needs)
|
|
285
|
+
if not attributes:
|
|
286
|
+
return True
|
|
287
|
+
with self._session_factory() as session:
|
|
288
|
+
return session.scalar(self._unresolved(contract, attributes).limit(1)) is None
|
|
289
|
+
|
|
290
|
+
def _unresolved(self, contract: ValidatedContract, attributes: list[str]) -> Select[str]:
|
|
291
|
+
"""Still-matching fichas with a needed attribute unresolved and work pending."""
|
|
292
|
+
resolved_needs = (
|
|
293
|
+
select(func.count(func.distinct(_FICHA_VALUE.c.attribute_id)))
|
|
294
|
+
.where(
|
|
295
|
+
_FICHA_VALUE.c.ficha_id == Ficha.ficha_id,
|
|
296
|
+
_FICHA_VALUE.c.attribute_id.in_(attributes),
|
|
297
|
+
)
|
|
298
|
+
.scalar_subquery()
|
|
299
|
+
)
|
|
300
|
+
return self._query_compiler.still_matching(contract).where(
|
|
301
|
+
or_(Ficha.pdf_pending, Ficha.extraction_pending),
|
|
302
|
+
resolved_needs < len(attributes),
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
def _candidates(
|
|
306
|
+
self, contract: ValidatedContract, attributes: list[str], now: datetime
|
|
307
|
+
) -> Select[str]:
|
|
308
|
+
# No failure recorded under the ficha's current row_stamp: never
|
|
309
|
+
# attempted, last attempt finished, or the site has a newer stamp.
|
|
310
|
+
untried = or_(
|
|
311
|
+
Ficha.enrichment_failures == 0,
|
|
312
|
+
Ficha.enrichment_attempt_stamp.is_(None),
|
|
313
|
+
Ficha.enrichment_attempt_stamp < Ficha.row_stamp,
|
|
314
|
+
)
|
|
315
|
+
return (
|
|
316
|
+
self._unresolved(contract, attributes)
|
|
317
|
+
.where(
|
|
318
|
+
# A failed ficha waits out its backoff.
|
|
319
|
+
or_(
|
|
320
|
+
untried,
|
|
321
|
+
Ficha.enrichment_retry_at.is_(None),
|
|
322
|
+
Ficha.enrichment_retry_at <= now,
|
|
323
|
+
),
|
|
324
|
+
)
|
|
325
|
+
.order_by(
|
|
326
|
+
# Untried fichas first, so failures can never fill max_items
|
|
327
|
+
# while another ficha could still be enriched.
|
|
328
|
+
case((untried, 0), else_=1),
|
|
329
|
+
# Failed fichas: the longest overdue first.
|
|
330
|
+
case((untried, null()), else_=Ficha.enrichment_retry_at),
|
|
331
|
+
# Oldest pending first: the fichas first seen earliest, then by id.
|
|
332
|
+
Ficha.first_seen_at,
|
|
333
|
+
Ficha.ficha_id,
|
|
334
|
+
)
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
async def _enrich_ficha(self, ficha_id: str) -> tuple[bool, bool]:
|
|
338
|
+
"""Return whether the ficha finished, and whether its PDF was requested.
|
|
339
|
+
|
|
340
|
+
A ficha whose own stored extraction input (or PDF text) is corrupt or
|
|
341
|
+
invalid (``InvalidExtractionInputError``) is not finished: the attempt
|
|
342
|
+
recorded before the work stands as a failure, its backoff applies and
|
|
343
|
+
the next ficha is enriched. Any other error propagates.
|
|
344
|
+
"""
|
|
345
|
+
progress = {"requested": False}
|
|
346
|
+
try:
|
|
347
|
+
return await self._enrich_ficha_steps(ficha_id, progress)
|
|
348
|
+
except InvalidExtractionInputError:
|
|
349
|
+
_LOGGER.warning(
|
|
350
|
+
"ficha %s: stored extraction input is unusable; enrichment attempt failed",
|
|
351
|
+
ficha_id,
|
|
352
|
+
exc_info=True,
|
|
353
|
+
)
|
|
354
|
+
return False, progress["requested"]
|
|
355
|
+
|
|
356
|
+
async def _enrich_ficha_steps(
|
|
357
|
+
self, ficha_id: str, progress: dict[str, bool]
|
|
358
|
+
) -> tuple[bool, bool]:
|
|
359
|
+
with self._session_factory() as session:
|
|
360
|
+
pdf_url = session.scalar(select(Ficha.pdf_url).where(Ficha.ficha_id == ficha_id))
|
|
361
|
+
known = (
|
|
362
|
+
session.execute(select(Pdf.text_sha256).where(Pdf.pdf_url == pdf_url)).first()
|
|
363
|
+
if pdf_url is not None
|
|
364
|
+
else None
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
requested = False
|
|
368
|
+
if pdf_url is not None:
|
|
369
|
+
if known is None:
|
|
370
|
+
# A known URL is never fetched again: file name = version.
|
|
371
|
+
requested = True
|
|
372
|
+
progress["requested"] = True
|
|
373
|
+
fetched = await self._fetch_pdf(ficha_id, pdf_url)
|
|
374
|
+
if fetched is None:
|
|
375
|
+
return False, requested
|
|
376
|
+
text_sha256 = fetched.text_sha256
|
|
377
|
+
else:
|
|
378
|
+
text_sha256 = known.text_sha256
|
|
379
|
+
if not self._apply_pdf_text(ficha_id, pdf_url, text_sha256):
|
|
380
|
+
return False, requested
|
|
381
|
+
return await self._extract(ficha_id), requested
|
|
382
|
+
|
|
383
|
+
async def _fetch_pdf(self, ficha_id: str, pdf_url: str) -> _FetchedPdf | None:
|
|
384
|
+
"""Download, parse and record a PDF; ``None`` if it could not be fetched."""
|
|
385
|
+
response = await get_pdf_response(self._client, pdf_url)
|
|
386
|
+
request_id = cast(str, response.extensions["request_id"])
|
|
387
|
+
if response.status_code != 200 or response.extensions["is_error_page"]:
|
|
388
|
+
# Logged by write_request; the ficha stays pdf_pending for a retry.
|
|
389
|
+
_LOGGER.warning(
|
|
390
|
+
"ficha %s: PDF %s returned HTTP %s%s; left pending",
|
|
391
|
+
ficha_id,
|
|
392
|
+
pdf_url,
|
|
393
|
+
response.status_code,
|
|
394
|
+
" (error page)" if response.extensions["is_error_page"] else "",
|
|
395
|
+
)
|
|
396
|
+
return None
|
|
397
|
+
|
|
398
|
+
text: bytes | None
|
|
399
|
+
page_count: int | None
|
|
400
|
+
try:
|
|
401
|
+
text, page_count = parse_pdf_text(response.content)
|
|
402
|
+
except Exception as error: # noqa: BLE001 - any failure to read untrusted bytes
|
|
403
|
+
# The URL is immutable, so a PDF that can't be read is recorded
|
|
404
|
+
# without text instead of being downloaded again. pypdf raises
|
|
405
|
+
# more than PyPdfError on malformed input (AttributeError,
|
|
406
|
+
# ValueError, KeyError, ...), so every parse failure counts.
|
|
407
|
+
_LOGGER.warning("ficha %s: PDF %s could not be parsed: %s", ficha_id, pdf_url, error)
|
|
408
|
+
text, page_count = None, None
|
|
409
|
+
if text is not None and not text.strip():
|
|
410
|
+
text = None
|
|
411
|
+
|
|
412
|
+
stored_at = self._now()
|
|
413
|
+
with self._session_factory.begin() as session:
|
|
414
|
+
payload_sha256 = session.scalar(
|
|
415
|
+
select(RequestLog.payload_sha256).where(RequestLog.request_id == request_id)
|
|
416
|
+
)
|
|
417
|
+
if payload_sha256 is None:
|
|
418
|
+
raise RuntimeError("PDF response has no stored payload")
|
|
419
|
+
text_sha256: str | None = None
|
|
420
|
+
if text is not None:
|
|
421
|
+
# Derived text is stored as a new payload, beside the raw PDF.
|
|
422
|
+
text_sha256 = self._payload_store.put(text, _PDF_TEXT_CONTENT_TYPE)
|
|
423
|
+
upsert(
|
|
424
|
+
session,
|
|
425
|
+
Payload,
|
|
426
|
+
[
|
|
427
|
+
{
|
|
428
|
+
"payload_sha256": text_sha256,
|
|
429
|
+
"content_type": _PDF_TEXT_CONTENT_TYPE,
|
|
430
|
+
"size_bytes": len(text),
|
|
431
|
+
"storage_uri": self._payload_store.storage_uri(text_sha256),
|
|
432
|
+
"stored_at": stored_at,
|
|
433
|
+
}
|
|
434
|
+
],
|
|
435
|
+
)
|
|
436
|
+
upsert(
|
|
437
|
+
session,
|
|
438
|
+
Pdf,
|
|
439
|
+
[
|
|
440
|
+
{
|
|
441
|
+
"pdf_url": pdf_url,
|
|
442
|
+
"ficha_id": ficha_id,
|
|
443
|
+
"request_id": request_id,
|
|
444
|
+
"payload_sha256": payload_sha256,
|
|
445
|
+
"text_sha256": text_sha256,
|
|
446
|
+
"page_count": page_count,
|
|
447
|
+
}
|
|
448
|
+
],
|
|
449
|
+
)
|
|
450
|
+
# ``pdf`` is append-only: if another run recorded this URL first,
|
|
451
|
+
# its row is the one that counts.
|
|
452
|
+
stored_text = session.execute(
|
|
453
|
+
select(Pdf.text_sha256).where(Pdf.pdf_url == pdf_url)
|
|
454
|
+
).one()
|
|
455
|
+
return _FetchedPdf(stored_text.text_sha256)
|
|
456
|
+
|
|
457
|
+
def _apply_pdf_text(self, ficha_id: str, pdf_url: str, text_sha256: str | None) -> bool:
|
|
458
|
+
"""Put the PDF text into the ficha's input and clear ``pdf_pending``."""
|
|
459
|
+
for _ in range(_INPUT_HASH_ATTEMPTS):
|
|
460
|
+
with self._session_factory.begin() as session:
|
|
461
|
+
current = session.execute(
|
|
462
|
+
select(Ficha.input_hash, Ficha.input_pdf_text_sha256).where(
|
|
463
|
+
Ficha.ficha_id == ficha_id, Ficha.pdf_url == pdf_url
|
|
464
|
+
)
|
|
465
|
+
).first()
|
|
466
|
+
if current is None:
|
|
467
|
+
# The Excel step replaced the PDF URL meanwhile: the new
|
|
468
|
+
# version is pending, not this one.
|
|
469
|
+
return False
|
|
470
|
+
input_hash = current.input_hash
|
|
471
|
+
values: dict[str, object] = {"pdf_pending": False}
|
|
472
|
+
# A ficha without a canonical input yet only records the PDF: the
|
|
473
|
+
# Excel step builds its input from the stored text later.
|
|
474
|
+
if input_hash is not None and current.input_pdf_text_sha256 != text_sha256:
|
|
475
|
+
# The PDF text is part of the ficha's input: a corrupt one
|
|
476
|
+
# is the ficha's own failure, a missing one fails fast.
|
|
477
|
+
pdf_text = (
|
|
478
|
+
read_input_payload(self._payload_store, text_sha256)
|
|
479
|
+
if text_sha256 is not None
|
|
480
|
+
else None
|
|
481
|
+
)
|
|
482
|
+
refreshed_hash, size_bytes = rebuild_pdf_input(
|
|
483
|
+
input_hash, pdf_text, self._payload_store
|
|
484
|
+
)
|
|
485
|
+
values["input_pdf_text_sha256"] = text_sha256
|
|
486
|
+
if refreshed_hash != input_hash:
|
|
487
|
+
upsert(
|
|
488
|
+
session,
|
|
489
|
+
Payload,
|
|
490
|
+
[
|
|
491
|
+
{
|
|
492
|
+
"payload_sha256": refreshed_hash,
|
|
493
|
+
"content_type": "application/json",
|
|
494
|
+
"size_bytes": size_bytes,
|
|
495
|
+
"storage_uri": self._payload_store.storage_uri(refreshed_hash),
|
|
496
|
+
"stored_at": self._now(),
|
|
497
|
+
}
|
|
498
|
+
],
|
|
499
|
+
)
|
|
500
|
+
values["input_hash"] = refreshed_hash
|
|
501
|
+
# The stored extraction no longer matches the current input.
|
|
502
|
+
values["extraction_pending"] = True
|
|
503
|
+
# Compare-and-set on the input the new one was built from: another
|
|
504
|
+
# step (Excel, cards) may have replaced it since it was read.
|
|
505
|
+
result = cast(
|
|
506
|
+
CursorResult[Any],
|
|
507
|
+
session.execute(
|
|
508
|
+
update(Ficha)
|
|
509
|
+
.where(
|
|
510
|
+
Ficha.ficha_id == ficha_id,
|
|
511
|
+
Ficha.pdf_url == pdf_url,
|
|
512
|
+
Ficha.input_hash.is_(None)
|
|
513
|
+
if input_hash is None
|
|
514
|
+
else Ficha.input_hash == input_hash,
|
|
515
|
+
)
|
|
516
|
+
.values(values)
|
|
517
|
+
.execution_options(synchronize_session=False)
|
|
518
|
+
),
|
|
519
|
+
)
|
|
520
|
+
if result.rowcount:
|
|
521
|
+
return True
|
|
522
|
+
_LOGGER.warning("ficha %s: canonical input kept changing; PDF left pending", ficha_id)
|
|
523
|
+
return False
|
|
524
|
+
|
|
525
|
+
async def _extract(self, ficha_id: str) -> bool:
|
|
526
|
+
"""Run the rules pass, then the LLM pass only if a residue remains."""
|
|
527
|
+
with self._session_factory() as session:
|
|
528
|
+
ficha = session.get(Ficha, ficha_id)
|
|
529
|
+
if ficha is None or ficha.input_hash is None:
|
|
530
|
+
return False
|
|
531
|
+
extractor = self._extractor(session)
|
|
532
|
+
rules = extractor.rules_pass(ficha)
|
|
533
|
+
session.commit()
|
|
534
|
+
if rules.residue:
|
|
535
|
+
outcome = await extractor.llm_pass(ficha)
|
|
536
|
+
# ``pending`` (another run holds the claim) and ``failed`` leave
|
|
537
|
+
# the ficha pending; ``skipped`` means no residue was left.
|
|
538
|
+
if outcome.status not in {"ok", "skipped"}:
|
|
539
|
+
return False
|
|
540
|
+
# Finished only for the input the passes ran on: a newer input
|
|
541
|
+
# committed meanwhile keeps the ficha pending.
|
|
542
|
+
result = cast(
|
|
543
|
+
CursorResult[Any],
|
|
544
|
+
session.execute(
|
|
545
|
+
update(Ficha)
|
|
546
|
+
.where(Ficha.ficha_id == ficha_id, Ficha.input_hash == rules.input_hash)
|
|
547
|
+
.values(extraction_pending=False)
|
|
548
|
+
.execution_options(synchronize_session=False)
|
|
549
|
+
),
|
|
550
|
+
)
|
|
551
|
+
session.commit()
|
|
552
|
+
return bool(result.rowcount)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def _attribute_needs(needs: Collection[str]) -> list[str]:
|
|
556
|
+
"""The needed attributes; structural fields come from the Excel, never enrichment."""
|
|
557
|
+
return sorted({need for need in needs if need not in STRUCTURAL_FIELDS})
|
piloto_ai_cli/errors.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Typed errors for refusals of CLI query contracts."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from enum import StrEnum
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class ContractErrorCode(StrEnum):
|
|
8
|
+
"""Machine-readable reasons a contract cannot be processed."""
|
|
9
|
+
|
|
10
|
+
SCHEMA_VIOLATION = "schema_violation"
|
|
11
|
+
UNKNOWN_ATTRIBUTE = "unknown_attribute"
|
|
12
|
+
UNIT_NOT_CONVERTIBLE = "unit_not_convertible"
|
|
13
|
+
BAD_OP_FOR_KIND = "bad_op_for_kind"
|
|
14
|
+
DEPARTMENT_UNAVAILABLE = "department_unavailable"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ParseError(ValueError):
|
|
18
|
+
"""A site response could not be parsed according to its expected structure."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InvalidExtractionInputError(ValueError):
|
|
22
|
+
"""A ficha's stored extraction input is corrupt or not a JSON object.
|
|
23
|
+
|
|
24
|
+
A failure of that ficha's own data, as opposed to configuration, storage
|
|
25
|
+
or database errors, which must propagate.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ReviewError(Exception):
|
|
30
|
+
"""A proposal cannot be reviewed in its current state."""
|
|
31
|
+
|
|
32
|
+
code = "review_conflict"
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str) -> None:
|
|
35
|
+
if not message:
|
|
36
|
+
raise ValueError("message cannot be empty")
|
|
37
|
+
self.message = message
|
|
38
|
+
super().__init__(message)
|
|
39
|
+
|
|
40
|
+
def __str__(self) -> str:
|
|
41
|
+
return f"{self.code}: {self.message}"
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, str]:
|
|
44
|
+
"""Return the JSON-ready refusal fields."""
|
|
45
|
+
return {"code": self.code, "message": self.message}
|
|
46
|
+
|
|
47
|
+
def to_json(self) -> str:
|
|
48
|
+
"""Serialize the refusal fields as deterministic JSON."""
|
|
49
|
+
return json.dumps(self.to_dict(), ensure_ascii=False, sort_keys=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
ErrorLocation = int | str
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ContractError(Exception):
|
|
56
|
+
"""A machine-readable contract refusal with a terminal-readable message."""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
code: ContractErrorCode,
|
|
61
|
+
location: ErrorLocation,
|
|
62
|
+
message: str,
|
|
63
|
+
) -> None:
|
|
64
|
+
if isinstance(location, bool) or not isinstance(location, (int, str)):
|
|
65
|
+
raise TypeError("location must be a predicate index or scope field")
|
|
66
|
+
if isinstance(location, int) and location < 0:
|
|
67
|
+
raise ValueError("predicate index cannot be negative")
|
|
68
|
+
if not isinstance(location, int) and not location:
|
|
69
|
+
raise ValueError("scope field cannot be empty")
|
|
70
|
+
if not message:
|
|
71
|
+
raise ValueError("message cannot be empty")
|
|
72
|
+
|
|
73
|
+
self.code = code
|
|
74
|
+
self.location = location
|
|
75
|
+
self.message = message
|
|
76
|
+
super().__init__(message)
|
|
77
|
+
|
|
78
|
+
def __str__(self) -> str:
|
|
79
|
+
location = f"predicate {self.location}" if isinstance(self.location, int) else self.location
|
|
80
|
+
return f"{self.code.value} at {location}: {self.message}"
|
|
81
|
+
|
|
82
|
+
def to_dict(self) -> dict[str, str | int]:
|
|
83
|
+
"""Return the JSON-ready refusal fields."""
|
|
84
|
+
return {
|
|
85
|
+
"code": self.code.value,
|
|
86
|
+
"location": self.location,
|
|
87
|
+
"message": self.message,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
def to_json(self) -> str:
|
|
91
|
+
"""Serialize the refusal fields as deterministic JSON."""
|
|
92
|
+
return json.dumps(self.to_dict(), ensure_ascii=False, sort_keys=True)
|