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
piloto_ai_cli/cli.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
"""Command-line entry point."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
8
|
+
from dataclasses import asdict, dataclass
|
|
9
|
+
from importlib.metadata import version
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any, Literal, cast
|
|
12
|
+
|
|
13
|
+
import typer
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.table import Table
|
|
16
|
+
from rich.text import Text
|
|
17
|
+
from sqlalchemy.exc import SQLAlchemyError
|
|
18
|
+
from sqlalchemy.orm import Session
|
|
19
|
+
from typer.core import TyperGroup
|
|
20
|
+
|
|
21
|
+
from piloto_ai_cli import DISTRIBUTION_NAME
|
|
22
|
+
from piloto_ai_cli.api import NOT_GIVEN, execute_attributes, execute_query, execute_save
|
|
23
|
+
from piloto_ai_cli.database import (
|
|
24
|
+
dispose_shared_engines,
|
|
25
|
+
make_engine,
|
|
26
|
+
make_session_factory,
|
|
27
|
+
sync_extraction_config,
|
|
28
|
+
)
|
|
29
|
+
from piloto_ai_cli.errors import ContractError, ContractErrorCode, ReviewError
|
|
30
|
+
from piloto_ai_cli.extraction import ExtractService
|
|
31
|
+
from piloto_ai_cli.health import HealthCheck, check_endpoints, check_orphans, check_summary
|
|
32
|
+
from piloto_ai_cli.http_client import HttpClient
|
|
33
|
+
from piloto_ai_cli.llm_client import LLMClient, LLMConfigurationError, LLMCredentialError
|
|
34
|
+
from piloto_ai_cli.payload_store import make_payload_store
|
|
35
|
+
from piloto_ai_cli.query_result import QueryResult
|
|
36
|
+
from piloto_ai_cli.reextract import ScopeReextraction, reextract_scope, validate_scope
|
|
37
|
+
from piloto_ai_cli.review import (
|
|
38
|
+
ProposalType,
|
|
39
|
+
list_pending_proposals,
|
|
40
|
+
merge_attribute,
|
|
41
|
+
review_proposal,
|
|
42
|
+
)
|
|
43
|
+
from piloto_ai_cli.run_log import RunLog
|
|
44
|
+
from piloto_ai_cli.settings import Settings
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class CliOptions:
|
|
49
|
+
"""Global options shared by CLI commands."""
|
|
50
|
+
|
|
51
|
+
json_output: bool
|
|
52
|
+
profile: Literal["pilot", "ci-mock"] | None
|
|
53
|
+
max_items: int | None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ErrorHandlingGroup(TyperGroup):
|
|
57
|
+
"""Render typed contract errors consistently for every command."""
|
|
58
|
+
|
|
59
|
+
def invoke(self, ctx: Any) -> Any:
|
|
60
|
+
try:
|
|
61
|
+
return super().invoke(ctx)
|
|
62
|
+
except (ContractError, ReviewError) as error:
|
|
63
|
+
output = error.to_json() if ctx.params.get("json_output") else str(error)
|
|
64
|
+
typer.echo(output, err=True)
|
|
65
|
+
raise typer.Exit(code=2) from None
|
|
66
|
+
except LLMConfigurationError as error:
|
|
67
|
+
# Configuration, not a refusal: the run is closed as failed.
|
|
68
|
+
code = (
|
|
69
|
+
"llm_credential_rejected"
|
|
70
|
+
if isinstance(error, LLMCredentialError)
|
|
71
|
+
else "llm_configuration_error"
|
|
72
|
+
)
|
|
73
|
+
if ctx.params.get("json_output"):
|
|
74
|
+
fields: dict[str, str] = {"code": code, "message": str(error)}
|
|
75
|
+
if isinstance(error, LLMCredentialError):
|
|
76
|
+
fields["request_id"] = error.request_id
|
|
77
|
+
output = json.dumps(fields, ensure_ascii=False, sort_keys=True)
|
|
78
|
+
else:
|
|
79
|
+
output = f"{code}: {error}"
|
|
80
|
+
typer.echo(output, err=True)
|
|
81
|
+
raise typer.Exit(code=1) from None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def create_app() -> typer.Typer:
|
|
85
|
+
"""Create the CLI app with global options and typed-error handling."""
|
|
86
|
+
app = typer.Typer(no_args_is_help=True, cls=ErrorHandlingGroup)
|
|
87
|
+
review_app = typer.Typer(no_args_is_help=False)
|
|
88
|
+
|
|
89
|
+
@app.callback(invoke_without_command=True)
|
|
90
|
+
def main(
|
|
91
|
+
ctx: typer.Context,
|
|
92
|
+
json_output: bool = typer.Option(False, "--json", help="Write results as JSON."),
|
|
93
|
+
profile: Literal["pilot", "ci-mock"] | None = typer.Option(
|
|
94
|
+
None, "--profile", help="Configuration profile to use."
|
|
95
|
+
),
|
|
96
|
+
max_items: int | None = typer.Option(
|
|
97
|
+
None, "--max-items", min=1, help="Maximum number of items to process."
|
|
98
|
+
),
|
|
99
|
+
version_option: bool = typer.Option(
|
|
100
|
+
False, "--version", help="Show the version and exit.", is_eager=True
|
|
101
|
+
),
|
|
102
|
+
) -> None:
|
|
103
|
+
if version_option:
|
|
104
|
+
typer.echo(f"pc {version(DISTRIBUTION_NAME)}")
|
|
105
|
+
raise typer.Exit()
|
|
106
|
+
ctx.obj = CliOptions(json_output, profile, max_items)
|
|
107
|
+
|
|
108
|
+
@review_app.callback(invoke_without_command=True)
|
|
109
|
+
def review(ctx: typer.Context) -> None:
|
|
110
|
+
if ctx.invoked_subcommand is None:
|
|
111
|
+
_run_review_command(ctx, "list", {}, list_pending_proposals)
|
|
112
|
+
|
|
113
|
+
@review_app.command()
|
|
114
|
+
def accept(
|
|
115
|
+
ctx: typer.Context,
|
|
116
|
+
proposal_type: ProposalType,
|
|
117
|
+
proposal_id: str,
|
|
118
|
+
) -> None:
|
|
119
|
+
def action(session: Session) -> list[dict[str, object]]:
|
|
120
|
+
review_proposal(session, proposal_type, proposal_id, "accept")
|
|
121
|
+
return [
|
|
122
|
+
{"proposal_type": proposal_type, "proposal_id": proposal_id, "status": "accepted"}
|
|
123
|
+
]
|
|
124
|
+
|
|
125
|
+
_run_review_command(
|
|
126
|
+
ctx, "accept", {"proposal_type": proposal_type, "proposal_id": proposal_id}, action
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
@review_app.command()
|
|
130
|
+
def reject(
|
|
131
|
+
ctx: typer.Context,
|
|
132
|
+
proposal_type: ProposalType,
|
|
133
|
+
proposal_id: str,
|
|
134
|
+
) -> None:
|
|
135
|
+
def action(session: Session) -> list[dict[str, object]]:
|
|
136
|
+
review_proposal(session, proposal_type, proposal_id, "reject")
|
|
137
|
+
return [
|
|
138
|
+
{"proposal_type": proposal_type, "proposal_id": proposal_id, "status": "rejected"}
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
_run_review_command(
|
|
142
|
+
ctx, "reject", {"proposal_type": proposal_type, "proposal_id": proposal_id}, action
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
@review_app.command()
|
|
146
|
+
def merge(
|
|
147
|
+
ctx: typer.Context,
|
|
148
|
+
attribute_id: str,
|
|
149
|
+
target_attribute_id: str,
|
|
150
|
+
) -> None:
|
|
151
|
+
def action(session: Session) -> list[dict[str, object]]:
|
|
152
|
+
merge_attribute(session, attribute_id, target_attribute_id)
|
|
153
|
+
return [
|
|
154
|
+
{
|
|
155
|
+
"attribute_id": attribute_id,
|
|
156
|
+
"merged_into": target_attribute_id,
|
|
157
|
+
"status": "accepted",
|
|
158
|
+
}
|
|
159
|
+
]
|
|
160
|
+
|
|
161
|
+
_run_review_command(
|
|
162
|
+
ctx,
|
|
163
|
+
"merge",
|
|
164
|
+
{"attribute_id": attribute_id, "target_attribute_id": target_attribute_id},
|
|
165
|
+
action,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
@app.command()
|
|
169
|
+
def save(ctx: typer.Context, document: str = typer.Argument(...)) -> None:
|
|
170
|
+
"""Validate and save a predicate document."""
|
|
171
|
+
options = ctx.obj
|
|
172
|
+
settings = Settings() if options.profile is None else Settings(profile=options.profile)
|
|
173
|
+
try:
|
|
174
|
+
query_id = execute_save(
|
|
175
|
+
settings, {"document": document}, lambda: _read_document(document)
|
|
176
|
+
)
|
|
177
|
+
finally:
|
|
178
|
+
dispose_shared_engines()
|
|
179
|
+
output = json.dumps({"query_id": query_id}) if options.json_output else query_id
|
|
180
|
+
typer.echo(output)
|
|
181
|
+
|
|
182
|
+
@app.command()
|
|
183
|
+
def query(
|
|
184
|
+
ctx: typer.Context,
|
|
185
|
+
document: str | None = typer.Argument(
|
|
186
|
+
None, help="Predicate document (inline JSON, a file, or - for stdin)."
|
|
187
|
+
),
|
|
188
|
+
saved: str | None = typer.Option(
|
|
189
|
+
None, "--saved", help="Run the saved query with this id instead of a document."
|
|
190
|
+
),
|
|
191
|
+
) -> None:
|
|
192
|
+
"""Validate a predicate document, sync what it needs, run it, and return the result."""
|
|
193
|
+
if document is None and saved is None:
|
|
194
|
+
raise typer.BadParameter("Give a document or --saved <id>.")
|
|
195
|
+
if document is not None and saved is not None:
|
|
196
|
+
raise typer.BadParameter("Give a document or --saved <id>, not both.")
|
|
197
|
+
options = ctx.obj
|
|
198
|
+
settings = Settings() if options.profile is None else Settings(profile=options.profile)
|
|
199
|
+
arguments: dict[str, object] = (
|
|
200
|
+
{"saved": saved} if saved is not None else {"document": document}
|
|
201
|
+
)
|
|
202
|
+
try:
|
|
203
|
+
result, contract = execute_query(
|
|
204
|
+
settings,
|
|
205
|
+
{**arguments, "max_items": options.max_items},
|
|
206
|
+
document=None if document is None else lambda: _read_document(document),
|
|
207
|
+
saved=NOT_GIVEN if saved is None else saved,
|
|
208
|
+
max_items=options.max_items,
|
|
209
|
+
)
|
|
210
|
+
finally:
|
|
211
|
+
dispose_shared_engines()
|
|
212
|
+
if options.json_output:
|
|
213
|
+
typer.echo(json.dumps(result.model_dump(mode="json"), ensure_ascii=False))
|
|
214
|
+
return
|
|
215
|
+
_render_query_result(
|
|
216
|
+
result, rows_included=(contract.include or {}).get("rows", True) is not False
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
@app.command()
|
|
220
|
+
def health(ctx: typer.Context) -> None:
|
|
221
|
+
"""Check catalog endpoints, parsers, and database foreign keys."""
|
|
222
|
+
options = ctx.obj
|
|
223
|
+
settings = Settings() if options.profile is None else Settings(profile=options.profile)
|
|
224
|
+
engine = make_engine(settings)
|
|
225
|
+
try:
|
|
226
|
+
session_factory = make_session_factory(engine)
|
|
227
|
+
checks: list[HealthCheck] = []
|
|
228
|
+
try:
|
|
229
|
+
with session_factory() as session:
|
|
230
|
+
with RunLog.open(session, "health", {}) as run:
|
|
231
|
+
with engine.connect() as connection:
|
|
232
|
+
payload_store = make_payload_store(settings, connection)
|
|
233
|
+
|
|
234
|
+
async def endpoint_checks() -> list[HealthCheck]:
|
|
235
|
+
async with HttpClient(
|
|
236
|
+
settings,
|
|
237
|
+
session_factory=session_factory,
|
|
238
|
+
payload_store=payload_store,
|
|
239
|
+
run_id=run.run_id,
|
|
240
|
+
) as client:
|
|
241
|
+
return await check_endpoints(client)
|
|
242
|
+
|
|
243
|
+
checks.extend(asyncio.run(endpoint_checks()))
|
|
244
|
+
checks.extend(check_orphans(session))
|
|
245
|
+
run.close(
|
|
246
|
+
"failed" if any(item.status == "failed" for item in checks) else "ok"
|
|
247
|
+
)
|
|
248
|
+
except (SQLAlchemyError, OSError) as error:
|
|
249
|
+
# Run log, request log or payload store failure.
|
|
250
|
+
reason = str(error).splitlines()[0] if str(error) else type(error).__name__
|
|
251
|
+
if not checks:
|
|
252
|
+
# The database, run log or payload store failed before any check
|
|
253
|
+
# ran (check_endpoints reports request-log failures itself, with
|
|
254
|
+
# its partial results): report it as a structured failed check.
|
|
255
|
+
checks = [HealthCheck("database.run_log", "failed", reason)]
|
|
256
|
+
else:
|
|
257
|
+
# The checks already ran (and their requests were logged); keep
|
|
258
|
+
# their results and add the late database failure.
|
|
259
|
+
checks.append(
|
|
260
|
+
HealthCheck(
|
|
261
|
+
"database.run_log",
|
|
262
|
+
"failed",
|
|
263
|
+
f"database error after the checks ran: {reason}",
|
|
264
|
+
)
|
|
265
|
+
)
|
|
266
|
+
columns = ("check", "status", "reason")
|
|
267
|
+
if options.json_output:
|
|
268
|
+
typer.echo(json.dumps({"checks": check_summary(checks)}, ensure_ascii=False))
|
|
269
|
+
else:
|
|
270
|
+
rows = [
|
|
271
|
+
{key: "" if value is None else value for key, value in row.items()}
|
|
272
|
+
for row in check_summary(checks)
|
|
273
|
+
]
|
|
274
|
+
render_rows(rows, columns, title="Health checks")
|
|
275
|
+
if any(item.status == "failed" for item in checks):
|
|
276
|
+
raise typer.Exit(code=1)
|
|
277
|
+
finally:
|
|
278
|
+
engine.dispose()
|
|
279
|
+
|
|
280
|
+
@app.command()
|
|
281
|
+
def reextract(
|
|
282
|
+
ctx: typer.Context,
|
|
283
|
+
scope: str = typer.Argument(
|
|
284
|
+
..., help="Scope as a JSON object (inline, a file, or - for stdin)."
|
|
285
|
+
),
|
|
286
|
+
) -> None:
|
|
287
|
+
"""Re-run extraction for a scope's member fichas under the current rules and model."""
|
|
288
|
+
options = ctx.obj
|
|
289
|
+
settings = Settings() if options.profile is None else Settings(profile=options.profile)
|
|
290
|
+
max_items = options.max_items if options.max_items is not None else settings.max_items
|
|
291
|
+
engine = make_engine(settings)
|
|
292
|
+
try:
|
|
293
|
+
session_factory = make_session_factory(engine)
|
|
294
|
+
with session_factory() as session:
|
|
295
|
+
with RunLog.open(
|
|
296
|
+
session, "reextract", {"scope": scope, "max_items": max_items}
|
|
297
|
+
) as run:
|
|
298
|
+
validated_scope = validate_scope(_read_document(scope, location="scope"))
|
|
299
|
+
# Re-extract under the configured model and prompt version.
|
|
300
|
+
sync_extraction_config(session, settings)
|
|
301
|
+
with engine.connect() as connection:
|
|
302
|
+
payload_store = make_payload_store(settings, connection)
|
|
303
|
+
|
|
304
|
+
async def run_passes() -> ScopeReextraction:
|
|
305
|
+
async with HttpClient(
|
|
306
|
+
settings,
|
|
307
|
+
session_factory=session_factory,
|
|
308
|
+
payload_store=payload_store,
|
|
309
|
+
run_id=run.run_id,
|
|
310
|
+
) as client:
|
|
311
|
+
# Without a real provider (the ci-mock profile), only
|
|
312
|
+
# fichas the rules pass fully resolves can complete;
|
|
313
|
+
# the others report LLM status "unavailable".
|
|
314
|
+
llm_client = (
|
|
315
|
+
LLMClient(settings, client)
|
|
316
|
+
if settings.llm_provider != "mock"
|
|
317
|
+
else None
|
|
318
|
+
)
|
|
319
|
+
try:
|
|
320
|
+
service = ExtractService(
|
|
321
|
+
session,
|
|
322
|
+
payload_store,
|
|
323
|
+
llm_client=llm_client,
|
|
324
|
+
input_usd_per_mtok=settings.llm_input_usd_per_mtok,
|
|
325
|
+
output_usd_per_mtok=settings.llm_output_usd_per_mtok,
|
|
326
|
+
)
|
|
327
|
+
return await reextract_scope(
|
|
328
|
+
session, service, validated_scope, max_items
|
|
329
|
+
)
|
|
330
|
+
finally:
|
|
331
|
+
if llm_client is not None:
|
|
332
|
+
await llm_client.aclose()
|
|
333
|
+
|
|
334
|
+
result = asyncio.run(run_passes())
|
|
335
|
+
finally:
|
|
336
|
+
engine.dispose()
|
|
337
|
+
rows = [
|
|
338
|
+
{
|
|
339
|
+
"ficha_id": item.ficha_id,
|
|
340
|
+
"rules_extraction_id": item.result.rules.extraction_id,
|
|
341
|
+
"llm_status": item.result.llm.status,
|
|
342
|
+
"llm_extraction_id": item.result.llm.extraction_id,
|
|
343
|
+
"llm_cached": item.result.llm.cached,
|
|
344
|
+
"reason": item.result.llm.reason,
|
|
345
|
+
}
|
|
346
|
+
for item in result.fichas
|
|
347
|
+
]
|
|
348
|
+
if options.json_output:
|
|
349
|
+
typer.echo(
|
|
350
|
+
json.dumps(
|
|
351
|
+
{"fichas": rows, "not_processed": list(result.not_processed)},
|
|
352
|
+
ensure_ascii=False,
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
return
|
|
356
|
+
render_rows(
|
|
357
|
+
[{key: "" if value is None else value for key, value in row.items()} for row in rows],
|
|
358
|
+
(
|
|
359
|
+
"ficha_id",
|
|
360
|
+
"rules_extraction_id",
|
|
361
|
+
"llm_status",
|
|
362
|
+
"llm_extraction_id",
|
|
363
|
+
"llm_cached",
|
|
364
|
+
"reason",
|
|
365
|
+
),
|
|
366
|
+
title="Re-extracted fichas",
|
|
367
|
+
)
|
|
368
|
+
if result.not_processed:
|
|
369
|
+
typer.echo(
|
|
370
|
+
f"{len(result.not_processed)} member fichas not processed "
|
|
371
|
+
f"(max_items {max_items}); use --json to list them."
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
@app.command()
|
|
375
|
+
def attributes(
|
|
376
|
+
ctx: typer.Context,
|
|
377
|
+
scope: str = typer.Argument(
|
|
378
|
+
..., help="Scope as a JSON object (inline, a file, or - for stdin)."
|
|
379
|
+
),
|
|
380
|
+
) -> None:
|
|
381
|
+
"""List a one-category scope's attributes, or a wider scope's categories."""
|
|
382
|
+
options = ctx.obj
|
|
383
|
+
settings = Settings() if options.profile is None else Settings(profile=options.profile)
|
|
384
|
+
try:
|
|
385
|
+
listing = execute_attributes(
|
|
386
|
+
settings, {"scope": scope}, lambda: _read_document(scope, location="scope")
|
|
387
|
+
)
|
|
388
|
+
finally:
|
|
389
|
+
dispose_shared_engines()
|
|
390
|
+
if listing.category is None:
|
|
391
|
+
category_rows = [
|
|
392
|
+
{"catalogue": item.catalogue, "category": item.category}
|
|
393
|
+
for item in listing.categories
|
|
394
|
+
]
|
|
395
|
+
if options.json_output:
|
|
396
|
+
typer.echo(json.dumps({"categories": category_rows}, ensure_ascii=False))
|
|
397
|
+
return
|
|
398
|
+
render_rows(
|
|
399
|
+
[
|
|
400
|
+
{key: "" if value is None else value for key, value in row.items()}
|
|
401
|
+
for row in category_rows
|
|
402
|
+
],
|
|
403
|
+
("catalogue", "category"),
|
|
404
|
+
title="Categories",
|
|
405
|
+
)
|
|
406
|
+
return
|
|
407
|
+
attribute_rows = [
|
|
408
|
+
{
|
|
409
|
+
"attribute_id": item.attribute_id,
|
|
410
|
+
"display_name": item.display_name,
|
|
411
|
+
"kind": item.kind,
|
|
412
|
+
"canonical_unit": item.canonical_unit,
|
|
413
|
+
"values": list(item.values),
|
|
414
|
+
}
|
|
415
|
+
for item in listing.attributes
|
|
416
|
+
]
|
|
417
|
+
if options.json_output:
|
|
418
|
+
typer.echo(
|
|
419
|
+
json.dumps(
|
|
420
|
+
{"category": listing.category, "attributes": attribute_rows},
|
|
421
|
+
ensure_ascii=False,
|
|
422
|
+
)
|
|
423
|
+
)
|
|
424
|
+
return
|
|
425
|
+
render_rows(
|
|
426
|
+
[
|
|
427
|
+
{
|
|
428
|
+
**row,
|
|
429
|
+
"canonical_unit": row["canonical_unit"] or "",
|
|
430
|
+
"values": ", ".join(cast(list[str], row["values"])),
|
|
431
|
+
}
|
|
432
|
+
for row in attribute_rows
|
|
433
|
+
],
|
|
434
|
+
("attribute_id", "display_name", "kind", "canonical_unit", "values"),
|
|
435
|
+
title=f"Attributes of {listing.category}",
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
app.add_typer(review_app, name="review", help="List and review extraction proposals.")
|
|
439
|
+
return app
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _run_review_command(
|
|
443
|
+
ctx: typer.Context,
|
|
444
|
+
operation: str,
|
|
445
|
+
arguments: Mapping[str, object],
|
|
446
|
+
action: Callable[[Session], Sequence[Mapping[str, object]]],
|
|
447
|
+
) -> None:
|
|
448
|
+
"""Run a review action with the configured database and run log."""
|
|
449
|
+
options = ctx.find_object(CliOptions)
|
|
450
|
+
if options is None:
|
|
451
|
+
raise RuntimeError("CLI options are not available")
|
|
452
|
+
|
|
453
|
+
settings = Settings(profile=options.profile) if options.profile is not None else Settings()
|
|
454
|
+
engine = make_engine(settings)
|
|
455
|
+
try:
|
|
456
|
+
with make_session_factory(engine)() as session:
|
|
457
|
+
with RunLog.open(session, "review", {"operation": operation, **arguments}):
|
|
458
|
+
rows = action(session)
|
|
459
|
+
finally:
|
|
460
|
+
engine.dispose()
|
|
461
|
+
columns = (
|
|
462
|
+
(
|
|
463
|
+
"proposal_type",
|
|
464
|
+
"proposal_id",
|
|
465
|
+
"status",
|
|
466
|
+
"extraction_id",
|
|
467
|
+
"ficha_id",
|
|
468
|
+
"attribute_id",
|
|
469
|
+
"display_name",
|
|
470
|
+
"kind",
|
|
471
|
+
"canonical_unit",
|
|
472
|
+
"raw_label",
|
|
473
|
+
"raw_unit",
|
|
474
|
+
"category",
|
|
475
|
+
"factor",
|
|
476
|
+
)
|
|
477
|
+
if operation == "list"
|
|
478
|
+
else tuple(rows[0])
|
|
479
|
+
if rows
|
|
480
|
+
else ()
|
|
481
|
+
)
|
|
482
|
+
title = "Pending proposals" if operation == "list" else "Review result"
|
|
483
|
+
render_rows(rows, columns, json_output=options.json_output, title=title)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _render_query_result(result: QueryResult, *, rows_included: bool) -> None:
|
|
487
|
+
"""Render a query envelope for the terminal: matches, then the reports.
|
|
488
|
+
|
|
489
|
+
Matches keep the envelope's order; prices are shown as the site reports
|
|
490
|
+
them, never ordered or compared. With ``include.rows: false`` the envelope
|
|
491
|
+
holds no rows, so no match table or match count is shown.
|
|
492
|
+
"""
|
|
493
|
+
match_columns = (
|
|
494
|
+
"ficha_id",
|
|
495
|
+
"currency",
|
|
496
|
+
"offered_min",
|
|
497
|
+
"offered_max",
|
|
498
|
+
"contracted_min",
|
|
499
|
+
"contracted_max",
|
|
500
|
+
"card_stamp",
|
|
501
|
+
)
|
|
502
|
+
if rows_included:
|
|
503
|
+
render_rows(
|
|
504
|
+
[
|
|
505
|
+
{
|
|
506
|
+
column: "" if value is None else value
|
|
507
|
+
for column, value in match.model_dump(include=set(match_columns)).items()
|
|
508
|
+
}
|
|
509
|
+
for match in result.matches
|
|
510
|
+
],
|
|
511
|
+
match_columns,
|
|
512
|
+
title=f"Matches (contract version {result.contract_version})",
|
|
513
|
+
)
|
|
514
|
+
typer.echo(f"{len(result.matches)} matches, {result.non_matches} non-matches.")
|
|
515
|
+
else:
|
|
516
|
+
typer.echo(f"Rows not requested; {result.non_matches} non-matches.")
|
|
517
|
+
if result.department_as_of is not None:
|
|
518
|
+
typer.echo(f"Department list as of {result.department_as_of.isoformat()}.")
|
|
519
|
+
if result.unknown:
|
|
520
|
+
render_rows(
|
|
521
|
+
[asdict(item) for item in result.unknown],
|
|
522
|
+
("predicate_index", "attribute_id", "reason", "count"),
|
|
523
|
+
title="Unknown",
|
|
524
|
+
)
|
|
525
|
+
if result.not_applicable:
|
|
526
|
+
render_rows(
|
|
527
|
+
[asdict(item) for item in result.not_applicable],
|
|
528
|
+
("attribute_id", "checked", "pending"),
|
|
529
|
+
title="Not applicable",
|
|
530
|
+
)
|
|
531
|
+
pending = result.pending
|
|
532
|
+
typer.echo(
|
|
533
|
+
f"Pending: {pending.card_pending} cards, {pending.pdf_pending} PDFs, "
|
|
534
|
+
f"{pending.extraction_pending} extractions, {pending.proposals} proposals."
|
|
535
|
+
)
|
|
536
|
+
for name, facet in result.facets.items():
|
|
537
|
+
render_rows(
|
|
538
|
+
[{"value": value.value, "count": value.count} for value in facet.values],
|
|
539
|
+
("value", "count"),
|
|
540
|
+
title=f"Facet {name} ({facet.unknown_count} unknown)",
|
|
541
|
+
)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _read_document(argument: str, *, location: str = "contract") -> object:
|
|
545
|
+
"""Read a JSON document from a file, stdin, or an inline JSON argument."""
|
|
546
|
+
try:
|
|
547
|
+
if argument == "-":
|
|
548
|
+
content = sys.stdin.read()
|
|
549
|
+
elif argument.lstrip().startswith(("{", "[")):
|
|
550
|
+
content = argument
|
|
551
|
+
else:
|
|
552
|
+
path = Path(argument)
|
|
553
|
+
content = path.read_text(encoding="utf-8") if path.is_file() else argument
|
|
554
|
+
return json.loads(content, parse_constant=_reject_constant, parse_float=_finite_float)
|
|
555
|
+
except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as error:
|
|
556
|
+
if isinstance(error, json.JSONDecodeError):
|
|
557
|
+
message = error.msg
|
|
558
|
+
elif isinstance(error, (OSError, UnicodeError)):
|
|
559
|
+
message = "The document could not be read."
|
|
560
|
+
else:
|
|
561
|
+
message = str(error)
|
|
562
|
+
raise ContractError(
|
|
563
|
+
code=ContractErrorCode.SCHEMA_VIOLATION,
|
|
564
|
+
location=location,
|
|
565
|
+
message=f"Invalid JSON document: {message}",
|
|
566
|
+
) from None
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _reject_constant(constant: str) -> object:
|
|
570
|
+
"""Refuse NaN and the infinities, which ``json.loads`` accepts but JSON does not."""
|
|
571
|
+
raise ValueError(f"{constant} is not a valid JSON value")
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def _finite_float(literal: str) -> float:
|
|
575
|
+
"""Parse a JSON number, refusing ones that overflow to an infinity (e.g. ``1e400``)."""
|
|
576
|
+
number = float(literal)
|
|
577
|
+
if not math.isfinite(number):
|
|
578
|
+
raise ValueError(f"{literal} is out of range for a JSON number")
|
|
579
|
+
return number
|
|
580
|
+
|
|
581
|
+
|
|
582
|
+
def render_rows(
|
|
583
|
+
rows: Sequence[Mapping[str, object]],
|
|
584
|
+
columns: Sequence[str],
|
|
585
|
+
*,
|
|
586
|
+
json_output: bool = False,
|
|
587
|
+
title: str | None = None,
|
|
588
|
+
) -> None:
|
|
589
|
+
"""Render result rows as JSON or a terminal table."""
|
|
590
|
+
if json_output:
|
|
591
|
+
typer.echo(json.dumps([dict(row) for row in rows], ensure_ascii=False))
|
|
592
|
+
return
|
|
593
|
+
|
|
594
|
+
table = Table(title=title)
|
|
595
|
+
for column in columns:
|
|
596
|
+
table.add_column(column)
|
|
597
|
+
for row in rows:
|
|
598
|
+
table.add_row(*(Text(str(row.get(column, ""))) for column in columns))
|
|
599
|
+
Console().print(table)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
app = create_app()
|