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,250 @@
|
|
|
1
|
+
"""List what a scope offers to build predicates from (``pc attributes``).
|
|
2
|
+
|
|
3
|
+
data-model.md §4, ``pc attributes <scope>``: one stamp read, the Excel step if
|
|
4
|
+
stale and, when the scope is exactly one category, one ``post_search`` (page 1)
|
|
5
|
+
whose filter pane seeds that category on every call. The listing then reports
|
|
6
|
+
what is known: the category's applicable attributes, or, for a scope spanning
|
|
7
|
+
several categories, its categories from the Excel. No cards, PDFs or
|
|
8
|
+
extraction.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable, Mapping
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
|
|
17
|
+
from sqlalchemy import Column, MetaData, String, Table, literal, select
|
|
18
|
+
from sqlalchemy.orm import Session, sessionmaker
|
|
19
|
+
from sqlalchemy.sql import ColumnElement
|
|
20
|
+
|
|
21
|
+
from piloto_ai_cli.connectors import HOME_URL, post_search_response
|
|
22
|
+
from piloto_ai_cli.errors import ContractError, ContractErrorCode
|
|
23
|
+
from piloto_ai_cli.http_client import HttpClient
|
|
24
|
+
from piloto_ai_cli.pane import seed_filter_pane
|
|
25
|
+
from piloto_ai_cli.parsers import parse_filter_pane
|
|
26
|
+
from piloto_ai_cli.payload_store import PayloadStore
|
|
27
|
+
from piloto_ai_cli.schema.models import (
|
|
28
|
+
SCHEMA,
|
|
29
|
+
Agreement,
|
|
30
|
+
Attribute,
|
|
31
|
+
AttributeScope,
|
|
32
|
+
Ficha,
|
|
33
|
+
SeedValue,
|
|
34
|
+
)
|
|
35
|
+
from piloto_ai_cli.search_form import SearchForm
|
|
36
|
+
from piloto_ai_cli.stamp_service import StampService
|
|
37
|
+
from piloto_ai_cli.sync import SyncService
|
|
38
|
+
|
|
39
|
+
_METADATA = MetaData()
|
|
40
|
+
_MEMBER_FICHA = Table("v_member_ficha", _METADATA, Column("ficha_id", String()), schema=SCHEMA)
|
|
41
|
+
_DEPARTMENT_FICHA = Table(
|
|
42
|
+
"v_department_ficha",
|
|
43
|
+
_METADATA,
|
|
44
|
+
Column("ficha_id", String()),
|
|
45
|
+
Column("department", String()),
|
|
46
|
+
schema=SCHEMA,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True, slots=True)
|
|
51
|
+
class ApplicableAttribute:
|
|
52
|
+
"""One accepted attribute applicable to a category, with its pane vocabulary."""
|
|
53
|
+
|
|
54
|
+
attribute_id: str
|
|
55
|
+
display_name: str
|
|
56
|
+
kind: str
|
|
57
|
+
canonical_unit: str | None
|
|
58
|
+
values: tuple[str, ...]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True, slots=True)
|
|
62
|
+
class ScopeCategory:
|
|
63
|
+
"""One category of a scope's current members, with its catalogue."""
|
|
64
|
+
|
|
65
|
+
catalogue: str | None
|
|
66
|
+
category: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True, slots=True)
|
|
70
|
+
class AttributesListing:
|
|
71
|
+
"""The answer of ``pc attributes``.
|
|
72
|
+
|
|
73
|
+
A one-category scope has ``category`` set and lists its ``attributes``; any
|
|
74
|
+
other scope has ``category`` None and lists its ``categories`` instead.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
category: str | None
|
|
78
|
+
attributes: tuple[ApplicableAttribute, ...] = ()
|
|
79
|
+
categories: tuple[ScopeCategory, ...] = ()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class AttributesService:
|
|
83
|
+
"""Sync what ``pc attributes`` needs for a scope, then list it."""
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
session: Session,
|
|
88
|
+
session_factory: sessionmaker[Session],
|
|
89
|
+
client: HttpClient,
|
|
90
|
+
payload_store: PayloadStore,
|
|
91
|
+
*,
|
|
92
|
+
now: Callable[[], datetime] | None = None,
|
|
93
|
+
) -> None:
|
|
94
|
+
"""``session`` is the run's own session; the sync steps use ``session_factory``."""
|
|
95
|
+
self._session = session
|
|
96
|
+
self._session_factory = session_factory
|
|
97
|
+
self._client = client
|
|
98
|
+
self._payload_store = payload_store
|
|
99
|
+
self._now = now or (lambda: datetime.now(UTC))
|
|
100
|
+
|
|
101
|
+
async def run(self, scope: Mapping[str, str]) -> AttributesListing:
|
|
102
|
+
"""List a validated contract scope (see ``reextract.validate_scope``)."""
|
|
103
|
+
stamp = await StampService(self._session, self._client, now=self._now).read()
|
|
104
|
+
# The agreement refresh must be visible to the sync step's own sessions.
|
|
105
|
+
self._session.commit()
|
|
106
|
+
_require_known_agreement(self._session, scope)
|
|
107
|
+
await self._sync_excel(scope, stamp)
|
|
108
|
+
category = scope.get("category")
|
|
109
|
+
if category is None:
|
|
110
|
+
return AttributesListing(None, categories=scope_categories(self._session, scope))
|
|
111
|
+
await self._seed_pane(scope, category)
|
|
112
|
+
return AttributesListing(
|
|
113
|
+
category, attributes=applicable_attributes(self._session, category)
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
async def _sync_excel(self, scope: Mapping[str, str], stamp: datetime) -> None:
|
|
117
|
+
"""The query's Excel step: the department list with a department, else the agreement's.
|
|
118
|
+
|
|
119
|
+
Each is skipped without a request when its checkpoint already holds
|
|
120
|
+
``stamp``. A scope without an agreement has no Excel step: the export
|
|
121
|
+
is per agreement (the whole-catalogue export times out, endpoints.md),
|
|
122
|
+
so such a scope lists what the synced agreements hold.
|
|
123
|
+
"""
|
|
124
|
+
agreement_id = scope.get("agreement")
|
|
125
|
+
if agreement_id is None:
|
|
126
|
+
return
|
|
127
|
+
sync = SyncService(self._session_factory, self._payload_store, now=self._now)
|
|
128
|
+
department = scope.get("department")
|
|
129
|
+
if department is not None:
|
|
130
|
+
await sync.sync_department(agreement_id, department, stamp, self._client, HOME_URL)
|
|
131
|
+
else:
|
|
132
|
+
await sync.sync_agreement(agreement_id, stamp, self._client, HOME_URL)
|
|
133
|
+
|
|
134
|
+
async def _seed_pane(self, scope: Mapping[str, str], category: str) -> None:
|
|
135
|
+
"""One search request (page 1) over the scope; its filter pane seeds ``category``."""
|
|
136
|
+
form_scope = dict(scope)
|
|
137
|
+
if "agreement" in scope:
|
|
138
|
+
with self._session_factory() as session:
|
|
139
|
+
agreement = session.get(Agreement, scope["agreement"])
|
|
140
|
+
if agreement is None:
|
|
141
|
+
raise ValueError(f"Unknown agreement: {scope['agreement']}")
|
|
142
|
+
form_scope["agreement"] = agreement.filter_value
|
|
143
|
+
response = await post_search_response(
|
|
144
|
+
self._client,
|
|
145
|
+
SearchForm(scope=form_scope, pagination_page="1", pagination_left_most_page="1"),
|
|
146
|
+
)
|
|
147
|
+
pane = parse_filter_pane(response.text)
|
|
148
|
+
with self._session_factory.begin() as session:
|
|
149
|
+
seed_filter_pane(
|
|
150
|
+
session, pane, category, response.extensions["request_id"], self._now()
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _require_known_agreement(session: Session, scope: Mapping[str, str]) -> None:
|
|
155
|
+
"""Refuse a scope whose agreement the just-refreshed listing does not hold.
|
|
156
|
+
|
|
157
|
+
Runs after the stamp read, so the agreement table reflects the home page,
|
|
158
|
+
and before any Excel or search request: an unknown agreement is a caller
|
|
159
|
+
error, refused like any other semantic scope error.
|
|
160
|
+
"""
|
|
161
|
+
agreement_id = scope.get("agreement")
|
|
162
|
+
if agreement_id is not None and session.get(Agreement, agreement_id) is None:
|
|
163
|
+
raise ContractError(
|
|
164
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
165
|
+
"scope.agreement",
|
|
166
|
+
f"Unknown agreement: {agreement_id}",
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def applicable_attributes(session: Session, category: str) -> tuple[ApplicableAttribute, ...]:
|
|
171
|
+
"""The accepted attributes ``attribute_scope`` records for ``category``.
|
|
172
|
+
|
|
173
|
+
Each scoped attribute is listed as the accepted attribute its
|
|
174
|
+
``merged_into`` chain ends at, once, with the category's ``seed_value``
|
|
175
|
+
rows of every attribute that resolves to it. An attribute that resolves to
|
|
176
|
+
no accepted one (proposed, rejected, a broken merge) is left out, as the
|
|
177
|
+
contract validator refuses it.
|
|
178
|
+
"""
|
|
179
|
+
attributes = {
|
|
180
|
+
attribute.attribute_id: attribute for attribute in session.scalars(select(Attribute))
|
|
181
|
+
}
|
|
182
|
+
scoped_ids = session.scalars(
|
|
183
|
+
select(AttributeScope.attribute_id).where(AttributeScope.category == category)
|
|
184
|
+
).all()
|
|
185
|
+
roots: dict[str, Attribute] = {}
|
|
186
|
+
for attribute_id in scoped_ids:
|
|
187
|
+
root = _accepted_root(attribute_id, attributes)
|
|
188
|
+
if root is not None:
|
|
189
|
+
roots[root.attribute_id] = root
|
|
190
|
+
values: dict[str, set[str]] = {attribute_id: set() for attribute_id in roots}
|
|
191
|
+
for attribute_id, raw_value in session.execute(
|
|
192
|
+
select(SeedValue.attribute_id, SeedValue.raw_value).where(SeedValue.category == category)
|
|
193
|
+
):
|
|
194
|
+
root = _accepted_root(attribute_id, attributes)
|
|
195
|
+
if root is not None and root.attribute_id in values:
|
|
196
|
+
values[root.attribute_id].add(raw_value)
|
|
197
|
+
return tuple(
|
|
198
|
+
ApplicableAttribute(
|
|
199
|
+
attribute_id=root.attribute_id,
|
|
200
|
+
display_name=root.display_name,
|
|
201
|
+
kind=root.kind,
|
|
202
|
+
canonical_unit=root.canonical_unit,
|
|
203
|
+
values=tuple(sorted(values[root.attribute_id])),
|
|
204
|
+
)
|
|
205
|
+
for root in sorted(roots.values(), key=lambda attribute: attribute.attribute_id)
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def scope_categories(session: Session, scope: Mapping[str, str]) -> tuple[ScopeCategory, ...]:
|
|
210
|
+
"""The distinct categories of the scope's current members, from the Excel.
|
|
211
|
+
|
|
212
|
+
Membership is ``v_department_ficha`` when the scope has a department, else
|
|
213
|
+
``v_member_ficha``, as for queries.
|
|
214
|
+
"""
|
|
215
|
+
department = scope.get("department")
|
|
216
|
+
if department is not None:
|
|
217
|
+
membership = select(literal(1)).where(
|
|
218
|
+
_DEPARTMENT_FICHA.c.ficha_id == Ficha.ficha_id,
|
|
219
|
+
_DEPARTMENT_FICHA.c.department == department,
|
|
220
|
+
)
|
|
221
|
+
else:
|
|
222
|
+
membership = select(literal(1)).where(_MEMBER_FICHA.c.ficha_id == Ficha.ficha_id)
|
|
223
|
+
conditions: list[ColumnElement[bool]] = [membership.exists()]
|
|
224
|
+
for field, column in (("agreement", Ficha.agreement_id), ("catalogue", Ficha.catalogue)):
|
|
225
|
+
if field in scope:
|
|
226
|
+
conditions.append(column == scope[field])
|
|
227
|
+
rows = session.execute(
|
|
228
|
+
select(Ficha.catalogue, Ficha.category)
|
|
229
|
+
.where(*conditions)
|
|
230
|
+
.distinct()
|
|
231
|
+
.order_by(Ficha.catalogue, Ficha.category)
|
|
232
|
+
)
|
|
233
|
+
# A row without a category has none to narrow to.
|
|
234
|
+
return tuple(
|
|
235
|
+
ScopeCategory(catalogue, category) for catalogue, category in rows if category is not None
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _accepted_root(attribute_id: str, attributes: Mapping[str, Attribute]) -> Attribute | None:
|
|
240
|
+
"""The accepted attribute a ``merged_into`` chain ends at, if any."""
|
|
241
|
+
seen: set[str] = set()
|
|
242
|
+
attribute = attributes.get(attribute_id)
|
|
243
|
+
while attribute is not None and attribute.merged_into is not None:
|
|
244
|
+
if attribute.attribute_id in seen:
|
|
245
|
+
return None
|
|
246
|
+
seen.add(attribute.attribute_id)
|
|
247
|
+
attribute = attributes.get(attribute.merged_into)
|
|
248
|
+
if attribute is None or attribute.status != "accepted":
|
|
249
|
+
return None
|
|
250
|
+
return attribute
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Determine whether a push changed the project version."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
import tomllib
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def version_tag(previous_contents: str | None, current_contents: str) -> str | None:
|
|
11
|
+
"""Return the version tag if the project version changed."""
|
|
12
|
+
current_version = tomllib.loads(current_contents)["project"]["version"]
|
|
13
|
+
|
|
14
|
+
if not isinstance(current_version, str):
|
|
15
|
+
raise ValueError("Project versions must be strings.")
|
|
16
|
+
|
|
17
|
+
if re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", current_version) is None:
|
|
18
|
+
raise ValueError("Project version must use X.Y.Z format.")
|
|
19
|
+
|
|
20
|
+
if previous_contents is None:
|
|
21
|
+
return f"v{current_version}"
|
|
22
|
+
|
|
23
|
+
previous_version = tomllib.loads(previous_contents)["project"]["version"]
|
|
24
|
+
if not isinstance(previous_version, str):
|
|
25
|
+
raise ValueError("Project versions must be strings.")
|
|
26
|
+
|
|
27
|
+
if current_version == previous_version:
|
|
28
|
+
return None
|
|
29
|
+
|
|
30
|
+
return f"v{current_version}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def main() -> None:
|
|
34
|
+
"""Print the version tag for a push when its version changed."""
|
|
35
|
+
before = sys.argv[1]
|
|
36
|
+
if not before or set(before) == {"0"}:
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
commit_check = subprocess.run(
|
|
40
|
+
["git", "cat-file", "-e", f"{before}^{{commit}}"],
|
|
41
|
+
capture_output=True,
|
|
42
|
+
text=True,
|
|
43
|
+
)
|
|
44
|
+
if commit_check.returncode != 0:
|
|
45
|
+
sys.exit(
|
|
46
|
+
f"Previous commit {before} is unavailable (force-push?); "
|
|
47
|
+
"refusing to decide whether the version changed, so no tag is emitted."
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
show = subprocess.run(
|
|
51
|
+
["git", "show", f"{before}:pyproject.toml"],
|
|
52
|
+
capture_output=True,
|
|
53
|
+
text=True,
|
|
54
|
+
)
|
|
55
|
+
# The commit exists, so a failure here means it has no pyproject.toml.
|
|
56
|
+
previous_contents = show.stdout if show.returncode == 0 else None
|
|
57
|
+
|
|
58
|
+
current_contents = Path("pyproject.toml").read_text(encoding="utf-8")
|
|
59
|
+
tag = version_tag(previous_contents, current_contents)
|
|
60
|
+
if tag is not None:
|
|
61
|
+
print(tag)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
main()
|
piloto_ai_cli/backoff.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Exponential backoff shared by the work queues that retry failed items."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
|
|
7
|
+
# Bounds the doubling so the float never overflows; the cap then applies.
|
|
8
|
+
_MAX_BACKOFF_EXPONENT = 63
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_backoff(base: timedelta, cap: timedelta) -> None:
|
|
12
|
+
"""Fail fast on a backoff that could never wait or never grow to its cap."""
|
|
13
|
+
if base <= timedelta(0):
|
|
14
|
+
raise ValueError("retry_base must be positive")
|
|
15
|
+
if cap < base:
|
|
16
|
+
raise ValueError("retry_cap must not be less than retry_base")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def backoff(failures: int, base: timedelta, cap: timedelta) -> timedelta:
|
|
20
|
+
"""The wait after ``failures`` consecutive failures: ``base`` doubled each time, capped."""
|
|
21
|
+
if failures < 1:
|
|
22
|
+
raise ValueError("failures must be at least 1")
|
|
23
|
+
exponent = min(failures - 1, _MAX_BACKOFF_EXPONENT)
|
|
24
|
+
seconds = base.total_seconds() * 2.0**exponent
|
|
25
|
+
return timedelta(seconds=min(seconds, cap.total_seconds()))
|