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,747 @@
|
|
|
1
|
+
"""piloto-ai-cli schema v2, as SQLAlchemy 2.0 models.
|
|
2
|
+
|
|
3
|
+
This file is the single source of the schema (proposal-v2.md §7): the ERDs
|
|
4
|
+
in docs/data-model.md are drawn from it, and the first Alembic migration will
|
|
5
|
+
be generated from it. Snowflake enforces only NOT NULL, so every primary,
|
|
6
|
+
unique and foreign key below is declared for the ORM and enforced by the
|
|
7
|
+
CLI's write path (one upsert helper that MERGEs on the declared key). On an
|
|
8
|
+
engine that enforces constraints, the same declarations become real ones.
|
|
9
|
+
|
|
10
|
+
Conventions:
|
|
11
|
+
- UUID strings for events (run, request, extraction, price observation).
|
|
12
|
+
- SHA-256 hex for content (payload, excel_hash, input_hash).
|
|
13
|
+
- The site's own ids where they exist (agreement_id, ficha_id).
|
|
14
|
+
- Site stamps ("Información actualizada al ...") are Lima-time TIMESTAMP_NTZ,
|
|
15
|
+
compared only with each other, never with the CLI's clock.
|
|
16
|
+
- Append-only, nothing deleted. The only in-place updates allowed are current
|
|
17
|
+
state (`agreement` with its Excel checkpoint, `ficha`, `department_sync`,
|
|
18
|
+
and the stamp and request of `ficha_department`), lifecycle closure
|
|
19
|
+
(`run_log`, `extraction` status, usage and `request_id`), review decisions
|
|
20
|
+
(status, `accepted_at`, `merged_into` on `attribute`, `alias`, `unit_rule`)
|
|
21
|
+
and pane refresh (`seed_value.last_request_id`). See docs/data-model.md §1.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
from collections.abc import Callable
|
|
28
|
+
from datetime import UTC, date, datetime
|
|
29
|
+
from decimal import Decimal
|
|
30
|
+
from typing import Any, ClassVar
|
|
31
|
+
|
|
32
|
+
from sqlalchemy import (
|
|
33
|
+
JSON,
|
|
34
|
+
Boolean,
|
|
35
|
+
Date,
|
|
36
|
+
DateTime,
|
|
37
|
+
ForeignKey,
|
|
38
|
+
Integer,
|
|
39
|
+
Numeric,
|
|
40
|
+
String,
|
|
41
|
+
Text,
|
|
42
|
+
TypeDecorator,
|
|
43
|
+
UniqueConstraint,
|
|
44
|
+
text,
|
|
45
|
+
)
|
|
46
|
+
from sqlalchemy.engine.interfaces import Dialect
|
|
47
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
48
|
+
from sqlalchemy.sql.type_api import TypeEngine
|
|
49
|
+
|
|
50
|
+
SCHEMA = "cli"
|
|
51
|
+
|
|
52
|
+
UUID = String(36)
|
|
53
|
+
SHA256 = String(64)
|
|
54
|
+
MONEY = Numeric(18, 2)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class TimestampNTZ(TypeDecorator[datetime]):
|
|
58
|
+
"""A timezone-naive timestamp, stored as TIMESTAMP_NTZ on Snowflake."""
|
|
59
|
+
|
|
60
|
+
impl = DateTime
|
|
61
|
+
cache_ok = True
|
|
62
|
+
|
|
63
|
+
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
|
64
|
+
if dialect.name == "snowflake":
|
|
65
|
+
from snowflake.sqlalchemy import TIMESTAMP_NTZ # type: ignore[attr-defined]
|
|
66
|
+
|
|
67
|
+
return dialect.type_descriptor(TIMESTAMP_NTZ())
|
|
68
|
+
return dialect.type_descriptor(DateTime(timezone=False))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
STAMP = TimestampNTZ() # TIMESTAMP_NTZ: the site's stamp, Lima time
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class TimestampTZ(TypeDecorator[datetime]):
|
|
75
|
+
"""An offset-aware timestamp, stored as TIMESTAMP_TZ on Snowflake.
|
|
76
|
+
|
|
77
|
+
SQLite has no timezone-aware type: SQLAlchemy would store the wall-clock
|
|
78
|
+
value without its offset and read back a naive datetime. On SQLite the
|
|
79
|
+
value is therefore normalised to UTC on write and read back as aware UTC,
|
|
80
|
+
which preserves the instant.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
impl = DateTime(timezone=True)
|
|
84
|
+
cache_ok = True
|
|
85
|
+
|
|
86
|
+
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
|
87
|
+
if dialect.name == "sqlite":
|
|
88
|
+
return dialect.type_descriptor(DateTime(timezone=False))
|
|
89
|
+
return dialect.type_descriptor(DateTime(timezone=True))
|
|
90
|
+
|
|
91
|
+
def process_bind_param(self, value: datetime | None, dialect: Dialect) -> datetime | None:
|
|
92
|
+
if value is None:
|
|
93
|
+
return None
|
|
94
|
+
if value.tzinfo is None or value.utcoffset() is None:
|
|
95
|
+
raise ValueError("TS values must be timezone-aware datetimes")
|
|
96
|
+
if dialect.name == "sqlite":
|
|
97
|
+
return value.astimezone(UTC).replace(tzinfo=None)
|
|
98
|
+
return value
|
|
99
|
+
|
|
100
|
+
def process_result_value(self, value: datetime | None, dialect: Dialect) -> datetime | None:
|
|
101
|
+
if value is None:
|
|
102
|
+
return None
|
|
103
|
+
if dialect.name == "sqlite":
|
|
104
|
+
return value.replace(tzinfo=UTC)
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
TS = TimestampTZ() # TIMESTAMP_TZ: our own clock
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class JSONDoc(TypeDecorator[Any]):
|
|
112
|
+
"""A JSON document: VARIANT on Snowflake, the generic JSON type elsewhere.
|
|
113
|
+
|
|
114
|
+
Snowflake's VARIANT doesn't (de)serialize Python values, so on Snowflake
|
|
115
|
+
values are written as JSON text through PARSE_JSON and parsed on read.
|
|
116
|
+
Other engines use SQLAlchemy's JSON type unchanged.
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
impl = JSON
|
|
120
|
+
cache_ok = True
|
|
121
|
+
|
|
122
|
+
def load_dialect_impl(self, dialect: Dialect) -> TypeEngine[Any]:
|
|
123
|
+
if dialect.name == "snowflake":
|
|
124
|
+
from snowflake.sqlalchemy import VARIANT # type: ignore[attr-defined]
|
|
125
|
+
|
|
126
|
+
return dialect.type_descriptor(VARIANT())
|
|
127
|
+
return dialect.type_descriptor(JSON())
|
|
128
|
+
|
|
129
|
+
def bind_processor(self, dialect: Dialect) -> Callable[[Any], Any] | None:
|
|
130
|
+
if dialect.name == "snowflake":
|
|
131
|
+
return lambda value: self.process_bind_param(value, dialect)
|
|
132
|
+
return super().bind_processor(dialect)
|
|
133
|
+
|
|
134
|
+
def process_bind_param(self, value: Any, dialect: Dialect) -> Any:
|
|
135
|
+
if dialect.name == "snowflake" and value is not None:
|
|
136
|
+
return json.dumps(value, sort_keys=True, ensure_ascii=False)
|
|
137
|
+
return value
|
|
138
|
+
|
|
139
|
+
def process_result_value(self, value: Any, dialect: Dialect) -> Any:
|
|
140
|
+
if dialect.name == "snowflake" and isinstance(value, str):
|
|
141
|
+
return json.loads(value)
|
|
142
|
+
return value
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# On Snowflake, a VARIANT can't take a JSON string bind directly in an INSERT;
|
|
146
|
+
# the upsert helper writes JSONDoc columns with PARSE_JSON(:value) in its MERGE
|
|
147
|
+
# (the only write path, see docs/data-model.md §1).
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Base(DeclarativeBase):
|
|
151
|
+
__table_args__: dict[str, Any] | tuple[Any, ...]
|
|
152
|
+
__table_args__ = {"schema": SCHEMA}
|
|
153
|
+
__updatable__: ClassVar[frozenset[str]] = frozenset()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# ---------------------------------------------------------------------------
|
|
157
|
+
# Raw side: append-only, for lineage and offline re-extraction
|
|
158
|
+
# ---------------------------------------------------------------------------
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class RunLog(Base):
|
|
162
|
+
"""One CLI command execution."""
|
|
163
|
+
|
|
164
|
+
__tablename__ = "run_log"
|
|
165
|
+
__updatable__ = frozenset({"finished_at", "outcome", "query_ids"})
|
|
166
|
+
|
|
167
|
+
run_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
168
|
+
command: Mapped[str] = mapped_column(
|
|
169
|
+
String
|
|
170
|
+
) # query, attributes, sync, review, reextract, health
|
|
171
|
+
arguments: Mapped[dict[str, Any]] = mapped_column(JSONDoc()) # e.g. the predicate document
|
|
172
|
+
started_at: Mapped[datetime] = mapped_column(TS)
|
|
173
|
+
finished_at: Mapped[datetime | None] = mapped_column(TS)
|
|
174
|
+
outcome: Mapped[str | None] = mapped_column(String) # ok, refused, failed
|
|
175
|
+
query_ids: Mapped[list[Any] | None] = mapped_column(JSONDoc()) # Snowflake query ids it ran
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class Payload(Base):
|
|
179
|
+
"""One stored response body (or derived text), keyed by its hash."""
|
|
180
|
+
|
|
181
|
+
__tablename__ = "payload"
|
|
182
|
+
|
|
183
|
+
payload_sha256: Mapped[str] = mapped_column(SHA256, primary_key=True)
|
|
184
|
+
content_type: Mapped[str] = mapped_column(
|
|
185
|
+
String
|
|
186
|
+
) # text/html, application/vnd...sheet, application/pdf, application/json
|
|
187
|
+
size_bytes: Mapped[int] = mapped_column(Integer)
|
|
188
|
+
storage_uri: Mapped[str] = mapped_column(String) # stage path of the stored file
|
|
189
|
+
stored_at: Mapped[datetime] = mapped_column(TS)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class RequestLog(Base):
|
|
193
|
+
"""One HTTP request, committed before any parsing, whatever the outcome."""
|
|
194
|
+
|
|
195
|
+
__tablename__ = "request_log"
|
|
196
|
+
|
|
197
|
+
request_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
198
|
+
run_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.run_log.run_id"))
|
|
199
|
+
endpoint: Mapped[str] = mapped_column(
|
|
200
|
+
String
|
|
201
|
+
) # get_home, post_download, post_search, get_pdf, post_llm
|
|
202
|
+
url: Mapped[str] = mapped_column(String)
|
|
203
|
+
http_method: Mapped[str] = mapped_column(String)
|
|
204
|
+
request_form: Mapped[dict[str, Any] | None] = mapped_column(
|
|
205
|
+
JSONDoc()
|
|
206
|
+
) # antiforgery token stripped; never credentials
|
|
207
|
+
requested_at: Mapped[datetime] = mapped_column(TS)
|
|
208
|
+
duration_ms: Mapped[int | None] = mapped_column(Integer)
|
|
209
|
+
http_status: Mapped[int | None] = mapped_column(Integer) # NULL on timeout or no connection
|
|
210
|
+
is_error_page: Mapped[bool] = mapped_column(
|
|
211
|
+
Boolean
|
|
212
|
+
) # HTTP 200 carrying the site's generic error page
|
|
213
|
+
error: Mapped[str | None] = mapped_column(Text)
|
|
214
|
+
payload_sha256: Mapped[str | None] = mapped_column(
|
|
215
|
+
ForeignKey(f"{SCHEMA}.payload.payload_sha256")
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# ---------------------------------------------------------------------------
|
|
220
|
+
# Clean side: catalog
|
|
221
|
+
# ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class Agreement(Base):
|
|
225
|
+
"""One agreement as listed on GET /, plus its Excel checkpoint.
|
|
226
|
+
|
|
227
|
+
The `excel_*` columns are the checkpoint: the newest stamp a complete Excel
|
|
228
|
+
export of the agreement was loaded under. They're NULL until the first
|
|
229
|
+
export, written in the same transaction as that export's ficha upsert,
|
|
230
|
+
and only moved forward (UPDATE ... WHERE excel_stamp IS NULL OR
|
|
231
|
+
excel_stamp < :new). The GET / refresh never touches them.
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
__tablename__ = "agreement"
|
|
235
|
+
__updatable__ = frozenset(
|
|
236
|
+
{
|
|
237
|
+
"name",
|
|
238
|
+
"status",
|
|
239
|
+
"type",
|
|
240
|
+
"ficha_count",
|
|
241
|
+
"filter_value",
|
|
242
|
+
"last_request_id",
|
|
243
|
+
"last_seen_at",
|
|
244
|
+
"excel_stamp",
|
|
245
|
+
"excel_synced_at",
|
|
246
|
+
"excel_request_id",
|
|
247
|
+
"excel_ficha_count",
|
|
248
|
+
}
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
agreement_id: Mapped[str] = mapped_column(String, primary_key=True) # e.g. EXT-CE-2022-5
|
|
252
|
+
name: Mapped[str] = mapped_column(String)
|
|
253
|
+
status: Mapped[str] = mapped_column(String) # VIGENTE, ...
|
|
254
|
+
type: Mapped[str | None] = mapped_column(String) # BIENES, ...
|
|
255
|
+
ficha_count: Mapped[int | None] = mapped_column(Integer)
|
|
256
|
+
filter_value: Mapped[str] = mapped_column(
|
|
257
|
+
String
|
|
258
|
+
) # data-agreement, sent as ClientFilter.Agreement
|
|
259
|
+
last_request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
260
|
+
first_seen_at: Mapped[datetime] = mapped_column(TS)
|
|
261
|
+
last_seen_at: Mapped[datetime] = mapped_column(TS)
|
|
262
|
+
# Excel checkpoint (NULL until the first complete export)
|
|
263
|
+
excel_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
264
|
+
excel_synced_at: Mapped[datetime | None] = mapped_column(TS)
|
|
265
|
+
excel_request_id: Mapped[str | None] = mapped_column(
|
|
266
|
+
ForeignKey(f"{SCHEMA}.request_log.request_id")
|
|
267
|
+
)
|
|
268
|
+
excel_ficha_count: Mapped[int | None] = mapped_column(Integer)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class Ficha(Base):
|
|
272
|
+
"""One product sheet, with its per-ficha sync state."""
|
|
273
|
+
|
|
274
|
+
__tablename__ = "ficha"
|
|
275
|
+
__updatable__ = frozenset(
|
|
276
|
+
{
|
|
277
|
+
"agreement_id",
|
|
278
|
+
"catalogue",
|
|
279
|
+
"category",
|
|
280
|
+
"description",
|
|
281
|
+
"marca",
|
|
282
|
+
"nro_parte",
|
|
283
|
+
"estado",
|
|
284
|
+
"pdf_url",
|
|
285
|
+
"excel_hash",
|
|
286
|
+
"row_stamp",
|
|
287
|
+
"excel_stamp",
|
|
288
|
+
"excel_request_id",
|
|
289
|
+
"card_stamp",
|
|
290
|
+
"card_paged_stamp",
|
|
291
|
+
"card_lookup_stamp",
|
|
292
|
+
"card_lookup_failure_stamp",
|
|
293
|
+
"card_lookup_failures",
|
|
294
|
+
"card_lookup_retry_at",
|
|
295
|
+
"input_hash",
|
|
296
|
+
"input_card_stamp",
|
|
297
|
+
"input_pdf_text_sha256",
|
|
298
|
+
"card_pending",
|
|
299
|
+
"pdf_pending",
|
|
300
|
+
"extraction_pending",
|
|
301
|
+
"enrichment_attempted_at",
|
|
302
|
+
"enrichment_attempt_stamp",
|
|
303
|
+
"enrichment_failures",
|
|
304
|
+
"enrichment_retry_at",
|
|
305
|
+
"rules_failed_input_hash",
|
|
306
|
+
"rules_failures",
|
|
307
|
+
"rules_retry_at",
|
|
308
|
+
"last_seen_at",
|
|
309
|
+
}
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
# e.g. 1763644; the Excel has no id column, so it is the numeric prefix of
|
|
313
|
+
# the PDF/image file name.
|
|
314
|
+
ficha_id: Mapped[str] = mapped_column(String, primary_key=True)
|
|
315
|
+
agreement_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.agreement.agreement_id"))
|
|
316
|
+
catalogue: Mapped[str | None] = mapped_column(String)
|
|
317
|
+
category: Mapped[str | None] = mapped_column(String)
|
|
318
|
+
description: Mapped[str | None] = mapped_column(Text)
|
|
319
|
+
marca: Mapped[str | None] = mapped_column(String)
|
|
320
|
+
nro_parte: Mapped[str | None] = mapped_column(String)
|
|
321
|
+
estado: Mapped[str | None] = mapped_column(String)
|
|
322
|
+
pdf_url: Mapped[str | None] = mapped_column(String)
|
|
323
|
+
# Sync state (proposal-v2 §4)
|
|
324
|
+
excel_hash: Mapped[str] = mapped_column(SHA256) # raw Excel row fields
|
|
325
|
+
# The newer-stamp write guard: stamp of the latest Excel row written (full
|
|
326
|
+
# or department export).
|
|
327
|
+
row_stamp: Mapped[datetime] = mapped_column(STAMP)
|
|
328
|
+
# Membership: set only by a full agreement export; equals the agreement's
|
|
329
|
+
# excel_stamp while a member. NULL if only seen in department exports.
|
|
330
|
+
excel_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
331
|
+
excel_request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
332
|
+
card_stamp: Mapped[datetime | None] = mapped_column(
|
|
333
|
+
STAMP
|
|
334
|
+
) # stamp of the latest card observation
|
|
335
|
+
# Stamp of the latest card paging that ran to the end of a scope this
|
|
336
|
+
# ficha was waiting in (card_stamp NULL or older). A ficha whose card that
|
|
337
|
+
# paging did not return is left to part-number recovery: paging skips it
|
|
338
|
+
# until the stamp moves, so a card the site never lists costs its pages
|
|
339
|
+
# once per site stamp, not once per query. NULL: never paged.
|
|
340
|
+
card_paged_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
341
|
+
# Stamp of the latest part-number lookup (card recovery after paging) the
|
|
342
|
+
# site answered, whether or not the answer had the ficha's card. Recovery skips fichas looked
|
|
343
|
+
# up at or after the current stamp, so a lookup that can never succeed
|
|
344
|
+
# costs one request per site stamp, not one per query. NULL: never looked up.
|
|
345
|
+
card_lookup_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
346
|
+
# Failed part-number lookups. Each lookup is written ahead as a failed
|
|
347
|
+
# attempt (also a lease against concurrent recoveries, and crash-safe) and
|
|
348
|
+
# stays one unless the site answered: one that failed at the site (any
|
|
349
|
+
# error status, the site's error page, an undecodable answer, the ficha's
|
|
350
|
+
# own card unparseable, or a transport error, after the client's retries),
|
|
351
|
+
# whose returned card could not be stored, or whose process died. They
|
|
352
|
+
# leave card_lookup_stamp as it was, so the ficha stays eligible under the
|
|
353
|
+
# stamp, but count as
|
|
354
|
+
# consecutive failures under card_lookup_failure_stamp; while the count is
|
|
355
|
+
# above 0 under the current site stamp, the ficha is looked up again only
|
|
356
|
+
# from card_lookup_retry_at (exponential backoff), after untried fichas, so
|
|
357
|
+
# one failing lookup can't hold back the fichas behind it. A lookup that
|
|
358
|
+
# completes resets the count to 0; a newer site stamp makes the record stale.
|
|
359
|
+
card_lookup_failure_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
360
|
+
card_lookup_failures: Mapped[int] = mapped_column(Integer, server_default=text("0"))
|
|
361
|
+
card_lookup_retry_at: Mapped[datetime | None] = mapped_column(TS)
|
|
362
|
+
# Hash of the current canonical extraction input (a payload); recomputed
|
|
363
|
+
# whenever the Excel row, card or PDF text changes.
|
|
364
|
+
input_hash: Mapped[str | None] = mapped_column(SHA256)
|
|
365
|
+
# Provenance of input_hash: the stamp of the card observation whose
|
|
366
|
+
# features it holds (NULL: built without card features) and the PDF text
|
|
367
|
+
# payload it holds (NULL: built without PDF text). An Excel sync whose row
|
|
368
|
+
# is unchanged (same excel_hash) and whose latest card stamp and PDF text
|
|
369
|
+
# match these reuses input_hash without rebuilding it.
|
|
370
|
+
input_card_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
371
|
+
input_pdf_text_sha256: Mapped[str | None] = mapped_column(
|
|
372
|
+
ForeignKey(f"{SCHEMA}.payload.payload_sha256")
|
|
373
|
+
)
|
|
374
|
+
card_pending: Mapped[bool] = mapped_column(Boolean)
|
|
375
|
+
pdf_pending: Mapped[bool] = mapped_column(Boolean)
|
|
376
|
+
extraction_pending: Mapped[bool] = mapped_column(Boolean)
|
|
377
|
+
# Enrichment attempts (PDF, then rules and LLM passes), so a ficha that
|
|
378
|
+
# keeps failing can't hold the front of the queue. An attempt is recorded
|
|
379
|
+
# when it starts, so one cut off by an error counts too: its time (our
|
|
380
|
+
# clock), the ficha's row_stamp then, and the consecutive attempts under
|
|
381
|
+
# that stamp that didn't finish the ficha. A finished attempt resets the
|
|
382
|
+
# count to 0; a newer row_stamp than the recorded one makes the record
|
|
383
|
+
# stale, so the next attempt counts from 0 again. While the count is above
|
|
384
|
+
# 0 under the current row_stamp, the ficha is retried only from
|
|
385
|
+
# enrichment_retry_at (exponential backoff), after untried fichas.
|
|
386
|
+
enrichment_attempted_at: Mapped[datetime | None] = mapped_column(TS)
|
|
387
|
+
enrichment_attempt_stamp: Mapped[datetime | None] = mapped_column(STAMP)
|
|
388
|
+
enrichment_failures: Mapped[int] = mapped_column(Integer, server_default=text("0"))
|
|
389
|
+
enrichment_retry_at: Mapped[datetime | None] = mapped_column(TS)
|
|
390
|
+
# Failed rules passes run by the sync for a new input (SyncService), so a
|
|
391
|
+
# ficha whose pass keeps failing (e.g. an unreadable input payload) never
|
|
392
|
+
# fails the query or holds back the fichas behind it: the input_hash the
|
|
393
|
+
# failures were counted under, the consecutive failures for that input,
|
|
394
|
+
# and the earliest time the pass is tried again (exponential backoff,
|
|
395
|
+
# enrichment's policy). A pass that succeeds clears all three; a new
|
|
396
|
+
# input_hash makes the record stale, so the new input is tried at once.
|
|
397
|
+
rules_failed_input_hash: Mapped[str | None] = mapped_column(SHA256)
|
|
398
|
+
rules_failures: Mapped[int] = mapped_column(Integer, server_default=text("0"))
|
|
399
|
+
rules_retry_at: Mapped[datetime | None] = mapped_column(TS)
|
|
400
|
+
first_seen_at: Mapped[datetime] = mapped_column(TS)
|
|
401
|
+
last_seen_at: Mapped[datetime] = mapped_column(TS)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class DepartmentSync(Base):
|
|
405
|
+
"""Our sync record for one (agreement, department) download.
|
|
406
|
+
|
|
407
|
+
Agreements are national; this is not a property of the agreement but a
|
|
408
|
+
record that we hold the complete list of the agreement's fichas offered in
|
|
409
|
+
one department. Without it, "not offered in D" and "never checked D" look
|
|
410
|
+
the same.
|
|
411
|
+
|
|
412
|
+
A department-filtered Excel export lists exactly the fichas offered in
|
|
413
|
+
that department. Its checkpoint is the newest stamp a complete export was
|
|
414
|
+
loaded under; written in the same transaction as that export's rows, and
|
|
415
|
+
only moved forward. Up to 25 per agreement, so not columns on agreement.
|
|
416
|
+
"""
|
|
417
|
+
|
|
418
|
+
__tablename__ = "department_sync"
|
|
419
|
+
__updatable__ = frozenset(
|
|
420
|
+
{"excel_stamp", "excel_synced_at", "excel_request_id", "excel_ficha_count"}
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
agreement_id: Mapped[str] = mapped_column(
|
|
424
|
+
ForeignKey(f"{SCHEMA}.agreement.agreement_id"), primary_key=True
|
|
425
|
+
)
|
|
426
|
+
department: Mapped[str] = mapped_column(
|
|
427
|
+
String, primary_key=True
|
|
428
|
+
) # as the site lists it, e.g. AMAZONAS
|
|
429
|
+
excel_stamp: Mapped[datetime] = mapped_column(STAMP)
|
|
430
|
+
excel_synced_at: Mapped[datetime] = mapped_column(TS)
|
|
431
|
+
excel_request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
432
|
+
excel_ficha_count: Mapped[int] = mapped_column(Integer)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
class FichaDepartment(Base):
|
|
436
|
+
"""A ficha seen in a department-filtered export: offered for delivery there.
|
|
437
|
+
|
|
438
|
+
Available in the department only while `stamp` equals the pair's
|
|
439
|
+
`department_sync.excel_stamp`; a ficha missing from a newer complete
|
|
440
|
+
export keeps its old stamp and stops matching (history kept).
|
|
441
|
+
"""
|
|
442
|
+
|
|
443
|
+
__tablename__ = "ficha_department"
|
|
444
|
+
__updatable__ = frozenset({"stamp", "request_id"})
|
|
445
|
+
|
|
446
|
+
ficha_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.ficha.ficha_id"), primary_key=True)
|
|
447
|
+
department: Mapped[str] = mapped_column(String, primary_key=True)
|
|
448
|
+
stamp: Mapped[datetime] = mapped_column(STAMP) # stamp of the export it was last seen in
|
|
449
|
+
request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
class Pdf(Base):
|
|
453
|
+
"""One downloaded ficha técnica.
|
|
454
|
+
|
|
455
|
+
URLs are immutable (file name = version), so one row per URL.
|
|
456
|
+
"""
|
|
457
|
+
|
|
458
|
+
__tablename__ = "pdf"
|
|
459
|
+
|
|
460
|
+
pdf_url: Mapped[str] = mapped_column(String, primary_key=True)
|
|
461
|
+
ficha_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.ficha.ficha_id"))
|
|
462
|
+
request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
463
|
+
payload_sha256: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.payload.payload_sha256"))
|
|
464
|
+
text_sha256: Mapped[str | None] = mapped_column(
|
|
465
|
+
ForeignKey(f"{SCHEMA}.payload.payload_sha256")
|
|
466
|
+
) # extracted text, stored as a payload
|
|
467
|
+
page_count: Mapped[int | None] = mapped_column(Integer)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
class FichaCard(Base):
|
|
471
|
+
"""One reading of one ficha's card (search HTML), as the site reported it.
|
|
472
|
+
|
|
473
|
+
Holds the card's structured features (`data-feature`, built by Perú Compras
|
|
474
|
+
with Azure AI services), which seed both the rules pass and the LLM pass,
|
|
475
|
+
plus its price statistics and yearly series. One row per card observation
|
|
476
|
+
(per site stamp); prices are never ranked or converted. The raw HTML stays
|
|
477
|
+
in `payload`, via `request_id`.
|
|
478
|
+
"""
|
|
479
|
+
|
|
480
|
+
__tablename__ = "ficha_card"
|
|
481
|
+
|
|
482
|
+
card_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
483
|
+
ficha_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.ficha.ficha_id"))
|
|
484
|
+
request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
485
|
+
stamp: Mapped[datetime] = mapped_column(STAMP)
|
|
486
|
+
observed_at: Mapped[datetime] = mapped_column(TS)
|
|
487
|
+
currency: Mapped[str] = mapped_column(String) # data-moneda, as reported (PEN, USD)
|
|
488
|
+
# Contracted: actual purchase orders
|
|
489
|
+
contracted_min: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
490
|
+
contracted_max: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
491
|
+
contracted_avg: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
492
|
+
contracted_median: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
493
|
+
orders_count: Mapped[int | None] = mapped_column(Integer)
|
|
494
|
+
contracted_amount: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
495
|
+
suppliers_count: Mapped[int | None] = mapped_column(Integer)
|
|
496
|
+
entities_count: Mapped[int | None] = mapped_column(Integer)
|
|
497
|
+
last_sale_date: Mapped[date | None] = mapped_column(Date)
|
|
498
|
+
# Offered: current supplier offers
|
|
499
|
+
offered_min: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
500
|
+
offered_max: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
501
|
+
offered_avg: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
502
|
+
offered_median: Mapped[Decimal | None] = mapped_column(MONEY)
|
|
503
|
+
offering_suppliers_count: Mapped[int | None] = mapped_column(Integer)
|
|
504
|
+
# The card's yearly series (data-historico) as the site reported it in this
|
|
505
|
+
# observation: [{"year": 2025, "orders_count": 4, "avg_unit_price": 4256.43}, ...].
|
|
506
|
+
# A snapshot, not our history: the site can revise past years.
|
|
507
|
+
historico: Mapped[list[Any] | None] = mapped_column(JSONDoc())
|
|
508
|
+
# The card's structured features (data-feature) as raw label/value pairs,
|
|
509
|
+
# e.g. [{"label": "Almacenamiento", "value": "1TB SSD"}, ...]. The card part
|
|
510
|
+
# of the canonical extraction input is read from the latest row.
|
|
511
|
+
features: Mapped[list[Any] | None] = mapped_column(JSONDoc())
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
# ---------------------------------------------------------------------------
|
|
515
|
+
# Clean side: attribute universe and extraction
|
|
516
|
+
# ---------------------------------------------------------------------------
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
class Attribute(Base):
|
|
520
|
+
"""One canonical attribute: the CLI's own stable id per concept."""
|
|
521
|
+
|
|
522
|
+
__tablename__ = "attribute"
|
|
523
|
+
__updatable__ = frozenset({"status", "accepted_at", "merged_into"})
|
|
524
|
+
|
|
525
|
+
attribute_id: Mapped[str] = mapped_column(String, primary_key=True) # e.g. almacenamiento
|
|
526
|
+
display_name: Mapped[str] = mapped_column(String)
|
|
527
|
+
kind: Mapped[str] = mapped_column(String) # quantity, set, categoric, flag
|
|
528
|
+
canonical_unit: Mapped[str | None] = mapped_column(String)
|
|
529
|
+
seeded_from_pane: Mapped[bool] = mapped_column(Boolean)
|
|
530
|
+
status: Mapped[str] = mapped_column(String) # proposed, accepted, rejected
|
|
531
|
+
merged_into: Mapped[str | None] = mapped_column(ForeignKey(f"{SCHEMA}.attribute.attribute_id"))
|
|
532
|
+
proposed_by: Mapped[str | None] = mapped_column(
|
|
533
|
+
ForeignKey(f"{SCHEMA}.extraction.extraction_id")
|
|
534
|
+
) # NULL when seeded from the pane
|
|
535
|
+
accepted_at: Mapped[datetime | None] = mapped_column(TS)
|
|
536
|
+
created_at: Mapped[datetime] = mapped_column(TS)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
class AttributeScope(Base):
|
|
540
|
+
"""An attribute known to apply to a category. Positive-only, never retracted."""
|
|
541
|
+
|
|
542
|
+
__tablename__ = "attribute_scope"
|
|
543
|
+
|
|
544
|
+
attribute_id: Mapped[str] = mapped_column(
|
|
545
|
+
ForeignKey(f"{SCHEMA}.attribute.attribute_id"), primary_key=True
|
|
546
|
+
)
|
|
547
|
+
category: Mapped[str] = mapped_column(String, primary_key=True)
|
|
548
|
+
origin: Mapped[str] = mapped_column(String) # pane, extraction
|
|
549
|
+
extraction_id: Mapped[str | None] = mapped_column(
|
|
550
|
+
ForeignKey(f"{SCHEMA}.extraction.extraction_id")
|
|
551
|
+
) # when origin = extraction
|
|
552
|
+
request_id: Mapped[str | None] = mapped_column(
|
|
553
|
+
ForeignKey(f"{SCHEMA}.request_log.request_id")
|
|
554
|
+
) # the pane response, when origin = pane
|
|
555
|
+
first_seen_at: Mapped[datetime] = mapped_column(TS)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
class SeedValue(Base):
|
|
559
|
+
"""One filter-pane value of one attribute in one category: vocabulary only.
|
|
560
|
+
|
|
561
|
+
Pane counts are not stored: the same category can be shown under different
|
|
562
|
+
agreement, catalogue or department filters, so its counts describe
|
|
563
|
+
different populations. Our own counts come from our tables.
|
|
564
|
+
"""
|
|
565
|
+
|
|
566
|
+
__tablename__ = "seed_value"
|
|
567
|
+
__updatable__ = frozenset({"last_request_id"})
|
|
568
|
+
|
|
569
|
+
attribute_id: Mapped[str] = mapped_column(
|
|
570
|
+
ForeignKey(f"{SCHEMA}.attribute.attribute_id"), primary_key=True
|
|
571
|
+
)
|
|
572
|
+
category: Mapped[str] = mapped_column(String, primary_key=True)
|
|
573
|
+
raw_value: Mapped[str] = mapped_column(String, primary_key=True)
|
|
574
|
+
# The latest pane response that listed this value (vocabulary provenance;
|
|
575
|
+
# no counts, which depend on the pane's scope).
|
|
576
|
+
last_request_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.request_log.request_id"))
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
class Alias(Base):
|
|
580
|
+
"""A raw label (pane, card, description, PDF) pointing at a canonical attribute."""
|
|
581
|
+
|
|
582
|
+
__tablename__ = "alias"
|
|
583
|
+
__table_args__ = (UniqueConstraint("raw_label", name="uq_alias_raw_label"), {"schema": SCHEMA})
|
|
584
|
+
__updatable__ = frozenset({"status", "accepted_at"})
|
|
585
|
+
|
|
586
|
+
alias_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
587
|
+
raw_label: Mapped[str] = mapped_column(String) # normalized: case-folded, trimmed
|
|
588
|
+
attribute_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.attribute.attribute_id"))
|
|
589
|
+
status: Mapped[str] = mapped_column(String) # proposed, accepted, rejected
|
|
590
|
+
proposed_by: Mapped[str | None] = mapped_column(
|
|
591
|
+
ForeignKey(f"{SCHEMA}.extraction.extraction_id")
|
|
592
|
+
)
|
|
593
|
+
accepted_at: Mapped[datetime | None] = mapped_column(TS)
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
class UnitRule(Base):
|
|
597
|
+
"""A raw unit converted to a canonical unit, optionally only within one category."""
|
|
598
|
+
|
|
599
|
+
__tablename__ = "unit_rule"
|
|
600
|
+
__table_args__ = (
|
|
601
|
+
UniqueConstraint("raw_unit", "category", name="uq_unit_rule"),
|
|
602
|
+
{"schema": SCHEMA},
|
|
603
|
+
)
|
|
604
|
+
__updatable__ = frozenset({"status", "accepted_at"})
|
|
605
|
+
|
|
606
|
+
rule_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
607
|
+
raw_unit: Mapped[str] = mapped_column(String) # e.g. lb
|
|
608
|
+
category: Mapped[str] = mapped_column(
|
|
609
|
+
String
|
|
610
|
+
) # '*' = any category (not NULL, so the unique key holds on every engine)
|
|
611
|
+
canonical_unit: Mapped[str] = mapped_column(String) # e.g. kg
|
|
612
|
+
factor: Mapped[Decimal] = mapped_column(Numeric(24, 12)) # canonical = raw * factor
|
|
613
|
+
status: Mapped[str] = mapped_column(String) # proposed, accepted, rejected
|
|
614
|
+
proposed_by: Mapped[str | None] = mapped_column(
|
|
615
|
+
ForeignKey(f"{SCHEMA}.extraction.extraction_id")
|
|
616
|
+
)
|
|
617
|
+
accepted_at: Mapped[datetime | None] = mapped_column(TS)
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
class Extraction(Base):
|
|
621
|
+
"""One extraction pass over one ficha's input: the rules pass or the LLM pass.
|
|
622
|
+
|
|
623
|
+
Cache key: (ficha_id, input_hash, model, prompt_version); `attempt` numbers
|
|
624
|
+
retries and explicit re-extractions under the same key, so every attempt is
|
|
625
|
+
kept and the current one is the latest `ok` attempt. The rules pass has
|
|
626
|
+
model = 'rules' and the rule-set version as prompt_version, no provider and
|
|
627
|
+
no request. An LLM pass records the provider of the client that made the call.
|
|
628
|
+
|
|
629
|
+
`input_hash` is the hash of the canonical extraction input (Excel row, card
|
|
630
|
+
features from the latest `ficha_card`,
|
|
631
|
+
attributes, description, PDF text), which is stored as a payload, so an old
|
|
632
|
+
extraction can always be traced to the exact input it saw.
|
|
633
|
+
"""
|
|
634
|
+
|
|
635
|
+
__tablename__ = "extraction"
|
|
636
|
+
__updatable__ = frozenset(
|
|
637
|
+
{"status", "request_id", "input_tokens", "output_tokens", "cost_usd", "finished_at"}
|
|
638
|
+
)
|
|
639
|
+
__table_args__ = (
|
|
640
|
+
UniqueConstraint(
|
|
641
|
+
"ficha_id",
|
|
642
|
+
"input_hash",
|
|
643
|
+
"model",
|
|
644
|
+
"prompt_version",
|
|
645
|
+
"attempt",
|
|
646
|
+
name="uq_extraction_attempt",
|
|
647
|
+
),
|
|
648
|
+
{"schema": SCHEMA},
|
|
649
|
+
)
|
|
650
|
+
|
|
651
|
+
extraction_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
652
|
+
ficha_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.ficha.ficha_id"))
|
|
653
|
+
input_hash: Mapped[str] = mapped_column(
|
|
654
|
+
ForeignKey(f"{SCHEMA}.payload.payload_sha256")
|
|
655
|
+
) # the stored canonical input
|
|
656
|
+
attempt: Mapped[int] = mapped_column(Integer) # 1, 2, ... under the same cache key
|
|
657
|
+
model: Mapped[str] = mapped_column(String) # 'rules' or the LLM model id
|
|
658
|
+
# The LLM provider that served the pass ('anthropic' or 'snowflake'); NULL
|
|
659
|
+
# for rules. Model ids alone can't tell them apart: Cortex serves the same ids.
|
|
660
|
+
provider: Mapped[str | None] = mapped_column(String)
|
|
661
|
+
prompt_version: Mapped[str] = mapped_column(String) # prompt version, or rule-set version
|
|
662
|
+
status: Mapped[str] = mapped_column(String) # pending, ok, failed
|
|
663
|
+
request_id: Mapped[str | None] = mapped_column(
|
|
664
|
+
ForeignKey(f"{SCHEMA}.request_log.request_id")
|
|
665
|
+
) # the LLM call; NULL for rules
|
|
666
|
+
input_tokens: Mapped[int | None] = mapped_column(Integer)
|
|
667
|
+
output_tokens: Mapped[int | None] = mapped_column(Integer)
|
|
668
|
+
cost_usd: Mapped[Decimal | None] = mapped_column(Numeric(12, 6))
|
|
669
|
+
started_at: Mapped[datetime] = mapped_column(TS)
|
|
670
|
+
finished_at: Mapped[datetime | None] = mapped_column(TS)
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
class ExtractionConfig(Base):
|
|
674
|
+
"""The configured LLM key used by the current-extraction view."""
|
|
675
|
+
|
|
676
|
+
__tablename__ = "extraction_config"
|
|
677
|
+
__updatable__ = frozenset({"llm_model", "llm_prompt_version"})
|
|
678
|
+
|
|
679
|
+
config_id: Mapped[str] = mapped_column(String, primary_key=True) # the active row is "current"
|
|
680
|
+
llm_model: Mapped[str] = mapped_column(String)
|
|
681
|
+
llm_prompt_version: Mapped[str] = mapped_column(String)
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
class FichaAttribute(Base):
|
|
685
|
+
"""One typed value of one attribute of one ficha, from one extraction.
|
|
686
|
+
|
|
687
|
+
A set attribute has one row per member (position 0, 1, ...). A value the
|
|
688
|
+
sources lack entirely is stored with kind = 'unknown', and one a source lists
|
|
689
|
+
with an empty or placeholder value with kind = 'blank', so both are queryable.
|
|
690
|
+
"""
|
|
691
|
+
|
|
692
|
+
__tablename__ = "ficha_attribute"
|
|
693
|
+
|
|
694
|
+
extraction_id: Mapped[str] = mapped_column(
|
|
695
|
+
ForeignKey(f"{SCHEMA}.extraction.extraction_id"), primary_key=True
|
|
696
|
+
)
|
|
697
|
+
attribute_id: Mapped[str] = mapped_column(
|
|
698
|
+
ForeignKey(f"{SCHEMA}.attribute.attribute_id"), primary_key=True
|
|
699
|
+
)
|
|
700
|
+
position: Mapped[int] = mapped_column(Integer, primary_key=True)
|
|
701
|
+
ficha_id: Mapped[str] = mapped_column(
|
|
702
|
+
ForeignKey(f"{SCHEMA}.ficha.ficha_id")
|
|
703
|
+
) # denormalized from extraction, for queries
|
|
704
|
+
kind: Mapped[str] = mapped_column(String) # quantity, set, categoric, flag, blank, unknown
|
|
705
|
+
value_number: Mapped[Decimal | None] = mapped_column(
|
|
706
|
+
Numeric(24, 6)
|
|
707
|
+
) # in the attribute's canonical unit
|
|
708
|
+
value_unit: Mapped[str | None] = mapped_column(String)
|
|
709
|
+
value_text: Mapped[str | None] = mapped_column(String) # canonical label, or sí/no
|
|
710
|
+
raw_text: Mapped[str | None] = mapped_column(Text) # what the source said
|
|
711
|
+
source: Mapped[str] = mapped_column(String) # card, excel, description, pdf
|
|
712
|
+
confidence: Mapped[Decimal] = mapped_column(Numeric(4, 3)) # 1.000 for the rules pass
|
|
713
|
+
|
|
714
|
+
|
|
715
|
+
# ---------------------------------------------------------------------------
|
|
716
|
+
# Clean side: queries
|
|
717
|
+
# ---------------------------------------------------------------------------
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
class SavedQuery(Base):
|
|
721
|
+
"""A predicate document the frontend saved, so re-running it returns the current catalog."""
|
|
722
|
+
|
|
723
|
+
__tablename__ = "saved_query"
|
|
724
|
+
|
|
725
|
+
query_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
726
|
+
contract_version: Mapped[int] = mapped_column(Integer)
|
|
727
|
+
document: Mapped[dict[str, Any]] = mapped_column(JSONDoc())
|
|
728
|
+
created_at: Mapped[datetime] = mapped_column(TS)
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
class QueryRun(Base):
|
|
732
|
+
"""One execution of a predicate document, saved or ad hoc."""
|
|
733
|
+
|
|
734
|
+
__tablename__ = "query_run"
|
|
735
|
+
|
|
736
|
+
query_run_id: Mapped[str] = mapped_column(UUID, primary_key=True)
|
|
737
|
+
run_id: Mapped[str] = mapped_column(ForeignKey(f"{SCHEMA}.run_log.run_id"))
|
|
738
|
+
query_id: Mapped[str | None] = mapped_column(
|
|
739
|
+
ForeignKey(f"{SCHEMA}.saved_query.query_id")
|
|
740
|
+
) # NULL for ad hoc
|
|
741
|
+
document: Mapped[dict[str, Any]] = mapped_column(JSONDoc())
|
|
742
|
+
stamp: Mapped[datetime] = mapped_column(STAMP) # the site stamp the query ran under
|
|
743
|
+
matches_count: Mapped[int] = mapped_column(Integer)
|
|
744
|
+
non_matches_count: Mapped[int] = mapped_column(Integer)
|
|
745
|
+
unknown_count: Mapped[int] = mapped_column(Integer)
|
|
746
|
+
pending_count: Mapped[int] = mapped_column(Integer)
|
|
747
|
+
duration_ms: Mapped[int] = mapped_column(Integer)
|