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
piloto_ai_cli/pane.py ADDED
@@ -0,0 +1,303 @@
1
+ """Seed the attribute universe from a search response's filter pane.
2
+
3
+ The pane is the site's own taxonomy (proposal-v2.md §5, "Seeds"): each
4
+ attribute label it lists becomes an accepted ``attribute`` with its value
5
+ vocabulary (``seed_value``), the category it applies to (``attribute_scope``,
6
+ origin ``pane``) and an accepted ``alias`` from the label, so the rules pass
7
+ can resolve card and description labels to it. A pane only says which category
8
+ its values belong to when the search scope is exactly one category; callers
9
+ seed only then (data-model.md §4, the Cards row).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ from datetime import datetime
16
+ from typing import Any, cast
17
+ from uuid import uuid4
18
+
19
+ from sqlalchemy import CursorResult, Table, select, update
20
+ from sqlalchemy.orm import Session
21
+
22
+ from piloto_ai_cli.database import upsert
23
+ from piloto_ai_cli.parsers import FilterPane
24
+ from piloto_ai_cli.schema.models import Alias, Attribute, AttributeScope, SeedValue
25
+
26
+ _LOGGER = logging.getLogger(__name__)
27
+
28
+
29
+ def seed_filter_pane(
30
+ session: Session,
31
+ pane: FilterPane,
32
+ category: str,
33
+ request_id: str,
34
+ now: datetime,
35
+ ) -> None:
36
+ """Write one category's pane attributes, values, scope and aliases.
37
+
38
+ - A label that already has an accepted alias to another attribute is
39
+ resolved through it (the alias table is the canonical label →
40
+ attribute mapping): the existing-attribute rules below apply to that
41
+ attribute, no attribute is created for the label and the alias is left
42
+ as it is.
43
+ - A label with no attribute of its own whose alias to another attribute
44
+ is still ``proposed`` is skipped (nothing is written for it) until that
45
+ alias is reviewed.
46
+ - Each attribute is decided once per call, however many labels reach it.
47
+ A new attribute that another writer committed after the read is
48
+ decided by the same existing-attribute rules.
49
+ - Any other new label becomes an attribute whose id is the normalized label, with
50
+ the site's own label as display name, kind ``categoric`` and no canonical
51
+ unit, ``seeded_from_pane`` and status ``accepted``.
52
+ - An existing attribute row is never changed, except that a ``proposed``
53
+ one is accepted: the pane is ground truth for the attributes it lists.
54
+ - A rejected attribute keeps its values and scope under its own id. A
55
+ merged one has them written under the accepted attribute it was merged
56
+ into, where the merge sends its values; a merge that ends nowhere live
57
+ is treated like a rejected attribute.
58
+ - An accepted alias (normalized label → attribute) is written for every
59
+ label whose attribute can receive values, unless the label already has
60
+ an alias; a ``proposed`` alias to the same attribute is accepted.
61
+ - ``seed_value`` rows only move ``last_request_id`` forward on re-seeding;
62
+ ``attribute_scope`` rows are positive-only and keep their first sighting.
63
+ """
64
+ labels: dict[str, str] = {}
65
+ values: dict[str, dict[str, None]] = {}
66
+ for attribute in pane.attributes:
67
+ labels.setdefault(attribute.label, attribute.raw_label.strip())
68
+ values.setdefault(attribute.label, {})[attribute.value] = None
69
+ if not labels:
70
+ return
71
+
72
+ attributes = {
73
+ attribute.attribute_id: attribute for attribute in session.scalars(select(Attribute)).all()
74
+ }
75
+ label_aliases = {
76
+ alias.raw_label: alias
77
+ for alias in session.scalars(select(Alias).where(Alias.raw_label.in_(list(labels)))).all()
78
+ }
79
+ # Each attribute is decided once per call: a second label reaching the same
80
+ # attribute reuses the outcome instead of repeating the compare-and-set.
81
+ decided: dict[str, tuple[str, bool]] = {}
82
+
83
+ def existing_target(attribute: Attribute) -> tuple[str, bool]:
84
+ if attribute.attribute_id not in decided:
85
+ decided[attribute.attribute_id] = _existing_target(session, attribute, attributes, now)
86
+ return decided[attribute.attribute_id]
87
+
88
+ new_attributes: list[dict[str, object]] = []
89
+ targets: dict[str, str] = {} # label -> attribute id its seeds are written under
90
+ alias_targets: dict[str, str] = {} # label -> attribute id its alias points at
91
+ for label, display_name in labels.items():
92
+ alias = label_aliases.get(label)
93
+ aliased = alias.attribute_id if alias is not None else None
94
+ if (
95
+ alias is not None
96
+ and alias.status == "accepted"
97
+ and aliased != label
98
+ and aliased in attributes
99
+ ):
100
+ # The label already resolves to an attribute through its accepted
101
+ # alias: the existing-attribute rules apply to that attribute, no
102
+ # attribute is created for the label and the alias is kept.
103
+ targets[label], _ = existing_target(attributes[aliased])
104
+ continue
105
+ existing = attributes.get(label)
106
+ if existing is None and alias is not None and alias.status == "proposed":
107
+ # The label's alias to another attribute awaits review: the pane
108
+ # writes nothing for it, so it neither pre-empts that decision nor
109
+ # creates a duplicate of the alias target. The next one-category
110
+ # sync after the review seeds it through the accepted alias, or
111
+ # through a new attribute if the alias was rejected.
112
+ _LOGGER.info(
113
+ "pane label %r not seeded: its alias to %r is still proposed", label, aliased
114
+ )
115
+ continue
116
+ if existing is None:
117
+ new_attributes.append(
118
+ {
119
+ "attribute_id": label,
120
+ "display_name": display_name,
121
+ "kind": "categoric",
122
+ "canonical_unit": None,
123
+ "seeded_from_pane": True,
124
+ "status": "accepted",
125
+ "proposed_by": None,
126
+ "accepted_at": now,
127
+ "created_at": now,
128
+ }
129
+ )
130
+ targets[label] = alias_targets[label] = label
131
+ continue
132
+ target, receives_alias = existing_target(existing)
133
+ targets[label] = target
134
+ if receives_alias:
135
+ alias_targets[label] = target
136
+
137
+ # Parents first: every row below references an attribute written or read here.
138
+ upsert(session, Attribute, new_attributes, insert_only=True)
139
+ if new_attributes:
140
+ _recheck_new_attributes(session, new_attributes, attributes, targets, alias_targets, now)
141
+ upsert(
142
+ session,
143
+ SeedValue,
144
+ [
145
+ {
146
+ "attribute_id": targets[label],
147
+ "category": category,
148
+ "raw_value": raw_value,
149
+ "last_request_id": request_id,
150
+ }
151
+ for label, label_values in values.items()
152
+ if label in targets
153
+ for raw_value in label_values
154
+ ],
155
+ )
156
+ upsert(
157
+ session,
158
+ AttributeScope,
159
+ [
160
+ {
161
+ "attribute_id": attribute_id,
162
+ "category": category,
163
+ "origin": "pane",
164
+ "extraction_id": None,
165
+ "request_id": request_id,
166
+ "first_seen_at": now,
167
+ }
168
+ for attribute_id in dict.fromkeys(targets.values())
169
+ ],
170
+ )
171
+ _seed_aliases(session, alias_targets, now)
172
+
173
+
174
+ def _recheck_new_attributes(
175
+ session: Session,
176
+ new_attributes: list[dict[str, object]],
177
+ attributes: dict[str, Attribute],
178
+ targets: dict[str, str],
179
+ alias_targets: dict[str, str],
180
+ now: datetime,
181
+ ) -> None:
182
+ """Apply the existing-attribute rules to new ids another writer created first.
183
+
184
+ The insert-only write keeps a row another writer committed after the read
185
+ (an LLM pass proposing the same attribute, say), so that row decides
186
+ where the label's seeds go and whether its alias may point there, exactly
187
+ as if it had been there before the read.
188
+ """
189
+ session.flush()
190
+ ids = [str(row["attribute_id"]) for row in new_attributes]
191
+ for attribute in session.scalars(select(Attribute).where(Attribute.attribute_id.in_(ids))):
192
+ attributes[attribute.attribute_id] = attribute
193
+ for attribute_id in ids:
194
+ attribute = attributes[attribute_id]
195
+ if attribute.status == "accepted" and attribute.merged_into is None:
196
+ continue # Ours, or an accepted one: the label's plan stands.
197
+ target, receives_alias = _existing_target(session, attribute, attributes, now)
198
+ for label, label_target in list(targets.items()):
199
+ if label_target != attribute_id:
200
+ continue
201
+ targets[label] = target
202
+ if receives_alias:
203
+ alias_targets[label] = target
204
+ else:
205
+ alias_targets.pop(label, None)
206
+
207
+
208
+ def _seed_aliases(session: Session, alias_targets: dict[str, str], now: datetime) -> None:
209
+ if not alias_targets:
210
+ return
211
+ existing = {
212
+ alias.raw_label: alias
213
+ for alias in session.scalars(
214
+ select(Alias).where(Alias.raw_label.in_(list(alias_targets)))
215
+ ).all()
216
+ }
217
+ new_aliases: list[dict[str, object]] = []
218
+ for label, attribute_id in alias_targets.items():
219
+ alias = existing.get(label)
220
+ if alias is None:
221
+ new_aliases.append(
222
+ {
223
+ "alias_id": str(uuid4()),
224
+ "raw_label": label,
225
+ "attribute_id": attribute_id,
226
+ "status": "accepted",
227
+ "proposed_by": None,
228
+ "accepted_at": now,
229
+ }
230
+ )
231
+ elif alias.attribute_id == attribute_id and alias.status == "proposed":
232
+ _accept_proposed(session, Alias, Alias.alias_id == alias.alias_id, now)
233
+ elif alias.attribute_id != attribute_id or alias.status != "accepted":
234
+ # The label already holds an alias (a label maps to one attribute)
235
+ # with a review decision of its own: it is left as it is.
236
+ _LOGGER.info(
237
+ "pane label %r keeps its %s alias to %r instead of %r",
238
+ label,
239
+ alias.status,
240
+ alias.attribute_id,
241
+ attribute_id,
242
+ )
243
+ upsert(session, Alias, new_aliases, insert_only=True)
244
+
245
+
246
+ def _existing_target(
247
+ session: Session, attribute: Attribute, attributes: dict[str, Attribute], now: datetime
248
+ ) -> tuple[str, bool]:
249
+ """Where an existing attribute's pane seeds go, and whether a label alias may point there.
250
+
251
+ The attribute row is never changed, except that a ``proposed`` one is
252
+ accepted (the pane is ground truth). A rejected attribute, or a merge that
253
+ ends nowhere live, keeps the seeds under its own id but receives no alias.
254
+ """
255
+ if attribute.merged_into is not None:
256
+ root = _live_root(attribute, attributes)
257
+ return (root, True) if root is not None else (attribute.attribute_id, False)
258
+ if attribute.status == "rejected":
259
+ return attribute.attribute_id, False
260
+ if attribute.status == "proposed":
261
+ # A concurrent review decision wins: the alias waits for an attribute
262
+ # that can receive values.
263
+ accepted = _accept_proposed(
264
+ session, Attribute, Attribute.attribute_id == attribute.attribute_id, now
265
+ )
266
+ return attribute.attribute_id, accepted
267
+ return attribute.attribute_id, True
268
+
269
+
270
+ def _live_root(attribute: Attribute, attributes: dict[str, Attribute]) -> str | None:
271
+ """The accepted, unmerged attribute a merge chain ends at, if any."""
272
+ current = attribute
273
+ seen = {attribute.attribute_id}
274
+ while current.merged_into is not None:
275
+ if current.merged_into in seen:
276
+ return None
277
+ seen.add(current.merged_into)
278
+ target = attributes.get(current.merged_into)
279
+ if target is None:
280
+ return None
281
+ current = target
282
+ return current.attribute_id if current.status == "accepted" else None
283
+
284
+
285
+ def _accept_proposed(
286
+ session: Session, model: type[Attribute] | type[Alias], key: Any, now: datetime
287
+ ) -> bool:
288
+ """Accept one proposed row, only if it is still proposed (compare-and-set)."""
289
+ table = cast(Table, model.__table__)
290
+ conditions = [key, table.c.status == "proposed"]
291
+ if model is Attribute:
292
+ conditions.append(table.c.merged_into.is_(None))
293
+ session.flush()
294
+ result = cast(
295
+ CursorResult[Any],
296
+ session.execute(
297
+ update(table)
298
+ .where(*conditions)
299
+ .values(status="accepted", accepted_at=now)
300
+ .execution_options(synchronize_session=False)
301
+ ),
302
+ )
303
+ return result.rowcount == 1