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/excel.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Parser for Perú Compras Excel exports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
import zipfile
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from urllib.parse import urlsplit
|
|
12
|
+
from xml.etree import ElementTree
|
|
13
|
+
|
|
14
|
+
_MAIN_NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
|
|
15
|
+
_COLUMNS = (
|
|
16
|
+
"Acuerdo Marco",
|
|
17
|
+
"Catálogo",
|
|
18
|
+
"Categoría",
|
|
19
|
+
"Descripción Ficha-Producto",
|
|
20
|
+
"Marca",
|
|
21
|
+
"Nro. Parte o Código Único de Identificación",
|
|
22
|
+
"Ficha Técnica",
|
|
23
|
+
"Imagen",
|
|
24
|
+
"Estado Ficha - Producto",
|
|
25
|
+
"Monto Contratado",
|
|
26
|
+
"Cant. OCAM",
|
|
27
|
+
)
|
|
28
|
+
# SpreadsheetML (ST_Xstring) escapes a character as ``_xHHHH_``; ``_x005F_`` escapes
|
|
29
|
+
# the underscore, so ``_x005F_x000D_`` is the literal text ``_x000D_``.
|
|
30
|
+
# A UTF-16 surrogate pair is written as two escapes (``_xD83D__xDE00_``) and is
|
|
31
|
+
# combined into one character; a lone surrogate escape is kept as literal text so
|
|
32
|
+
# values stay valid UTF-8 for hashing.
|
|
33
|
+
_XSTRING_ESCAPE = re.compile(
|
|
34
|
+
r"_x(?P<high>[Dd][89ABab][0-9A-Fa-f]{2})__x(?P<low>[Dd][C-Fc-f][0-9A-Fa-f]{2})_"
|
|
35
|
+
r"|_x(?P<code>[0-9A-Fa-f]{4})_"
|
|
36
|
+
)
|
|
37
|
+
_HEADER_ALIASES = {
|
|
38
|
+
"Ficha Técnica URL": "Ficha Técnica",
|
|
39
|
+
"Imagen URL": "Imagen",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True)
|
|
44
|
+
class ExcelFicha:
|
|
45
|
+
"""One ficha row from an Excel export, with its source and derived fields."""
|
|
46
|
+
|
|
47
|
+
agreement: str
|
|
48
|
+
catalogue: str
|
|
49
|
+
category: str
|
|
50
|
+
description: str
|
|
51
|
+
marca: str
|
|
52
|
+
nro_parte: str
|
|
53
|
+
ficha_tecnica_url: str
|
|
54
|
+
imagen_url: str
|
|
55
|
+
estado: str
|
|
56
|
+
monto_contratado: str
|
|
57
|
+
cant_ocam: str
|
|
58
|
+
ficha_id: str
|
|
59
|
+
pdf_url: str | None
|
|
60
|
+
excel_hash: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_excel(body: bytes) -> list[ExcelFicha]:
|
|
64
|
+
"""Parse an Excel export into fichas, hashing each row's raw cell values."""
|
|
65
|
+
try:
|
|
66
|
+
with zipfile.ZipFile(io.BytesIO(body)) as workbook:
|
|
67
|
+
shared_strings = _shared_strings(workbook)
|
|
68
|
+
sheet = ElementTree.fromstring(workbook.read("xl/worksheets/sheet1.xml"))
|
|
69
|
+
except (ElementTree.ParseError, KeyError, zipfile.BadZipFile) as exc:
|
|
70
|
+
raise ValueError("Invalid Excel export") from exc
|
|
71
|
+
|
|
72
|
+
sheet_data = sheet.find(f"{_MAIN_NS}sheetData")
|
|
73
|
+
if sheet_data is None:
|
|
74
|
+
raise ValueError("Excel export has no worksheet data")
|
|
75
|
+
|
|
76
|
+
rows = list(sheet_data.findall(f"{_MAIN_NS}row"))
|
|
77
|
+
if not rows:
|
|
78
|
+
raise ValueError("Excel export has no header row")
|
|
79
|
+
|
|
80
|
+
header_cells = _cell_values(rows[0], shared_strings)
|
|
81
|
+
normalized_headers = {
|
|
82
|
+
index: _HEADER_ALIASES.get(value, value) for index, value in header_cells.items()
|
|
83
|
+
}
|
|
84
|
+
if len(normalized_headers) != len(_COLUMNS) or set(normalized_headers.values()) != set(
|
|
85
|
+
_COLUMNS
|
|
86
|
+
):
|
|
87
|
+
raise ValueError("Excel export has missing or duplicate columns")
|
|
88
|
+
headers = {column: index for index, column in normalized_headers.items()}
|
|
89
|
+
|
|
90
|
+
result: list[ExcelFicha] = []
|
|
91
|
+
for row_number, row in enumerate(rows[1:], start=2):
|
|
92
|
+
cells = _cell_values(row, shared_strings)
|
|
93
|
+
raw_fields = tuple(cells.get(headers[column], "") for column in _COLUMNS)
|
|
94
|
+
if not any(raw_fields):
|
|
95
|
+
continue
|
|
96
|
+
|
|
97
|
+
ficha_id = _ficha_id(raw_fields[6], raw_fields[7], row_number)
|
|
98
|
+
excel_hash = hashlib.sha256(
|
|
99
|
+
json.dumps(raw_fields, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
|
100
|
+
).hexdigest()
|
|
101
|
+
result.append(
|
|
102
|
+
ExcelFicha(
|
|
103
|
+
agreement=raw_fields[0],
|
|
104
|
+
catalogue=raw_fields[1],
|
|
105
|
+
category=raw_fields[2],
|
|
106
|
+
description=raw_fields[3],
|
|
107
|
+
marca=raw_fields[4],
|
|
108
|
+
nro_parte=raw_fields[5],
|
|
109
|
+
ficha_tecnica_url=raw_fields[6],
|
|
110
|
+
imagen_url=raw_fields[7],
|
|
111
|
+
estado=raw_fields[8],
|
|
112
|
+
monto_contratado=raw_fields[9],
|
|
113
|
+
cant_ocam=raw_fields[10],
|
|
114
|
+
ficha_id=ficha_id,
|
|
115
|
+
pdf_url=raw_fields[6] or None,
|
|
116
|
+
excel_hash=excel_hash,
|
|
117
|
+
)
|
|
118
|
+
)
|
|
119
|
+
return result
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _shared_strings(workbook: zipfile.ZipFile) -> list[str]:
|
|
123
|
+
try:
|
|
124
|
+
root = ElementTree.fromstring(workbook.read("xl/sharedStrings.xml"))
|
|
125
|
+
except KeyError:
|
|
126
|
+
return []
|
|
127
|
+
return [
|
|
128
|
+
_decode_xstring("".join(text.text or "" for text in item.iter(f"{_MAIN_NS}t")))
|
|
129
|
+
for item in root.findall(f"{_MAIN_NS}si")
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _decode_xstring(text: str) -> str:
|
|
134
|
+
"""Decode ``_xHHHH_`` escapes in one left-to-right pass.
|
|
135
|
+
|
|
136
|
+
A single pass keeps ``_x005F_x000D_`` as the literal ``_x000D_``: the ``_x005F_``
|
|
137
|
+
match becomes ``_`` and scanning resumes after it.
|
|
138
|
+
"""
|
|
139
|
+
return _XSTRING_ESCAPE.sub(_decode_escape, text)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _decode_escape(match: re.Match[str]) -> str:
|
|
143
|
+
if match["high"] is not None:
|
|
144
|
+
high = int(match["high"], 16)
|
|
145
|
+
low = int(match["low"], 16)
|
|
146
|
+
return chr(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00))
|
|
147
|
+
code = int(match["code"], 16)
|
|
148
|
+
if 0xD800 <= code <= 0xDFFF:
|
|
149
|
+
return match.group()
|
|
150
|
+
return chr(code)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _cell_values(row: ElementTree.Element, shared_strings: list[str]) -> dict[int, str]:
|
|
154
|
+
values: dict[int, str] = {}
|
|
155
|
+
for cell in row.findall(f"{_MAIN_NS}c"):
|
|
156
|
+
reference = cell.get("r", "")
|
|
157
|
+
letters = re.match(r"[A-Z]+", reference)
|
|
158
|
+
if letters is None:
|
|
159
|
+
raise ValueError(f"Invalid Excel cell reference: {reference!r}")
|
|
160
|
+
column_index = 0
|
|
161
|
+
for letter in letters.group():
|
|
162
|
+
column_index = column_index * 26 + ord(letter) - ord("A") + 1
|
|
163
|
+
column_index -= 1
|
|
164
|
+
|
|
165
|
+
value = cell.find(f"{_MAIN_NS}v")
|
|
166
|
+
if cell.get("t") == "s" and value is not None and value.text is not None:
|
|
167
|
+
try:
|
|
168
|
+
values[column_index] = shared_strings[int(value.text)]
|
|
169
|
+
except (IndexError, ValueError) as exc:
|
|
170
|
+
raise ValueError("Excel export has an invalid shared string reference") from exc
|
|
171
|
+
elif cell.get("t") == "inlineStr":
|
|
172
|
+
values[column_index] = _decode_xstring(
|
|
173
|
+
"".join(text.text or "" for text in cell.iter(f"{_MAIN_NS}t"))
|
|
174
|
+
)
|
|
175
|
+
else:
|
|
176
|
+
values[column_index] = value.text if value is not None and value.text else ""
|
|
177
|
+
return values
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _ficha_id(pdf_url: str, image_url: str, row_number: int) -> str:
|
|
181
|
+
for url in (pdf_url, image_url):
|
|
182
|
+
filename = urlsplit(url).path.rsplit("/", 1)[-1]
|
|
183
|
+
match = re.match(r"(\d+)", filename)
|
|
184
|
+
if match is not None:
|
|
185
|
+
return match.group(1)
|
|
186
|
+
raise ValueError(f"Excel row {row_number} has no ficha ID in its file URLs")
|