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,175 @@
|
|
|
1
|
+
"""Assemble and record a deterministic query result."""
|
|
2
|
+
|
|
3
|
+
from datetime import date, datetime
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from time import perf_counter_ns
|
|
6
|
+
from typing import Any
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict
|
|
10
|
+
from sqlalchemy import and_, func, select
|
|
11
|
+
from sqlalchemy.orm import Session
|
|
12
|
+
|
|
13
|
+
from piloto_ai_cli.database import upsert
|
|
14
|
+
from piloto_ai_cli.query_compiler import (
|
|
15
|
+
CompiledQuery,
|
|
16
|
+
FacetSummary,
|
|
17
|
+
NotApplicable,
|
|
18
|
+
PendingCounts,
|
|
19
|
+
UnknownCount,
|
|
20
|
+
)
|
|
21
|
+
from piloto_ai_cli.schema.contract import ValidatedContract
|
|
22
|
+
from piloto_ai_cli.schema.models import Ficha, FichaCard, QueryRun
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class QueryMatch(BaseModel):
|
|
26
|
+
"""One matching ficha, with the latest card values and their source stamps."""
|
|
27
|
+
|
|
28
|
+
model_config = ConfigDict(frozen=True)
|
|
29
|
+
|
|
30
|
+
ficha_id: str
|
|
31
|
+
currency: str | None
|
|
32
|
+
contracted_min: Decimal | None
|
|
33
|
+
contracted_max: Decimal | None
|
|
34
|
+
contracted_avg: Decimal | None
|
|
35
|
+
contracted_median: Decimal | None
|
|
36
|
+
orders_count: int | None
|
|
37
|
+
contracted_amount: Decimal | None
|
|
38
|
+
suppliers_count: int | None
|
|
39
|
+
entities_count: int | None
|
|
40
|
+
last_sale_date: date | None
|
|
41
|
+
offered_min: Decimal | None
|
|
42
|
+
offered_max: Decimal | None
|
|
43
|
+
offered_avg: Decimal | None
|
|
44
|
+
offered_median: Decimal | None
|
|
45
|
+
offering_suppliers_count: int | None
|
|
46
|
+
historico: list[Any] | None
|
|
47
|
+
row_stamp: datetime
|
|
48
|
+
excel_stamp: datetime | None
|
|
49
|
+
card_stamp: datetime | None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class QueryResult(BaseModel):
|
|
53
|
+
"""Typed result envelope returned by the query library API."""
|
|
54
|
+
|
|
55
|
+
model_config = ConfigDict(frozen=True)
|
|
56
|
+
|
|
57
|
+
matches: tuple[QueryMatch, ...]
|
|
58
|
+
non_matches: int
|
|
59
|
+
unknown: tuple[UnknownCount, ...]
|
|
60
|
+
not_applicable: tuple[NotApplicable, ...]
|
|
61
|
+
pending: PendingCounts
|
|
62
|
+
facets: dict[str, FacetSummary]
|
|
63
|
+
contract_version: int
|
|
64
|
+
department_as_of: datetime | None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def run_query(
|
|
68
|
+
session: Session,
|
|
69
|
+
compiled: CompiledQuery,
|
|
70
|
+
contract: ValidatedContract,
|
|
71
|
+
document: dict[str, Any],
|
|
72
|
+
*,
|
|
73
|
+
run_id: str,
|
|
74
|
+
stamp: datetime,
|
|
75
|
+
query_id: str | None = None,
|
|
76
|
+
) -> QueryResult:
|
|
77
|
+
"""Execute a compiled query, build its envelope, and persist its run counts."""
|
|
78
|
+
started_at = perf_counter_ns()
|
|
79
|
+
session.flush()
|
|
80
|
+
rows = compiled.execute(session.connection())
|
|
81
|
+
include_rows = (contract.include or {}).get("rows", True) is not False
|
|
82
|
+
matches = _read_matches(session, rows.matches) if include_rows else ()
|
|
83
|
+
result = QueryResult(
|
|
84
|
+
matches=matches,
|
|
85
|
+
non_matches=rows.non_matches,
|
|
86
|
+
unknown=rows.unknown_counts,
|
|
87
|
+
not_applicable=rows.not_applicable,
|
|
88
|
+
pending=rows.pending,
|
|
89
|
+
facets=rows.facets,
|
|
90
|
+
contract_version=contract.contract_version,
|
|
91
|
+
department_as_of=rows.department_as_of,
|
|
92
|
+
)
|
|
93
|
+
pending_count = (
|
|
94
|
+
rows.pending.card_pending
|
|
95
|
+
+ rows.pending.pdf_pending
|
|
96
|
+
+ rows.pending.extraction_pending
|
|
97
|
+
+ rows.pending.proposals
|
|
98
|
+
)
|
|
99
|
+
upsert(
|
|
100
|
+
session,
|
|
101
|
+
QueryRun,
|
|
102
|
+
[
|
|
103
|
+
{
|
|
104
|
+
"query_run_id": str(uuid4()),
|
|
105
|
+
"run_id": run_id,
|
|
106
|
+
"query_id": query_id,
|
|
107
|
+
"document": document,
|
|
108
|
+
"stamp": stamp,
|
|
109
|
+
"matches_count": len(rows.matches),
|
|
110
|
+
"non_matches_count": rows.non_matches,
|
|
111
|
+
"unknown_count": len({ficha_id for ficha_id, _, _, _ in rows.unknown}),
|
|
112
|
+
"pending_count": pending_count,
|
|
113
|
+
"duration_ms": max(0, (perf_counter_ns() - started_at) // 1_000_000),
|
|
114
|
+
}
|
|
115
|
+
],
|
|
116
|
+
)
|
|
117
|
+
return result
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _read_matches(session: Session, ficha_ids: tuple[str, ...]) -> tuple[QueryMatch, ...]:
|
|
121
|
+
if not ficha_ids:
|
|
122
|
+
return ()
|
|
123
|
+
|
|
124
|
+
latest_card = (
|
|
125
|
+
select(
|
|
126
|
+
FichaCard.ficha_id.label("ficha_id"),
|
|
127
|
+
FichaCard.card_id.label("card_id"),
|
|
128
|
+
func.row_number()
|
|
129
|
+
.over(
|
|
130
|
+
partition_by=FichaCard.ficha_id,
|
|
131
|
+
order_by=(
|
|
132
|
+
FichaCard.stamp.desc(),
|
|
133
|
+
FichaCard.observed_at.desc(),
|
|
134
|
+
FichaCard.card_id.desc(),
|
|
135
|
+
),
|
|
136
|
+
)
|
|
137
|
+
.label("position"),
|
|
138
|
+
)
|
|
139
|
+
.where(FichaCard.ficha_id.in_(ficha_ids))
|
|
140
|
+
.subquery()
|
|
141
|
+
)
|
|
142
|
+
rows = session.execute(
|
|
143
|
+
select(Ficha, FichaCard)
|
|
144
|
+
.outerjoin(
|
|
145
|
+
latest_card,
|
|
146
|
+
and_(latest_card.c.ficha_id == Ficha.ficha_id, latest_card.c.position == 1),
|
|
147
|
+
)
|
|
148
|
+
.outerjoin(FichaCard, FichaCard.card_id == latest_card.c.card_id)
|
|
149
|
+
.where(Ficha.ficha_id.in_(ficha_ids))
|
|
150
|
+
).all()
|
|
151
|
+
matches_by_id: dict[str, QueryMatch] = {}
|
|
152
|
+
for ficha, card in rows:
|
|
153
|
+
matches_by_id[ficha.ficha_id] = QueryMatch(
|
|
154
|
+
ficha_id=ficha.ficha_id,
|
|
155
|
+
currency=card.currency if card is not None else None,
|
|
156
|
+
contracted_min=card.contracted_min if card is not None else None,
|
|
157
|
+
contracted_max=card.contracted_max if card is not None else None,
|
|
158
|
+
contracted_avg=card.contracted_avg if card is not None else None,
|
|
159
|
+
contracted_median=card.contracted_median if card is not None else None,
|
|
160
|
+
orders_count=card.orders_count if card is not None else None,
|
|
161
|
+
contracted_amount=card.contracted_amount if card is not None else None,
|
|
162
|
+
suppliers_count=card.suppliers_count if card is not None else None,
|
|
163
|
+
entities_count=card.entities_count if card is not None else None,
|
|
164
|
+
last_sale_date=card.last_sale_date if card is not None else None,
|
|
165
|
+
offered_min=card.offered_min if card is not None else None,
|
|
166
|
+
offered_max=card.offered_max if card is not None else None,
|
|
167
|
+
offered_avg=card.offered_avg if card is not None else None,
|
|
168
|
+
offered_median=card.offered_median if card is not None else None,
|
|
169
|
+
offering_suppliers_count=card.offering_suppliers_count if card is not None else None,
|
|
170
|
+
historico=card.historico if card is not None else None,
|
|
171
|
+
row_stamp=ficha.row_stamp,
|
|
172
|
+
excel_stamp=ficha.excel_stamp,
|
|
173
|
+
card_stamp=card.stamp if card is not None else None,
|
|
174
|
+
)
|
|
175
|
+
return tuple(matches_by_id[ficha_id] for ficha_id in ficha_ids if ficha_id in matches_by_id)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Run a predicate document end to end (``pc query``).
|
|
2
|
+
|
|
3
|
+
data-model.md §4, ``pc query <document>``: the command opens its run and
|
|
4
|
+
validates the document (steps 1-2); :class:`QueryService` then reads the stamp
|
|
5
|
+
(3), brings the scope up to it (4), compiles and runs the query (5) and
|
|
6
|
+
records the ``query_run`` (6); closing the run is step 7. ``pc query --saved
|
|
7
|
+
<id>`` reads the document from ``saved_query`` (:func:`load_saved_document`)
|
|
8
|
+
and continues as ``pc query``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from datetime import UTC, datetime, timedelta
|
|
15
|
+
from typing import Any
|
|
16
|
+
from uuid import UUID
|
|
17
|
+
|
|
18
|
+
from sqlalchemy import select
|
|
19
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
20
|
+
|
|
21
|
+
from piloto_ai_cli.cards import CardsSyncService
|
|
22
|
+
from piloto_ai_cli.enrichment import EnrichmentService
|
|
23
|
+
from piloto_ai_cli.errors import ContractError, ContractErrorCode
|
|
24
|
+
from piloto_ai_cli.extraction import ExtractService, LLMProvider
|
|
25
|
+
from piloto_ai_cli.http_client import HttpClient
|
|
26
|
+
from piloto_ai_cli.payload_store import PayloadStore
|
|
27
|
+
from piloto_ai_cli.query_compiler import QueryCompiler
|
|
28
|
+
from piloto_ai_cli.query_result import QueryResult, run_query
|
|
29
|
+
from piloto_ai_cli.schema.contract import ValidatedContract
|
|
30
|
+
from piloto_ai_cli.schema.models import SavedQuery, UnitRule
|
|
31
|
+
from piloto_ai_cli.settings import Settings
|
|
32
|
+
from piloto_ai_cli.stamp_service import StampService
|
|
33
|
+
from piloto_ai_cli.sync import SyncService, SyncSteps, require_agreement
|
|
34
|
+
from piloto_ai_cli.unit_converter import UnitConverter
|
|
35
|
+
|
|
36
|
+
SAVED_LOCATION = "saved"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def canonical_saved_id(query_id: object) -> str:
|
|
40
|
+
"""Return ``query_id`` in the canonical form ``pc save`` stores it in.
|
|
41
|
+
|
|
42
|
+
``UUID()`` also accepts upper case, braces, ``urn:uuid:`` and unhyphenated
|
|
43
|
+
forms; ``saved_query.query_id`` holds the lower-case hyphenated string, so
|
|
44
|
+
the id is normalized before it is used as a key or recorded. An id that is
|
|
45
|
+
not a UUID, or not a string at all, is refused with a ``ContractError`` on
|
|
46
|
+
``saved``.
|
|
47
|
+
"""
|
|
48
|
+
if not isinstance(query_id, str):
|
|
49
|
+
raise ContractError(
|
|
50
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
51
|
+
SAVED_LOCATION,
|
|
52
|
+
f"Saved query id must be a string, not {type(query_id).__qualname__}",
|
|
53
|
+
)
|
|
54
|
+
try:
|
|
55
|
+
return str(UUID(query_id))
|
|
56
|
+
except ValueError:
|
|
57
|
+
raise ContractError(
|
|
58
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
59
|
+
SAVED_LOCATION,
|
|
60
|
+
f"Saved query id is not a UUID: {query_id!r}",
|
|
61
|
+
) from None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def load_saved_document(session: Session, query_id: str) -> dict[str, Any]:
|
|
65
|
+
"""Return the predicate document saved under ``query_id``.
|
|
66
|
+
|
|
67
|
+
The id is canonicalized first (:func:`canonical_saved_id`). An id that is
|
|
68
|
+
not a UUID, or that no ``saved_query`` row holds, is refused with a
|
|
69
|
+
``ContractError`` on ``saved``, like any other caller error.
|
|
70
|
+
"""
|
|
71
|
+
query_id = canonical_saved_id(query_id)
|
|
72
|
+
saved = session.get(SavedQuery, query_id)
|
|
73
|
+
if saved is None:
|
|
74
|
+
raise ContractError(
|
|
75
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
76
|
+
SAVED_LOCATION,
|
|
77
|
+
f"Unknown saved query: {query_id}",
|
|
78
|
+
)
|
|
79
|
+
return saved.document
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def effective_max_items(option: int | None, contract: ValidatedContract, settings: Settings) -> int:
|
|
83
|
+
"""The ``max_items`` a query runs with.
|
|
84
|
+
|
|
85
|
+
The command-line ``--max-items`` wins, then the document's own
|
|
86
|
+
``max_items``, then the configured default (``PILOTO_MAX_ITEMS``).
|
|
87
|
+
"""
|
|
88
|
+
if option is not None:
|
|
89
|
+
return option
|
|
90
|
+
if contract.max_items is not None:
|
|
91
|
+
return contract.max_items
|
|
92
|
+
return settings.max_items
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class QueryService:
|
|
96
|
+
"""Steps 3-6 of ``pc query``: stamp, sync, compile and run, record."""
|
|
97
|
+
|
|
98
|
+
def __init__(
|
|
99
|
+
self,
|
|
100
|
+
session: Session,
|
|
101
|
+
session_factory: sessionmaker[Session],
|
|
102
|
+
client: HttpClient,
|
|
103
|
+
payload_store: PayloadStore,
|
|
104
|
+
settings: Settings,
|
|
105
|
+
*,
|
|
106
|
+
llm_client: LLMProvider | None = None,
|
|
107
|
+
now: Callable[[], datetime] | None = None,
|
|
108
|
+
) -> None:
|
|
109
|
+
"""``session`` is the run's own session; the sync steps use ``session_factory``.
|
|
110
|
+
|
|
111
|
+
``llm_client`` is the provider the enrichment's LLM pass calls; without
|
|
112
|
+
one (no provider configured), a ficha whose rules pass leaves a residue
|
|
113
|
+
the query needs fails the run instead of being silently skipped.
|
|
114
|
+
"""
|
|
115
|
+
self._session = session
|
|
116
|
+
self._session_factory = session_factory
|
|
117
|
+
self._client = client
|
|
118
|
+
self._payload_store = payload_store
|
|
119
|
+
self._settings = settings
|
|
120
|
+
self._llm_client = llm_client
|
|
121
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
122
|
+
|
|
123
|
+
async def run(
|
|
124
|
+
self,
|
|
125
|
+
contract: ValidatedContract,
|
|
126
|
+
document: dict[str, Any],
|
|
127
|
+
*,
|
|
128
|
+
run_id: str,
|
|
129
|
+
max_items: int,
|
|
130
|
+
query_id: str | None = None,
|
|
131
|
+
) -> QueryResult:
|
|
132
|
+
"""Bring ``contract``'s scope up to the stamp, run it and record its ``query_run``.
|
|
133
|
+
|
|
134
|
+
The ``query_run`` row is left in the run's session for ``RunLog.close()``
|
|
135
|
+
to commit with the run's outcome, so a run that fails or is refused
|
|
136
|
+
later records no ``query_run``.
|
|
137
|
+
"""
|
|
138
|
+
# Refusals that depend only on the document come before the stamp
|
|
139
|
+
# read's request (data-model.md section 4, step 2).
|
|
140
|
+
require_agreement(contract)
|
|
141
|
+
stamp = await StampService(self._session, self._client, now=self._now).read()
|
|
142
|
+
# The agreement refresh (and anything the command wrote before it) must
|
|
143
|
+
# be visible to the sync steps' own sessions.
|
|
144
|
+
self._session.commit()
|
|
145
|
+
compiler = QueryCompiler(
|
|
146
|
+
UnitConverter(self._session.scalars(select(UnitRule)).all()),
|
|
147
|
+
self._settings.confidence_threshold,
|
|
148
|
+
)
|
|
149
|
+
steps = self._sync_steps(compiler)
|
|
150
|
+
await SyncService(self._session_factory, self._payload_store, now=self._now).sync(
|
|
151
|
+
contract, max_items, stamp=stamp, steps=steps
|
|
152
|
+
)
|
|
153
|
+
# The sync committed in its own sessions: read the scope as it is now.
|
|
154
|
+
self._session.expire_all()
|
|
155
|
+
return run_query(
|
|
156
|
+
self._session,
|
|
157
|
+
compiler.compile(contract),
|
|
158
|
+
contract,
|
|
159
|
+
document,
|
|
160
|
+
run_id=run_id,
|
|
161
|
+
stamp=stamp,
|
|
162
|
+
query_id=query_id,
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
def _sync_steps(self, compiler: QueryCompiler) -> SyncSteps:
|
|
166
|
+
settings = self._settings
|
|
167
|
+
|
|
168
|
+
def extractor(session: Session) -> ExtractService:
|
|
169
|
+
return ExtractService(
|
|
170
|
+
session,
|
|
171
|
+
self._payload_store,
|
|
172
|
+
llm_client=self._llm_client,
|
|
173
|
+
now=self._now,
|
|
174
|
+
input_usd_per_mtok=settings.llm_input_usd_per_mtok,
|
|
175
|
+
output_usd_per_mtok=settings.llm_output_usd_per_mtok,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
return SyncSteps(
|
|
179
|
+
client=self._client,
|
|
180
|
+
cards=CardsSyncService(
|
|
181
|
+
self._session_factory,
|
|
182
|
+
self._client,
|
|
183
|
+
self._payload_store,
|
|
184
|
+
retry_base=timedelta(seconds=settings.card_lookup_retry_base_seconds),
|
|
185
|
+
retry_cap=timedelta(seconds=settings.card_lookup_retry_cap_seconds),
|
|
186
|
+
now=self._now,
|
|
187
|
+
),
|
|
188
|
+
enrichment=EnrichmentService(
|
|
189
|
+
self._session_factory,
|
|
190
|
+
self._client,
|
|
191
|
+
self._payload_store,
|
|
192
|
+
extractor,
|
|
193
|
+
compiler,
|
|
194
|
+
retry_base=timedelta(seconds=settings.enrichment_retry_base_seconds),
|
|
195
|
+
retry_cap=timedelta(seconds=settings.enrichment_retry_cap_seconds),
|
|
196
|
+
now=self._now,
|
|
197
|
+
),
|
|
198
|
+
extractor=extractor,
|
|
199
|
+
)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Explicit re-extraction of a scope's member fichas (``pc reextract``)."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any, cast
|
|
6
|
+
|
|
7
|
+
from jsonschema import Draft202012Validator
|
|
8
|
+
from sqlalchemy import Column, MetaData, String, Table, literal, select
|
|
9
|
+
from sqlalchemy.orm import Session
|
|
10
|
+
|
|
11
|
+
from piloto_ai_cli.errors import ContractError, ContractErrorCode
|
|
12
|
+
from piloto_ai_cli.extraction import ExtractService, ReextractionResult
|
|
13
|
+
from piloto_ai_cli.schema.contract import CONTRACT_V1_SCHEMA
|
|
14
|
+
from piloto_ai_cli.schema.models import SCHEMA, DepartmentSync, Ficha
|
|
15
|
+
|
|
16
|
+
# The scope of ``pc reextract`` is the contract's ``scope`` object (proposal §3).
|
|
17
|
+
_SCOPE_VALIDATOR = Draft202012Validator(
|
|
18
|
+
cast(dict[str, Any], CONTRACT_V1_SCHEMA["properties"]["scope"])
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
_METADATA = MetaData()
|
|
22
|
+
_MEMBER_FICHA = Table("v_member_ficha", _METADATA, Column("ficha_id", String()), schema=SCHEMA)
|
|
23
|
+
_DEPARTMENT_FICHA = Table(
|
|
24
|
+
"v_department_ficha",
|
|
25
|
+
_METADATA,
|
|
26
|
+
Column("ficha_id", String()),
|
|
27
|
+
Column("department", String()),
|
|
28
|
+
schema=SCHEMA,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True, slots=True)
|
|
33
|
+
class ReextractedFicha:
|
|
34
|
+
"""One member ficha whose passes were re-run."""
|
|
35
|
+
|
|
36
|
+
ficha_id: str
|
|
37
|
+
result: ReextractionResult
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class ScopeReextraction:
|
|
42
|
+
"""The fichas re-extracted within ``max_items`` and the members left over."""
|
|
43
|
+
|
|
44
|
+
fichas: tuple[ReextractedFicha, ...]
|
|
45
|
+
not_processed: tuple[str, ...]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def validate_scope(document: object) -> dict[str, str]:
|
|
49
|
+
"""Return a scope object valid under the contract schema, or raise a refusal."""
|
|
50
|
+
error = next(iter(sorted(_SCOPE_VALIDATOR.iter_errors(document), key=str)), None)
|
|
51
|
+
if error is not None:
|
|
52
|
+
location = ".".join(["scope", *(str(part) for part in error.absolute_path)])
|
|
53
|
+
raise ContractError(ContractErrorCode.SCHEMA_VIOLATION, location, error.message)
|
|
54
|
+
scope = cast(dict[str, str], document)
|
|
55
|
+
if "department" in scope and "agreement" not in scope:
|
|
56
|
+
raise ContractError(
|
|
57
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
58
|
+
"scope.agreement",
|
|
59
|
+
"Department scope requires an agreement.",
|
|
60
|
+
)
|
|
61
|
+
return dict(scope)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def scope_member_ids(session: Session, scope: Mapping[str, str]) -> list[str]:
|
|
65
|
+
"""Return the ids of the scope's member fichas that have an extraction input.
|
|
66
|
+
|
|
67
|
+
Membership is ``v_department_ficha`` when the scope has a department, else
|
|
68
|
+
``v_member_ficha``, as for queries. Fichas without an input (never carded
|
|
69
|
+
or built) have nothing to extract and are left out. Ids are ordered so a
|
|
70
|
+
``max_items`` cut is deterministic.
|
|
71
|
+
|
|
72
|
+
A department never synced for the agreement has unknown membership, so it
|
|
73
|
+
is refused with ``department_unavailable`` (as ``pc query`` does) rather
|
|
74
|
+
than read as an empty scope (data-model.md §4, department availability).
|
|
75
|
+
"""
|
|
76
|
+
if (department := scope.get("department")) is not None:
|
|
77
|
+
synced = session.get(DepartmentSync, (scope["agreement"], department))
|
|
78
|
+
if synced is None:
|
|
79
|
+
raise ContractError(
|
|
80
|
+
ContractErrorCode.DEPARTMENT_UNAVAILABLE,
|
|
81
|
+
"scope.department",
|
|
82
|
+
"Department was not synced.",
|
|
83
|
+
)
|
|
84
|
+
membership = _DEPARTMENT_FICHA
|
|
85
|
+
membership_conditions = [
|
|
86
|
+
membership.c.ficha_id == Ficha.ficha_id,
|
|
87
|
+
membership.c.department == department,
|
|
88
|
+
]
|
|
89
|
+
else:
|
|
90
|
+
membership = _MEMBER_FICHA
|
|
91
|
+
membership_conditions = [membership.c.ficha_id == Ficha.ficha_id]
|
|
92
|
+
conditions = [
|
|
93
|
+
select(literal(1)).select_from(membership).where(*membership_conditions).exists(),
|
|
94
|
+
Ficha.input_hash.is_not(None),
|
|
95
|
+
]
|
|
96
|
+
for field, column in (
|
|
97
|
+
("agreement", Ficha.agreement_id),
|
|
98
|
+
("catalogue", Ficha.catalogue),
|
|
99
|
+
("category", Ficha.category),
|
|
100
|
+
):
|
|
101
|
+
if field in scope:
|
|
102
|
+
conditions.append(column == scope[field])
|
|
103
|
+
return list(
|
|
104
|
+
session.scalars(select(Ficha.ficha_id).where(*conditions).order_by(Ficha.ficha_id)).all()
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def reextract_scope(
|
|
109
|
+
session: Session,
|
|
110
|
+
service: ExtractService,
|
|
111
|
+
scope: Mapping[str, str],
|
|
112
|
+
max_items: int,
|
|
113
|
+
) -> ScopeReextraction:
|
|
114
|
+
"""Re-run both passes for the first ``max_items`` member fichas of a scope.
|
|
115
|
+
|
|
116
|
+
``max_items`` counts fichas (endpoints.md, rule 14): the members past it
|
|
117
|
+
are returned as not processed, never silently dropped. Each ficha's passes
|
|
118
|
+
commit as they finish (``ExtractService.reextract``), so an interrupted
|
|
119
|
+
run keeps the fichas it already re-extracted.
|
|
120
|
+
"""
|
|
121
|
+
if max_items < 1:
|
|
122
|
+
raise ValueError("max_items must be positive")
|
|
123
|
+
member_ids = scope_member_ids(session, scope)
|
|
124
|
+
selected, not_processed = member_ids[:max_items], member_ids[max_items:]
|
|
125
|
+
fichas: list[ReextractedFicha] = []
|
|
126
|
+
for ficha_id in selected:
|
|
127
|
+
ficha = session.get_one(Ficha, ficha_id)
|
|
128
|
+
fichas.append(ReextractedFicha(ficha_id, await service.reextract(ficha)))
|
|
129
|
+
return ScopeReextraction(tuple(fichas), tuple(not_processed))
|