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.
Files changed (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,398 @@
1
+ """Endpoint and database-integrity checks for ``pc health``."""
2
+
3
+ from collections import Counter
4
+ from collections.abc import Callable, Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ import httpx2
9
+ from sqlalchemy import and_, func, select
10
+ from sqlalchemy.exc import SQLAlchemyError
11
+ from sqlalchemy.orm import Session
12
+
13
+ from piloto_ai_cli.connectors import (
14
+ HOME_URL,
15
+ get_home,
16
+ get_pdf_response,
17
+ post_download_response,
18
+ post_search_response,
19
+ )
20
+ from piloto_ai_cli.excel import ExcelFicha, parse_excel
21
+ from piloto_ai_cli.http_client import HttpClient
22
+ from piloto_ai_cli.parsers import (
23
+ AgreementCard,
24
+ HomePage,
25
+ parse_cards,
26
+ parse_filter_pane,
27
+ parse_home,
28
+ )
29
+ from piloto_ai_cli.pdf_parser import parse_pdf_text
30
+ from piloto_ai_cli.schema.models import Base
31
+ from piloto_ai_cli.search_form import SearchForm
32
+
33
+ # Failures of our own storage (run log, request log, payload store), not of the
34
+ # site: they propagate so the command reports them as such instead of blaming
35
+ # an endpoint or parser.
36
+ _INFRASTRUCTURE_ERRORS = (SQLAlchemyError, OSError)
37
+ # Reason prefix of a check that did not run. Whether another check's failure
38
+ # caused it is never inferred from this text: ``HealthCheck.blocked_by`` names
39
+ # that check, and is None when the blocker is a precondition that is not a check.
40
+ NOT_RUN_PREFIX = "not run: "
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class HealthCheck:
45
+ """The result of one endpoint/parser or foreign-key check."""
46
+
47
+ check: str
48
+ status: Literal["ok", "failed"]
49
+ reason: str | None = None
50
+ # For a check that did not run: the failed check (in the same report) that
51
+ # kept it from running, or None when what blocked it is not a check (a
52
+ # precondition such as an agreement list with no fichas).
53
+ blocked_by: str | None = None
54
+
55
+ def as_dict(self) -> dict[str, str | None]:
56
+ return {
57
+ "check": self.check,
58
+ "status": self.status,
59
+ "reason": self.reason,
60
+ "blocked_by": self.blocked_by,
61
+ }
62
+
63
+
64
+ def _failure(check: str, error: Exception | str) -> HealthCheck:
65
+ reason = (str(error) or type(error).__name__) if isinstance(error, Exception) else error
66
+ return HealthCheck(check, "failed", reason)
67
+
68
+
69
+ def _response_result(
70
+ check: str,
71
+ response: httpx2.Response,
72
+ parser: Callable[[], object],
73
+ ) -> tuple[HealthCheck, object | None]:
74
+ if response.extensions.get("is_error_page"):
75
+ return _failure(check, "site returned its error page"), None
76
+ try:
77
+ response.raise_for_status()
78
+ return HealthCheck(check, "ok"), parser()
79
+ except _INFRASTRUCTURE_ERRORS:
80
+ raise
81
+ except Exception as error:
82
+ return _failure(check, error), None
83
+
84
+
85
+ def _not_run(check: str, reason: str | None, blocked_by: str | None) -> HealthCheck:
86
+ """Report a check that did not run, naming the failed check that blocked it, if any."""
87
+ return HealthCheck(
88
+ check,
89
+ "failed",
90
+ f"{NOT_RUN_PREFIX}{reason or 'a prerequisite check failed'}",
91
+ blocked_by,
92
+ )
93
+
94
+
95
+ def _parse_search_cards(fragment: str) -> None:
96
+ if not parse_cards(fragment):
97
+ raise ValueError("search response contained no ficha cards")
98
+
99
+
100
+ def _parse_filter_pane(fragment: str) -> None:
101
+ pane = parse_filter_pane(fragment)
102
+ if not pane.categories:
103
+ raise ValueError("search response contained no filter categories")
104
+ if not pane.attributes:
105
+ raise ValueError("search response contained no filter attributes")
106
+
107
+
108
+ def _parse_excel(body: bytes) -> list[ExcelFicha]:
109
+ rows = parse_excel(body)
110
+ if not rows:
111
+ raise ValueError("Excel export contained no ficha rows")
112
+ return rows
113
+
114
+
115
+ def _parse_pdf(body: bytes) -> bool:
116
+ """Parse a PDF and return whether it has a text layer."""
117
+ text, page_count = parse_pdf_text(body)
118
+ if not page_count:
119
+ raise ValueError("PDF contained no pages")
120
+ return bool(text.strip())
121
+
122
+
123
+ # A ficha PDF is whatever the supplier uploaded: many are scans with no text
124
+ # layer, and some cannot be parsed at all (enrichment records both without
125
+ # text). Such a PDF says nothing about the endpoint or the parser, so the PDF
126
+ # check moves on to the export's next distinct PDF URL, up to this many PDFs,
127
+ # and fails only if none has text.
128
+ MAX_PDF_SAMPLES = 5
129
+ NO_TEXT_REASON = "PDF contained no extractable text"
130
+
131
+ ENDPOINT_CHECKS = (
132
+ "get_home.parse_home",
133
+ "post_search.parse_cards",
134
+ "post_search.parse_filter_pane",
135
+ "post_download.parse_excel",
136
+ "get_pdf.parse_pdf_text",
137
+ )
138
+ STORAGE_CHECK = "storage.request_log"
139
+
140
+
141
+ async def check_endpoints(client: HttpClient) -> list[HealthCheck]:
142
+ """Make one request per endpoint and run each parser on the stored response.
143
+
144
+ The checks run on the smallest agreement with fichas: its Excel export first,
145
+ then a search scoped to that agreement and the category of the export's first
146
+ row with a PDF (a category scope is what exposes the attribute filters), then
147
+ that row's PDF. A PDF that cannot be parsed, has no pages or has no text
148
+ layer (a scanned ficha) is a property of that document, not of the site, so
149
+ the PDF check then tries the export's next PDFs, up to ``MAX_PDF_SAMPLES`` in
150
+ all; a transport error, an HTTP error status, the site's error page or any
151
+ other HTML response fails it at once.
152
+
153
+ A request-log or payload-store failure stops the endpoint checks but does not
154
+ lose the results already gathered: those are kept, the checks that did not
155
+ run are reported as ``not run``, and a ``storage.request_log`` failure is
156
+ added. ``write_request`` sends a request before logging it, so such a failure
157
+ means at least one request may have gone out unlogged.
158
+ """
159
+ results: dict[str, HealthCheck] = {}
160
+ try:
161
+ await _run_endpoint_checks(client, results)
162
+ except _INFRASTRUCTURE_ERRORS as error:
163
+ reason = (str(error).splitlines() or [type(error).__name__])[0] or type(error).__name__
164
+ checks = [
165
+ results.get(name)
166
+ or _not_run(name, f"request log or payload store failed: {reason}", STORAGE_CHECK)
167
+ for name in ENDPOINT_CHECKS
168
+ ]
169
+ checks.append(
170
+ _failure(
171
+ STORAGE_CHECK,
172
+ f"request log or payload store failed: {reason}; "
173
+ "the last request may have been sent without being logged",
174
+ )
175
+ )
176
+ return checks
177
+ return [results[name] for name in ENDPOINT_CHECKS]
178
+
179
+
180
+ async def _run_endpoint_checks(client: HttpClient, results: dict[str, HealthCheck]) -> None:
181
+ """Run the endpoint checks, recording each result in ``results`` as it completes."""
182
+ try:
183
+ response = await get_home(client, allow_error_page=True)
184
+ except _INFRASTRUCTURE_ERRORS:
185
+ raise
186
+ except Exception as error:
187
+ home_check = _failure("get_home.parse_home", error)
188
+ home_page = None
189
+ else:
190
+ home_check, parsed_home = _response_result(
191
+ "get_home.parse_home", response, lambda: parse_home(response.text)
192
+ )
193
+ home_page = parsed_home if isinstance(parsed_home, HomePage) else None
194
+ results[home_check.check] = home_check
195
+
196
+ agreement: AgreementCard | None = None
197
+ prerequisite_reason: str | None = home_check.reason
198
+ if home_check.status == "ok" and home_page is not None:
199
+ populated = [card for card in home_page.agreements if card.ficha_count > 0]
200
+ if populated:
201
+ agreement = min(populated, key=lambda card: card.ficha_count)
202
+ prerequisite_reason = (
203
+ "GET / did not provide an antiforgery token" if client.token is None else None
204
+ )
205
+ else:
206
+ prerequisite_reason = "GET / listed no agreement with fichas"
207
+
208
+ excel_rows: list[ExcelFicha] | None = None
209
+ if prerequisite_reason is not None or agreement is None:
210
+ # Blocked by the home check when it failed; otherwise by a precondition
211
+ # (no agreement with fichas, no antiforgery token), which is no check.
212
+ download_check = _not_run(
213
+ "post_download.parse_excel",
214
+ prerequisite_reason,
215
+ "get_home.parse_home" if home_check.status == "failed" else None,
216
+ )
217
+ else:
218
+ download_form = SearchForm(
219
+ scope={"agreement": agreement.filter_value},
220
+ pagination_page="1",
221
+ pagination_left_most_page="1",
222
+ )
223
+ try:
224
+ response = await post_download_response(client, HOME_URL, download_form)
225
+ except _INFRASTRUCTURE_ERRORS:
226
+ raise
227
+ except Exception as error:
228
+ download_check = _failure("post_download.parse_excel", error)
229
+ else:
230
+ download_check, parsed_rows = _response_result(
231
+ "post_download.parse_excel",
232
+ response,
233
+ lambda: _parse_excel(response.content),
234
+ )
235
+ excel_rows = parsed_rows if isinstance(parsed_rows, list) else None
236
+
237
+ results[download_check.check] = download_check
238
+
239
+ sample: ExcelFicha | None = None
240
+ if excel_rows:
241
+ sample = next((row for row in excel_rows if row.pdf_url), excel_rows[0])
242
+
243
+ # The search and the PDF need a row of the export, so a failed download
244
+ # check (failed or not run itself) is what blocks them.
245
+ download_blocker = "post_download.parse_excel" if download_check.status == "failed" else None
246
+ if agreement is None or sample is None:
247
+ search_reason = prerequisite_reason or download_check.reason
248
+ search_checks = [
249
+ _not_run("post_search.parse_cards", search_reason, download_blocker),
250
+ _not_run("post_search.parse_filter_pane", search_reason, download_blocker),
251
+ ]
252
+ else:
253
+ search_form = SearchForm(
254
+ scope={"agreement": agreement.filter_value, "category": sample.category},
255
+ pagination_page="1",
256
+ pagination_left_most_page="1",
257
+ )
258
+ try:
259
+ response = await post_search_response(client, search_form)
260
+ except _INFRASTRUCTURE_ERRORS:
261
+ raise
262
+ except Exception as error:
263
+ search_checks = [
264
+ _failure("post_search.parse_cards", error),
265
+ _failure("post_search.parse_filter_pane", error),
266
+ ]
267
+ else:
268
+ cards_check, _ = _response_result(
269
+ "post_search.parse_cards",
270
+ response,
271
+ lambda: _parse_search_cards(response.text),
272
+ )
273
+ pane_check, _ = _response_result(
274
+ "post_search.parse_filter_pane",
275
+ response,
276
+ lambda: _parse_filter_pane(response.text),
277
+ )
278
+ search_checks = [cards_check, pane_check]
279
+
280
+ for search_check in search_checks:
281
+ results[search_check.check] = search_check
282
+ if sample is None:
283
+ pdf_check = _not_run(
284
+ "get_pdf.parse_pdf_text",
285
+ prerequisite_reason or download_check.reason or "Excel export contained no ficha rows",
286
+ download_blocker,
287
+ )
288
+ elif sample.pdf_url is None:
289
+ # A precondition, not a check: the download check itself passed.
290
+ pdf_check = _not_run("get_pdf.parse_pdf_text", "Excel rows contained no PDF URL", None)
291
+ else:
292
+ pdf_check = await _check_pdfs(client, excel_rows or [sample])
293
+ results[pdf_check.check] = pdf_check
294
+
295
+
296
+ async def _check_pdfs(client: HttpClient, rows: Sequence[ExcelFicha]) -> HealthCheck:
297
+ """Check the export's PDFs in order until one has a text layer.
298
+
299
+ What a PDF contains is whatever the supplier uploaded, so a PDF that cannot
300
+ be parsed, has no pages or has no text layer moves the check on to the next
301
+ one. A transport error, an HTTP error status, the site's error page or any
302
+ other HTML response describes the endpoint and fails the check at once. The
303
+ check fails when no sampled PDF has text; its reason counts each distinct
304
+ per-document cause, in sample order.
305
+ """
306
+ check = "get_pdf.parse_pdf_text"
307
+ pdf_urls = list(dict.fromkeys(row.pdf_url for row in rows if row.pdf_url))
308
+ sampled = pdf_urls[:MAX_PDF_SAMPLES]
309
+ document_reasons: list[str] = []
310
+ for pdf_url in sampled:
311
+ try:
312
+ response = await get_pdf_response(client, pdf_url)
313
+ except _INFRASTRUCTURE_ERRORS:
314
+ raise
315
+ except Exception as error:
316
+ return _failure(check, error)
317
+ if response.extensions.get("is_error_page"):
318
+ return _failure(check, "site returned its error page")
319
+ try:
320
+ response.raise_for_status()
321
+ except Exception as error:
322
+ return _failure(check, error)
323
+ if _is_html(response):
324
+ # Same test write_request() uses: HTML where a PDF belongs is a page
325
+ # of the site (maintenance, login, soft 404), not a supplier file.
326
+ return _failure(check, "site returned HTML instead of a PDF")
327
+ try:
328
+ has_text = _parse_pdf(response.content)
329
+ except _INFRASTRUCTURE_ERRORS:
330
+ raise
331
+ except Exception as error:
332
+ document_reasons.append(str(error) or type(error).__name__)
333
+ continue
334
+ if has_text:
335
+ return HealthCheck(check, "ok")
336
+ document_reasons.append(NO_TEXT_REASON)
337
+ if len(document_reasons) == 1:
338
+ return _failure(check, document_reasons[0])
339
+ reason = f"none of the {len(sampled)} PDFs sampled contained extractable text"
340
+ counts = Counter(document_reasons)
341
+ if set(counts) != {NO_TEXT_REASON}:
342
+ # Counter keeps first-seen order, so the reasons appear in sample order.
343
+ reason += " (" + "; ".join(f"{n} x {text}" for text, n in counts.items()) + ")"
344
+ return _failure(check, reason)
345
+
346
+
347
+ def _is_html(response: httpx2.Response) -> bool:
348
+ content_type = response.headers.get("content-type", "")
349
+ return "html" in content_type.lower() or response.content.lstrip().startswith(b"<")
350
+
351
+
352
+ def check_orphans(session: Session) -> list[HealthCheck]:
353
+ """Run one anti-join for each declared foreign-key constraint."""
354
+ checks: list[HealthCheck] = []
355
+ tables = sorted(Base.metadata.tables.values(), key=lambda table: table.fullname)
356
+ for table in tables:
357
+ constraints = sorted(
358
+ table.foreign_key_constraints,
359
+ key=lambda constraint: tuple(element.parent.name for element in constraint.elements),
360
+ )
361
+ for constraint in constraints:
362
+ elements = tuple(constraint.elements)
363
+ parent_alias = constraint.referred_table.alias()
364
+ conditions = [
365
+ table.c[element.parent.name] == parent_alias.c[element.column.name]
366
+ for element in elements
367
+ ]
368
+ populated = [table.c[element.parent.name].is_not(None) for element in elements]
369
+ missing = [parent_alias.c[element.column.name].is_(None) for element in elements]
370
+ check_name = (
371
+ f"orphan:{table.name}."
372
+ f"{','.join(element.parent.name for element in elements)}->"
373
+ f"{constraint.referred_table.name}."
374
+ f"{','.join(element.column.name for element in elements)}"
375
+ )
376
+ statement = (
377
+ select(func.count())
378
+ .select_from(table.outerjoin(parent_alias, and_(*conditions)))
379
+ .where(and_(*populated, *missing))
380
+ )
381
+ try:
382
+ count = session.scalar(statement) or 0
383
+ except Exception as error:
384
+ # A failed orphan query is that foreign key's failure: report it
385
+ # and carry on with the other constraints.
386
+ session.rollback()
387
+ checks.append(_failure(check_name, error))
388
+ continue
389
+ if count:
390
+ checks.append(_failure(check_name, f"{count} orphan row(s)"))
391
+ else:
392
+ checks.append(HealthCheck(check_name, "ok"))
393
+ return checks
394
+
395
+
396
+ def check_summary(checks: Sequence[HealthCheck]) -> tuple[dict[str, str | None], ...]:
397
+ """Convert checks to JSON-compatible structured results."""
398
+ return tuple(check.as_dict() for check in checks)