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/api.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"""The library API: the typed Python surface the frontend agent imports.
|
|
2
|
+
|
|
3
|
+
proposal-v2.md §2-3: the frontend agent calls the CLI with a predicate
|
|
4
|
+
document and gets the result envelope back. These functions are that call
|
|
5
|
+
without the command line: :func:`query` (and :func:`query_saved`),
|
|
6
|
+
:func:`attributes` and :func:`save` run exactly what ``pc query``, ``pc
|
|
7
|
+
attributes`` and ``pc save`` run (data-model.md §3-4), each in its own
|
|
8
|
+
``run_log`` run, and return typed results instead of printing them. The
|
|
9
|
+
commands are thin wrappers over this module.
|
|
10
|
+
|
|
11
|
+
Inputs are JSON values as Python objects (what ``json.loads`` returns). A
|
|
12
|
+
refusal is raised as :class:`~piloto_ai_cli.errors.ContractError`, after its
|
|
13
|
+
run is closed ``refused``. Configuration comes from ``settings``, or from the
|
|
14
|
+
environment when it is omitted (``Settings()``).
|
|
15
|
+
|
|
16
|
+
The functions are synchronous: each runs its own event loop for its requests,
|
|
17
|
+
so call them from a worker thread (``asyncio.to_thread``) inside async code.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
import json
|
|
22
|
+
import reprlib
|
|
23
|
+
from collections.abc import Callable, Mapping
|
|
24
|
+
from datetime import UTC, datetime
|
|
25
|
+
from enum import Enum
|
|
26
|
+
from typing import Any, Final, cast
|
|
27
|
+
from uuid import uuid4
|
|
28
|
+
|
|
29
|
+
from piloto_ai_cli.attributes_service import AttributesListing, AttributesService
|
|
30
|
+
from piloto_ai_cli.database import (
|
|
31
|
+
make_session_factory,
|
|
32
|
+
run_slot,
|
|
33
|
+
shared_engine,
|
|
34
|
+
sync_extraction_config,
|
|
35
|
+
upsert,
|
|
36
|
+
)
|
|
37
|
+
from piloto_ai_cli.errors import ContractError, ContractErrorCode
|
|
38
|
+
from piloto_ai_cli.http_client import HttpClient
|
|
39
|
+
from piloto_ai_cli.llm_client import LLMClient
|
|
40
|
+
from piloto_ai_cli.payload_store import make_payload_store
|
|
41
|
+
from piloto_ai_cli.query_result import QueryResult
|
|
42
|
+
from piloto_ai_cli.query_service import (
|
|
43
|
+
QueryService,
|
|
44
|
+
canonical_saved_id,
|
|
45
|
+
effective_max_items,
|
|
46
|
+
load_saved_document,
|
|
47
|
+
)
|
|
48
|
+
from piloto_ai_cli.reextract import validate_scope
|
|
49
|
+
from piloto_ai_cli.run_log import RunLog
|
|
50
|
+
from piloto_ai_cli.schema import ContractValidator, ValidatedContract
|
|
51
|
+
from piloto_ai_cli.schema.models import SavedQuery
|
|
52
|
+
from piloto_ai_cli.settings import Settings
|
|
53
|
+
from piloto_ai_cli.sync import require_agreement
|
|
54
|
+
|
|
55
|
+
DocumentReader = Callable[[], object]
|
|
56
|
+
"""Returns the JSON document a command runs on, or raises a ``ContractError``."""
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def query(
|
|
60
|
+
document: object,
|
|
61
|
+
*,
|
|
62
|
+
settings: Settings | None = None,
|
|
63
|
+
max_items: int | None = None,
|
|
64
|
+
) -> QueryResult:
|
|
65
|
+
"""Validate a predicate document, sync what it needs, run it and return the envelope.
|
|
66
|
+
|
|
67
|
+
``max_items`` caps the fichas enriched by this call; it wins over the
|
|
68
|
+
document's own ``max_items``, which wins over ``settings.max_items``.
|
|
69
|
+
"""
|
|
70
|
+
_check_max_items(max_items)
|
|
71
|
+
arguments = {"document": _argument_text(document), "max_items": max_items}
|
|
72
|
+
result, _ = execute_query(
|
|
73
|
+
settings or Settings(),
|
|
74
|
+
arguments,
|
|
75
|
+
document=lambda: _json_document(document, "contract"),
|
|
76
|
+
max_items=max_items,
|
|
77
|
+
)
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def query_saved(
|
|
82
|
+
query_id: str,
|
|
83
|
+
*,
|
|
84
|
+
settings: Settings | None = None,
|
|
85
|
+
max_items: int | None = None,
|
|
86
|
+
) -> QueryResult:
|
|
87
|
+
"""Run the predicate document saved under ``query_id`` (see :func:`save`), as :func:`query`.
|
|
88
|
+
|
|
89
|
+
The ``query_run`` records the id. An id that is not a UUID, or that no
|
|
90
|
+
saved query holds, is refused on ``saved``, as is an id that is not a string.
|
|
91
|
+
"""
|
|
92
|
+
_check_max_items(max_items)
|
|
93
|
+
recorded_id = query_id if isinstance(query_id, str) else _safe_repr(query_id)
|
|
94
|
+
result, _ = execute_query(
|
|
95
|
+
settings or Settings(),
|
|
96
|
+
{"saved": recorded_id, "max_items": max_items},
|
|
97
|
+
saved=query_id,
|
|
98
|
+
max_items=max_items,
|
|
99
|
+
function="query_saved",
|
|
100
|
+
)
|
|
101
|
+
return result
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def attributes(scope: object, *, settings: Settings | None = None) -> AttributesListing:
|
|
105
|
+
"""List a one-category scope's attributes, or a wider scope's categories."""
|
|
106
|
+
return execute_attributes(
|
|
107
|
+
settings or Settings(),
|
|
108
|
+
{"scope": _argument_text(scope)},
|
|
109
|
+
lambda: _json_document(scope, "scope"),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def save(document: object, *, settings: Settings | None = None) -> str:
|
|
114
|
+
"""Validate a predicate document, store it as a saved query and return its id."""
|
|
115
|
+
return execute_save(
|
|
116
|
+
settings or Settings(),
|
|
117
|
+
{"document": _argument_text(document)},
|
|
118
|
+
lambda: _json_document(document, "contract"),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class _NotGiven(Enum):
|
|
123
|
+
"""Type of :data:`NOT_GIVEN` (a one-member enum is the typed sentinel idiom)."""
|
|
124
|
+
|
|
125
|
+
TOKEN = "not given"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
NOT_GIVEN: Final = _NotGiven.TOKEN
|
|
129
|
+
"""``saved`` was not given to :func:`execute_query`. ``None`` cannot mark this,
|
|
130
|
+
since a library caller's ``None`` id must be refused inside its run."""
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def execute_query(
|
|
134
|
+
settings: Settings,
|
|
135
|
+
arguments: Mapping[str, object],
|
|
136
|
+
*,
|
|
137
|
+
document: DocumentReader | None = None,
|
|
138
|
+
saved: object = NOT_GIVEN,
|
|
139
|
+
max_items: int | None = None,
|
|
140
|
+
function: str = "query",
|
|
141
|
+
) -> tuple[QueryResult, ValidatedContract]:
|
|
142
|
+
"""Run ``pc query`` on the document ``document`` reads, or on the saved query ``saved``.
|
|
143
|
+
|
|
144
|
+
The shared implementation of :func:`query`, :func:`query_saved` and the
|
|
145
|
+
command, which records its own ``arguments`` and reads its argument inside
|
|
146
|
+
the run, so an unreadable document closes the run ``refused``. Exactly
|
|
147
|
+
one of ``document`` and ``saved`` is given; ``saved`` may be any object,
|
|
148
|
+
and one that is not a UUID string is refused on ``saved`` inside the run.
|
|
149
|
+
``function`` names the public function called, for the error raised inside
|
|
150
|
+
a running event loop. Returns the envelope and the validated contract it
|
|
151
|
+
answers.
|
|
152
|
+
|
|
153
|
+
Every ``execute_*`` function uses the process-wide engine from
|
|
154
|
+
:func:`shared_engine` and leaves it open, so repeated library calls reuse
|
|
155
|
+
its pooled connections; the ``pc`` commands dispose it when they finish.
|
|
156
|
+
"""
|
|
157
|
+
if (document is None) == (saved is NOT_GIVEN):
|
|
158
|
+
raise ValueError("Give exactly one of document and saved")
|
|
159
|
+
_require_no_running_loop(function)
|
|
160
|
+
engine = shared_engine(settings)
|
|
161
|
+
session_factory = make_session_factory(engine)
|
|
162
|
+
with run_slot(), session_factory() as session:
|
|
163
|
+
with RunLog.open(session, "query", arguments) as run:
|
|
164
|
+
# Step 2: a refusal closes the run ``refused`` before any request.
|
|
165
|
+
saved_id = canonical_saved_id(saved) if saved is not NOT_GIVEN else None
|
|
166
|
+
predicate_document: object = (
|
|
167
|
+
load_saved_document(session, saved_id)
|
|
168
|
+
if saved_id is not None
|
|
169
|
+
else cast(DocumentReader, document)()
|
|
170
|
+
)
|
|
171
|
+
contract = ContractValidator(session).validate(predicate_document)
|
|
172
|
+
# A scope without an agreement is refused here, before the
|
|
173
|
+
# extraction_config write below: a refusal writes nothing.
|
|
174
|
+
require_agreement(contract)
|
|
175
|
+
effective = effective_max_items(max_items, contract, settings)
|
|
176
|
+
# Enrichment's LLM pass runs under the configured model and
|
|
177
|
+
# prompt. Committed now: the requests below log in sessions of
|
|
178
|
+
# their own, which must neither wait on nor miss it.
|
|
179
|
+
sync_extraction_config(session, settings)
|
|
180
|
+
session.commit()
|
|
181
|
+
with engine.connect() as connection:
|
|
182
|
+
payload_store = make_payload_store(settings, connection)
|
|
183
|
+
|
|
184
|
+
async def run_service() -> QueryResult:
|
|
185
|
+
async with HttpClient(
|
|
186
|
+
settings,
|
|
187
|
+
session_factory=session_factory,
|
|
188
|
+
payload_store=payload_store,
|
|
189
|
+
run_id=run.run_id,
|
|
190
|
+
) as client:
|
|
191
|
+
# Without a real provider (the ci-mock profile), a
|
|
192
|
+
# ficha whose needed attribute is left to the LLM
|
|
193
|
+
# fails the run instead of being skipped silently.
|
|
194
|
+
llm_client = (
|
|
195
|
+
LLMClient(settings, client) if settings.llm_provider != "mock" else None
|
|
196
|
+
)
|
|
197
|
+
try:
|
|
198
|
+
service = QueryService(
|
|
199
|
+
session,
|
|
200
|
+
session_factory,
|
|
201
|
+
client,
|
|
202
|
+
payload_store,
|
|
203
|
+
settings,
|
|
204
|
+
llm_client=llm_client,
|
|
205
|
+
)
|
|
206
|
+
return await service.run(
|
|
207
|
+
contract,
|
|
208
|
+
cast(dict[str, Any], predicate_document),
|
|
209
|
+
run_id=run.run_id,
|
|
210
|
+
max_items=effective,
|
|
211
|
+
query_id=saved_id,
|
|
212
|
+
)
|
|
213
|
+
finally:
|
|
214
|
+
if llm_client is not None:
|
|
215
|
+
await llm_client.aclose()
|
|
216
|
+
|
|
217
|
+
result = asyncio.run(run_service())
|
|
218
|
+
return result, contract
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def execute_attributes(
|
|
222
|
+
settings: Settings, arguments: Mapping[str, object], scope: DocumentReader
|
|
223
|
+
) -> AttributesListing:
|
|
224
|
+
"""Run ``pc attributes`` on the scope ``scope`` reads; shared by :func:`attributes`."""
|
|
225
|
+
_require_no_running_loop("attributes")
|
|
226
|
+
engine = shared_engine(settings)
|
|
227
|
+
session_factory = make_session_factory(engine)
|
|
228
|
+
with run_slot(), session_factory() as session:
|
|
229
|
+
with RunLog.open(session, "attributes", arguments) as run:
|
|
230
|
+
validated_scope = validate_scope(scope())
|
|
231
|
+
with engine.connect() as connection:
|
|
232
|
+
payload_store = make_payload_store(settings, connection)
|
|
233
|
+
|
|
234
|
+
async def list_scope() -> AttributesListing:
|
|
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
|
+
service = AttributesService(session, session_factory, client, payload_store)
|
|
242
|
+
return await service.run(validated_scope)
|
|
243
|
+
|
|
244
|
+
listing = asyncio.run(list_scope())
|
|
245
|
+
return listing
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def execute_save(
|
|
249
|
+
settings: Settings, arguments: Mapping[str, object], document: DocumentReader
|
|
250
|
+
) -> str:
|
|
251
|
+
"""Run ``pc save`` on the document ``document`` reads; shared by :func:`save`."""
|
|
252
|
+
engine = shared_engine(settings)
|
|
253
|
+
with run_slot(), make_session_factory(engine)() as session:
|
|
254
|
+
with RunLog.open(session, "save", arguments):
|
|
255
|
+
predicate_document = document()
|
|
256
|
+
validated = ContractValidator(session).validate(predicate_document)
|
|
257
|
+
query_id = str(uuid4())
|
|
258
|
+
upsert(
|
|
259
|
+
session,
|
|
260
|
+
SavedQuery,
|
|
261
|
+
[
|
|
262
|
+
{
|
|
263
|
+
"query_id": query_id,
|
|
264
|
+
"contract_version": validated.contract_version,
|
|
265
|
+
"document": cast(dict[str, Any], predicate_document),
|
|
266
|
+
"created_at": datetime.now(UTC),
|
|
267
|
+
}
|
|
268
|
+
],
|
|
269
|
+
)
|
|
270
|
+
return query_id
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _require_no_running_loop(function: str) -> None:
|
|
274
|
+
"""Refuse a call made from a running event loop before any side effect.
|
|
275
|
+
|
|
276
|
+
The query and attributes steps run their own event loop with
|
|
277
|
+
:func:`asyncio.run`, which cannot start inside another one. Checking first
|
|
278
|
+
keeps such a call from opening a run or writing anything.
|
|
279
|
+
"""
|
|
280
|
+
try:
|
|
281
|
+
asyncio.get_running_loop()
|
|
282
|
+
except RuntimeError:
|
|
283
|
+
return
|
|
284
|
+
raise RuntimeError(
|
|
285
|
+
f"piloto_ai_cli.{function}() cannot be called from a running event loop; "
|
|
286
|
+
f"call it from async code with asyncio.to_thread(piloto_ai_cli.{function}, ...)"
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
MAX_DOCUMENT_DEPTH = 64
|
|
291
|
+
"""Deepest nesting of objects and arrays a library document may have.
|
|
292
|
+
|
|
293
|
+
A contract document is a few levels deep. Bounding the depth (OWASP: limit
|
|
294
|
+
JSON nesting) keeps a hostile or broken document from exhausting the
|
|
295
|
+
recursion limit in the encoder or the schema validator; it is refused as a
|
|
296
|
+
``schema_violation`` instead.
|
|
297
|
+
"""
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _reject_non_string_keys(value: object, location: str) -> None:
|
|
301
|
+
"""Refuse any object key that is not a string, and nesting deeper than the limit.
|
|
302
|
+
|
|
303
|
+
``json.dumps`` would turn such keys into strings and could merge distinct
|
|
304
|
+
keys (``1`` and ``"1"``) into one, so the run would see another document.
|
|
305
|
+
The walk is iterative, so it cannot exhaust the recursion limit itself. A
|
|
306
|
+
circular reference is nested without end, so it is refused by the depth
|
|
307
|
+
limit too.
|
|
308
|
+
"""
|
|
309
|
+
pending: list[tuple[object, int]] = [(value, 1)]
|
|
310
|
+
while pending:
|
|
311
|
+
item, depth = pending.pop()
|
|
312
|
+
if not isinstance(item, Mapping | list | tuple):
|
|
313
|
+
continue
|
|
314
|
+
if depth > MAX_DOCUMENT_DEPTH:
|
|
315
|
+
raise ContractError(
|
|
316
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
317
|
+
location,
|
|
318
|
+
"Invalid JSON document: nested deeper than "
|
|
319
|
+
f"{MAX_DOCUMENT_DEPTH} levels (or a circular reference)",
|
|
320
|
+
)
|
|
321
|
+
if isinstance(item, Mapping):
|
|
322
|
+
for key, child in item.items():
|
|
323
|
+
if not isinstance(key, str):
|
|
324
|
+
raise ContractError(
|
|
325
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
326
|
+
location,
|
|
327
|
+
f"Invalid JSON document: object key {key!r} is not a string",
|
|
328
|
+
)
|
|
329
|
+
pending.append((child, depth + 1))
|
|
330
|
+
else:
|
|
331
|
+
pending.extend((child, depth + 1) for child in item)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _check_max_items(max_items: int | None) -> None:
|
|
335
|
+
"""Refuse a ``max_items`` the command line's ``--max-items`` (``min=1``) would refuse."""
|
|
336
|
+
if max_items is not None and (
|
|
337
|
+
not isinstance(max_items, int) or isinstance(max_items, bool) or max_items < 1
|
|
338
|
+
):
|
|
339
|
+
raise ValueError(f"max_items must be a positive integer, not {max_items!r}")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _argument_text(value: object) -> str:
|
|
343
|
+
"""``value`` as the run log records it: its JSON text, like an inline command argument.
|
|
344
|
+
|
|
345
|
+
Recording never raises, so every refusal reaches the run and is logged. A
|
|
346
|
+
value that is not JSON (it is refused inside the run) is recorded by
|
|
347
|
+
:func:`_safe_repr` instead. A value the document check refuses (non-string
|
|
348
|
+
keys, nesting deeper than ``MAX_DOCUMENT_DEPTH``, a circular reference) is
|
|
349
|
+
not serialized at all, since the encoder could exhaust the recursion limit
|
|
350
|
+
on it: it is recorded by :func:`_safe_repr` too.
|
|
351
|
+
"""
|
|
352
|
+
try:
|
|
353
|
+
_reject_non_string_keys(value, "document")
|
|
354
|
+
except ContractError:
|
|
355
|
+
return _safe_repr(value)
|
|
356
|
+
try:
|
|
357
|
+
return json.dumps(value, ensure_ascii=False)
|
|
358
|
+
except TypeError, ValueError:
|
|
359
|
+
return _safe_repr(value)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _safe_repr(value: object) -> str:
|
|
363
|
+
"""A bounded ``repr`` of ``value`` that never raises.
|
|
364
|
+
|
|
365
|
+
:func:`reprlib.repr` limits depth and size and replaces values whose own
|
|
366
|
+
``repr`` fails (an int over the digit limit, a raising ``__repr__``) by a
|
|
367
|
+
placeholder; anything it still cannot render is recorded by its type name.
|
|
368
|
+
"""
|
|
369
|
+
try:
|
|
370
|
+
return reprlib.repr(value)
|
|
371
|
+
except Exception: # recording a refused argument must never fail the refusal
|
|
372
|
+
return f"<unrepresentable {type(value).__qualname__}>"
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _json_document(value: object, location: str) -> object:
|
|
376
|
+
"""Return a JSON copy of ``value``, or refuse it as the command refuses unreadable JSON.
|
|
377
|
+
|
|
378
|
+
The round trip refuses what JSON cannot hold (``NaN``, the infinities,
|
|
379
|
+
objects such as ``Decimal`` or ``datetime``), as ``pc`` refuses them in its
|
|
380
|
+
argument, and turns tuples into lists. Object keys that are not strings are
|
|
381
|
+
refused first, since the round trip would silently convert them, and so is
|
|
382
|
+
nesting deeper than ``MAX_DOCUMENT_DEPTH`` (which includes a circular
|
|
383
|
+
reference). The copy also keeps the run
|
|
384
|
+
independent of later changes the caller makes to ``value``.
|
|
385
|
+
"""
|
|
386
|
+
_reject_non_string_keys(value, location)
|
|
387
|
+
try:
|
|
388
|
+
return json.loads(json.dumps(value, allow_nan=False))
|
|
389
|
+
except (TypeError, ValueError) as error:
|
|
390
|
+
raise ContractError(
|
|
391
|
+
ContractErrorCode.SCHEMA_VIOLATION,
|
|
392
|
+
location,
|
|
393
|
+
f"Invalid JSON document: {error}",
|
|
394
|
+
) from None
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Helpers for extracting raw attribute labels and values from text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
|
|
8
|
+
_DESCRIPTION_LABELS = (
|
|
9
|
+
"TIPO",
|
|
10
|
+
"GRADO DE CALIDAD",
|
|
11
|
+
"LONGITUD DEL GRANO",
|
|
12
|
+
"CONT.NETO",
|
|
13
|
+
"MARCA",
|
|
14
|
+
"UNIDAD DE DESPACHO",
|
|
15
|
+
"ENV.PRIMARIO",
|
|
16
|
+
"GARANTÍA",
|
|
17
|
+
"CUMPLE REQ. DE CALIDAD",
|
|
18
|
+
"CUMPLE REQ. DE INOCUIDAD",
|
|
19
|
+
"COD.IDENT",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
_CATEGORY_PREFIX = re.compile(r"^\s*[^:\s][^:]*\s:\s*$")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def split_key_value_text(text: str, known_labels: Iterable[str] = ()) -> list[tuple[str, str]]:
|
|
27
|
+
"""Split key-value lines, using known labels to find inline attribute boundaries.
|
|
28
|
+
|
|
29
|
+
Within a line, a known label followed by ``:`` starts a new pair, and the
|
|
30
|
+
value of the previous pair ends there. The text before the first known
|
|
31
|
+
label is handled so no label is truncated:
|
|
32
|
+
|
|
33
|
+
- a category prefix (``FRIJOL :``, words then a space before the colon and
|
|
34
|
+
nothing else) is dropped;
|
|
35
|
+
- text without a colon is the start of the first label
|
|
36
|
+
(``NOMBRE DE MARCA: ACME`` keeps ``NOMBRE DE MARCA``);
|
|
37
|
+
- text with a colon is its own pair, split at its first colon.
|
|
38
|
+
|
|
39
|
+
A raw label that ends with a known label and appears after another pair on
|
|
40
|
+
the same line cannot be told apart from the previous value; pass it in
|
|
41
|
+
``known_labels`` (longer labels win). Lines without a known label are split
|
|
42
|
+
at their first colon only, so unknown labels keep their full text and values
|
|
43
|
+
keep any further colons.
|
|
44
|
+
"""
|
|
45
|
+
labels = sorted(
|
|
46
|
+
{label.strip() for label in (*_DESCRIPTION_LABELS, *known_labels) if label.strip()},
|
|
47
|
+
key=len,
|
|
48
|
+
reverse=True,
|
|
49
|
+
)
|
|
50
|
+
label_pattern = re.compile(
|
|
51
|
+
rf"(?<!\S)(?P<label>{'|'.join(_label_regex(label) for label in labels)})\s*:",
|
|
52
|
+
re.IGNORECASE,
|
|
53
|
+
)
|
|
54
|
+
pairs: list[tuple[str, str]] = []
|
|
55
|
+
|
|
56
|
+
for line in text.splitlines():
|
|
57
|
+
matches = list(label_pattern.finditer(line))
|
|
58
|
+
if not matches:
|
|
59
|
+
_append_pair(pairs, *_split_first_colon(line))
|
|
60
|
+
continue
|
|
61
|
+
|
|
62
|
+
first_label = matches[0]["label"]
|
|
63
|
+
prefix = line[: matches[0].start()]
|
|
64
|
+
if prefix.strip() and not _CATEGORY_PREFIX.match(prefix):
|
|
65
|
+
if ":" in prefix:
|
|
66
|
+
_append_pair(pairs, *_split_first_colon(prefix))
|
|
67
|
+
else:
|
|
68
|
+
first_label = prefix + first_label
|
|
69
|
+
|
|
70
|
+
for index, match in enumerate(matches):
|
|
71
|
+
end = matches[index + 1].start() if index + 1 < len(matches) else len(line)
|
|
72
|
+
label = first_label if index == 0 else match["label"]
|
|
73
|
+
_append_pair(pairs, label, line[match.end() : end])
|
|
74
|
+
|
|
75
|
+
return pairs
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _label_regex(label: str) -> str:
|
|
79
|
+
"""Match a label as written, tolerating spacing variants after its periods.
|
|
80
|
+
|
|
81
|
+
Exports write the same label as ``CUMPLE REQ. DE CALIDAD`` and
|
|
82
|
+
``CUMPLE REQ.DE CALIDAD``; the matched text is kept as written.
|
|
83
|
+
"""
|
|
84
|
+
parts = re.split(r"(\.\s*|\s+)", label)
|
|
85
|
+
return "".join(
|
|
86
|
+
r"\.\s*" if part.startswith(".") else r"\s+" if part.isspace() else re.escape(part)
|
|
87
|
+
for part in parts
|
|
88
|
+
if part
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _split_first_colon(text: str) -> tuple[str, str]:
|
|
93
|
+
label, separator, value = text.partition(":")
|
|
94
|
+
return (label, value) if separator else ("", "")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _append_pair(pairs: list[tuple[str, str]], label: str, value: str) -> None:
|
|
98
|
+
label = label.strip()
|
|
99
|
+
value = value.strip()
|
|
100
|
+
if label and value:
|
|
101
|
+
pairs.append((label, value))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def normalize_label(raw_label: str) -> str:
|
|
105
|
+
"""Normalize a raw attribute label as stored in ``alias.raw_label``."""
|
|
106
|
+
return raw_label.strip().casefold()
|