argos-cli 0.3.1__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 (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,146 @@
1
+ """Download seguro de recursos apontados por atalhos ``.url`` em anexos.
2
+
3
+ Só domínios ``.gov.br`` por ``http``/``https``. O destino é validado antes de
4
+ cada requisição (inclusive redirecionamentos) e todo endereço resolvido precisa
5
+ ser público; o corpo é limitado em tamanho e o tipo de conteúdo precisa estar
6
+ numa lista permitida.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import ipaddress
12
+ import mimetypes
13
+ import re
14
+ import socket
15
+ from pathlib import Path
16
+ from typing import Any, Callable
17
+ from urllib.parse import urljoin, urlparse
18
+
19
+ from ..errors import InputValidationError
20
+
21
+ ALLOWED_SCHEMES = frozenset({"http", "https"})
22
+ ALLOWED_DOMAIN_SUFFIXES = (".gov.br",)
23
+ MAX_BYTES = 10 * 1024 * 1024
24
+ TIMEOUT_SECONDS = 30
25
+ MAX_REDIRECTS = 5
26
+ ALLOWED_MIME = frozenset(
27
+ {
28
+ "application/pdf",
29
+ "application/msword",
30
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
31
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
32
+ "application/vnd.oasis.opendocument.text",
33
+ "application/vnd.oasis.opendocument.spreadsheet",
34
+ "text/plain",
35
+ "text/html",
36
+ "text/markdown",
37
+ "image/png",
38
+ "image/jpeg",
39
+ }
40
+ )
41
+ _USER_AGENT = "Mozilla/5.0 (compatible; ArgosCLI; +https://github.com/)"
42
+
43
+
44
+ def parse_url_shortcut(content: bytes) -> str:
45
+ """Lê a linha ``URL=`` de um atalho ``.url`` (formato INI do Windows)."""
46
+ text = content.decode("utf-8", errors="ignore")
47
+ for line in text.splitlines():
48
+ match = re.match(r"^\s*URL\s*=\s*(\S.*?)\s*$", line, flags=re.IGNORECASE)
49
+ if match:
50
+ return match.group(1)
51
+ raise InputValidationError("atalho .url sem linha URL=")
52
+
53
+
54
+ def validate_url(url: str, *, resolver: Callable[..., Any] = socket.getaddrinfo) -> None:
55
+ """Recusa URL fora da política; não faz requisição."""
56
+ parsed = urlparse(url)
57
+ if parsed.scheme.casefold() not in ALLOWED_SCHEMES:
58
+ raise InputValidationError(f"esquema de URL não permitido: {parsed.scheme or '(vazio)'}")
59
+ hostname = (parsed.hostname or "").casefold()
60
+ if not hostname:
61
+ raise InputValidationError("URL sem hostname")
62
+ if "@" in parsed.netloc:
63
+ raise InputValidationError("URL com credenciais embutidas não permitida")
64
+ if not any(hostname.endswith(suffix) for suffix in ALLOWED_DOMAIN_SUFFIXES):
65
+ raise InputValidationError(f"domínio não permitido: {hostname}")
66
+ port = parsed.port or (443 if parsed.scheme.casefold() == "https" else 80)
67
+ try:
68
+ addresses = {item[4][0] for item in resolver(hostname, port, type=socket.SOCK_STREAM)}
69
+ except OSError as exc:
70
+ raise InputValidationError(f"hostname não resolvido: {hostname}") from exc
71
+ if not addresses:
72
+ raise InputValidationError(f"hostname sem endereço: {hostname}")
73
+ for address in addresses:
74
+ ip = ipaddress.ip_address(address)
75
+ if ip.is_private or ip.is_reserved or ip.is_loopback or ip.is_link_local or ip.is_multicast:
76
+ raise InputValidationError("hostname resolve para endereço privado ou reservado")
77
+
78
+
79
+ class UrlFetcher:
80
+ """Baixa um recurso permitido e devolve ``(nome, bytes, content_type)``."""
81
+
82
+ def __init__(
83
+ self,
84
+ *,
85
+ session_factory: Callable[[], Any] | None = None,
86
+ resolver: Callable[..., Any] = socket.getaddrinfo,
87
+ ) -> None:
88
+ self._session_factory = session_factory
89
+ self._resolver = resolver
90
+
91
+ def _session(self) -> Any:
92
+ if self._session_factory is not None:
93
+ return self._session_factory()
94
+ try:
95
+ import requests
96
+ except ImportError as exc: # pragma: no cover - depende do ambiente do usuário
97
+ raise InputValidationError("download de .url requer argos-cli[attachments]") from exc
98
+ return requests.Session()
99
+
100
+ def fetch(self, url: str) -> tuple[str, bytes, str]:
101
+ session = self._session()
102
+ current = url
103
+ response = None
104
+ for _ in range(MAX_REDIRECTS + 1):
105
+ validate_url(current, resolver=self._resolver)
106
+ # A política acima restringe esquema, domínio e endereços resolvidos (anti-SSRF).
107
+ response = session.get(
108
+ current,
109
+ headers={"User-Agent": _USER_AGENT},
110
+ timeout=TIMEOUT_SECONDS,
111
+ stream=True,
112
+ allow_redirects=False,
113
+ )
114
+ if getattr(response, "is_redirect", False) or getattr(response, "is_permanent_redirect", False):
115
+ location = response.headers.get("Location")
116
+ response.close()
117
+ if not location:
118
+ raise InputValidationError("redirecionamento sem destino")
119
+ current = urljoin(current, location)
120
+ continue
121
+ break
122
+ else:
123
+ raise InputValidationError("quantidade máxima de redirecionamentos excedida")
124
+ assert response is not None
125
+ try:
126
+ response.raise_for_status()
127
+ length = response.headers.get("Content-Length")
128
+ if length and length.isdigit() and int(length) > MAX_BYTES:
129
+ raise InputValidationError(f"recurso excede {MAX_BYTES} bytes")
130
+ data = bytearray()
131
+ for chunk in response.iter_content(chunk_size=8192):
132
+ data.extend(chunk)
133
+ if len(data) > MAX_BYTES:
134
+ raise InputValidationError(f"recurso excede {MAX_BYTES} bytes")
135
+ content_type = str(response.headers.get("Content-Type", "")).split(";")[0].strip().casefold()
136
+ finally:
137
+ response.close()
138
+ name = Path(urlparse(current).path).name or "recurso"
139
+ if not content_type:
140
+ content_type = (mimetypes.guess_type(name)[0] or "").casefold()
141
+ if content_type not in ALLOWED_MIME:
142
+ raise InputValidationError(f"tipo de conteúdo não permitido: {content_type or 'desconhecido'}")
143
+ if not Path(name).suffix:
144
+ extension = mimetypes.guess_extension(content_type) or ""
145
+ name = f"{name}{extension}"
146
+ return name, bytes(data), content_type
argos/adapters/xlsx.py ADDED
@@ -0,0 +1,454 @@
1
+ """Leitura e escrita de XLSX/CSV e serialização determinística.
2
+
3
+ Absorve `inputs`, `workbook_tables` e `workbook_serialization`: o núcleo não
4
+ depende de `openpyxl` fora deste adaptador."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import csv
9
+ import json
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Callable, Iterable, Mapping
13
+ from ..core import InputValidationError, MissingInputError, OperationContext, sha256_file
14
+ import io
15
+ import re
16
+
17
+
18
+ def row_has_values(values: Iterable[Any]) -> bool:
19
+ """Uma linha/registro conta como preenchido se algum valor não é vazio."""
20
+ return any(value not in (None, "") for value in values)
21
+
22
+
23
+ def require_file(context: OperationContext, value: str | Path, label: str) -> Path:
24
+ """Resolve e valida um arquivo de entrada obrigatório."""
25
+ path = context.path(value)
26
+ if not path.exists():
27
+ raise MissingInputError(f"arquivo de {label} ausente: {path}")
28
+ if not path.is_file():
29
+ raise InputValidationError(f"o input de {label} não é arquivo: {path}")
30
+ return path
31
+
32
+
33
+ def read_json_file(path: Path, *, label: str) -> Any:
34
+ """Lê e parseia um arquivo JSON, sem resolução de caminho."""
35
+ try:
36
+ return json.loads(path.read_text(encoding="utf-8"))
37
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
38
+ raise InputValidationError(f"{label} não é JSON válido: {path}") from exc
39
+
40
+
41
+ def _read_json_file(context: OperationContext, value: str | Path, label: str) -> Any:
42
+ return read_json_file(require_file(context, value, label), label=label)
43
+
44
+
45
+ def load_json_list(
46
+ context: OperationContext,
47
+ value: Any,
48
+ *,
49
+ label: str,
50
+ keys: Iterable[str] = (),
51
+ item_fn: Callable[[Any, int], dict[str, Any]],
52
+ ) -> list[dict[str, Any]]:
53
+ """Lê uma lista de especificações de um arquivo JSON ou de um Mapping.
54
+
55
+ Um Mapping é desembrulhado pela primeira chave de ``keys`` com valor
56
+ verdadeiro; o resultado deve ser uma lista não vazia. ``item_fn`` valida e
57
+ normaliza cada item e recebe a posição (1-based) para mensagens
58
+ posicionais; pode capturar estado (ex.: conjunto de saídas repetidas).
59
+ """
60
+ if isinstance(value, (str, Path)):
61
+ payload = _read_json_file(context, value, label)
62
+ else:
63
+ payload = value
64
+ if isinstance(payload, Mapping):
65
+ for key in keys:
66
+ if payload.get(key):
67
+ payload = payload[key]
68
+ break
69
+ if not isinstance(payload, list) or not payload:
70
+ raise InputValidationError(f"{label} deve ser uma lista JSON não vazia")
71
+ return [item_fn(item, position) for position, item in enumerate(payload, start=1)]
72
+
73
+
74
+ def load_json_object(
75
+ context: OperationContext,
76
+ value: Any,
77
+ *,
78
+ label: str,
79
+ ) -> Mapping[str, Any]:
80
+ """Lê um objeto JSON de um arquivo ou de um Mapping.
81
+
82
+ ``None`` ou string vazia produzem um objeto vazio (contexto opcional);
83
+ um Mapping é devolvido como está; um caminho é lido e validado como
84
+ objeto JSON.
85
+ """
86
+ if value in (None, ""):
87
+ return {}
88
+ if isinstance(value, Mapping):
89
+ return value
90
+ payload = _read_json_file(context, value, label)
91
+ if not isinstance(payload, Mapping):
92
+ raise InputValidationError(f"{label} deve ser um objeto JSON")
93
+ return payload
94
+
95
+
96
+ def openpyxl_workbook():
97
+ """Importa preguiçosamente ``openpyxl.load_workbook``.
98
+
99
+ O chamador decide os modos (ex.: ``read_only`` para leitura, modo padrão
100
+ para ajustes com escrita).
101
+ """
102
+ try:
103
+ from openpyxl import load_workbook
104
+ except ImportError as exc: # pragma: no cover - depende do ambiente do usuário
105
+ raise InputValidationError(
106
+ "a operação XLSX requer openpyxl; instale argos-cli[workbooks]"
107
+ ) from exc
108
+ return load_workbook
109
+
110
+
111
+ def find_header_row(worksheet: Any, *, required: Iterable[str] = ()) -> tuple[int, list[str]]:
112
+ """Localiza a linha de cabeçalho nas primeiras 20 linhas.
113
+
114
+ Sem ``required``, a primeira linha não vazia é o cabeçalho; com
115
+ ``required``, a primeira linha que contém todos os nomes exigidos.
116
+ Retorna ``(0, [])`` quando nenhuma linha serve.
117
+ """
118
+ required_norm = {str(item).casefold() for item in required}
119
+ for row_number, row in enumerate(
120
+ worksheet.iter_rows(max_row=min(worksheet.max_row or 1, 20), values_only=True),
121
+ start=1,
122
+ ):
123
+ values = ["" if value is None else str(value).strip() for value in row]
124
+ if not any(values):
125
+ continue
126
+ present = {value.casefold() for value in values if value}
127
+ if not required_norm or required_norm.issubset(present):
128
+ return row_number, values
129
+ return 0, []
130
+
131
+
132
+ def find_column(headers: Iterable[str], candidates: Iterable[str]) -> str | None:
133
+ """Devolve o nome canônico da coluna cujo cabeçalho normalizado casa."""
134
+ normalized = {str(header).strip().casefold(): str(header) for header in headers if header}
135
+ for candidate in candidates:
136
+ found = normalized.get(str(candidate).strip().casefold())
137
+ if found:
138
+ return found
139
+ return None
140
+
141
+
142
+ def _rows_from_sheet(worksheet: Any, header_row: int, headers: list[str]) -> list[dict[str, Any]]:
143
+ rows: list[dict[str, Any]] = []
144
+ for values in worksheet.iter_rows(min_row=header_row + 1, values_only=True):
145
+ row = {
146
+ headers[index]: values[index] if index < len(values) else None
147
+ for index in range(len(headers))
148
+ if headers[index]
149
+ }
150
+ if row_has_values(row.values()):
151
+ rows.append(row)
152
+ return rows
153
+
154
+
155
+ def sheet_records(
156
+ worksheet: Any,
157
+ *,
158
+ required: Iterable[str] = (),
159
+ ) -> tuple[int, list[str], list[dict[str, Any]]]:
160
+ """Cabeçalho e registros de uma aba de planilha.
161
+
162
+ A aba precisa ter cabeçalho (com ``required``, contendo os nomes
163
+ exigidos); linhas totalmente vazias são descartadas.
164
+ """
165
+ header_row, headers = find_header_row(worksheet, required=required)
166
+ if not header_row:
167
+ raise InputValidationError(f"aba {worksheet.title!r} não possui cabeçalho esperado")
168
+ return header_row, headers, _rows_from_sheet(worksheet, header_row, headers)
169
+
170
+
171
+ def _csv_records(
172
+ path: Path,
173
+ *,
174
+ required: Iterable[str] = (),
175
+ ) -> tuple[list[str], list[dict[str, Any]]]:
176
+ try:
177
+ sample = path.read_text(encoding="utf-8-sig", errors="strict")[:65536]
178
+ except (OSError, UnicodeError) as exc:
179
+ raise InputValidationError(f"não foi possível ler CSV {path}: {exc}") from exc
180
+ try:
181
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
182
+ except csv.Error:
183
+ dialect = csv.excel
184
+ with path.open("r", encoding="utf-8-sig", newline="") as stream:
185
+ reader = csv.DictReader(stream, dialect=dialect)
186
+ if not reader.fieldnames:
187
+ raise InputValidationError(f"CSV {path.name!r} não possui cabeçalho esperado")
188
+ headers = [str(field or "").strip().lstrip("\ufeff") for field in reader.fieldnames]
189
+ required_norm = {str(item).strip().casefold() for item in required}
190
+ present = {header.casefold() for header in headers if header}
191
+ if required_norm and not required_norm.issubset(present):
192
+ raise InputValidationError(f"CSV {path.name!r} não possui cabeçalho esperado")
193
+ rows: list[dict[str, Any]] = []
194
+ for raw_row in reader:
195
+ row = {
196
+ headers[index]: (raw_row.get(reader.fieldnames[index]) or "").strip()
197
+ for index in range(len(headers))
198
+ if headers[index]
199
+ }
200
+ if row_has_values(row.values()):
201
+ rows.append(row)
202
+ return headers, rows
203
+
204
+
205
+ def workbook_records(
206
+ path: Path,
207
+ *,
208
+ required: Iterable[str] = (),
209
+ ) -> tuple[list[str], list[dict[str, Any]]]:
210
+ """Cabeçalho e registros da aba ativa de um arquivo XLSX ou CSV."""
211
+ if path.suffix.casefold() == ".csv":
212
+ return _csv_records(path, required=required)
213
+ load_workbook = openpyxl_workbook()
214
+ workbook = load_workbook(path, read_only=True, data_only=True)
215
+ try:
216
+ _, headers, rows = sheet_records(workbook.active, required=required)
217
+ finally:
218
+ workbook.close()
219
+ return headers, rows
220
+
221
+
222
+ @dataclass(frozen=True)
223
+ class TabularRecord:
224
+ """One physical response row, including its source row number."""
225
+
226
+ row_number: int
227
+ values: tuple[Any, ...]
228
+
229
+
230
+ @dataclass(frozen=True)
231
+ class TabularTable:
232
+ """Headers and positional rows before duplicate names can be lost in a dict."""
233
+
234
+ headers: tuple[str, ...]
235
+ rows: tuple[TabularRecord, ...]
236
+
237
+
238
+ def _table_value_present(value: Any) -> bool:
239
+ return value is not None and not (isinstance(value, str) and not value.strip())
240
+
241
+
242
+ def _trim_empty_header_columns(headers: list[str]) -> list[str]:
243
+ while headers and not headers[-1]:
244
+ headers.pop()
245
+ return headers
246
+
247
+
248
+ def _finish_tabular_table(headers: list[str], rows: list[TabularRecord]) -> TabularTable:
249
+ last_data_row = max(
250
+ (index for index, record in enumerate(rows) if any(_table_value_present(value) for value in record.values)),
251
+ default=-1,
252
+ )
253
+ return TabularTable(tuple(headers), tuple(rows[: last_data_row + 1]))
254
+
255
+
256
+ def read_tabular_table(path: Path) -> TabularTable:
257
+ """Read XLSX/CSV without collapsing duplicate headers or interior blank rows.
258
+
259
+ Trailing empty rows/columns are presentation space and are omitted. Rows
260
+ between the header and the final populated row retain their physical
261
+ positions, including completely blank rows for DSL policy validation.
262
+ """
263
+ if path.suffix.casefold() == ".csv":
264
+ return _read_tabular_csv(path)
265
+
266
+ load_workbook = openpyxl_workbook()
267
+ try:
268
+ workbook = load_workbook(path, read_only=True, data_only=True)
269
+ except (OSError, ValueError) as exc:
270
+ raise InputValidationError(f"não foi possível ler XLSX {path}: {exc}") from exc
271
+ try:
272
+ worksheet = workbook.active
273
+ header_row, raw_headers = find_header_row(worksheet)
274
+ if not header_row:
275
+ raise InputValidationError(f"planilha {path.name!r} não possui cabeçalho")
276
+ headers = _trim_empty_header_columns(list(raw_headers))
277
+ if not headers:
278
+ raise InputValidationError(f"planilha {path.name!r} não possui cabeçalho")
279
+
280
+ rows: list[TabularRecord] = []
281
+ for row_number, values in enumerate(
282
+ worksheet.iter_rows(min_row=header_row + 1, values_only=True),
283
+ start=header_row + 1,
284
+ ):
285
+ extra = values[len(headers) :]
286
+ if any(_table_value_present(value) for value in extra):
287
+ raise InputValidationError(f"linha {row_number} de {path.name!r} contém valor sem cabeçalho")
288
+ positional = tuple(values[index] if index < len(values) else None for index in range(len(headers)))
289
+ rows.append(TabularRecord(row_number, positional))
290
+ return _finish_tabular_table(headers, rows)
291
+ finally:
292
+ workbook.close()
293
+
294
+
295
+ def _read_tabular_csv(path: Path) -> TabularTable:
296
+ try:
297
+ sample = path.read_text(encoding="utf-8-sig", errors="strict")[:65536]
298
+ except (OSError, UnicodeError) as exc:
299
+ raise InputValidationError(f"não foi possível ler CSV {path}: {exc}") from exc
300
+ try:
301
+ dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
302
+ except csv.Error:
303
+ dialect = csv.excel
304
+
305
+ try:
306
+ with path.open("r", encoding="utf-8-sig", newline="") as stream:
307
+ reader = csv.reader(stream, dialect=dialect)
308
+ try:
309
+ raw_headers = next(reader)
310
+ except StopIteration as exc:
311
+ raise InputValidationError(f"CSV {path.name!r} não possui cabeçalho") from exc
312
+ headers = _trim_empty_header_columns([str(header or "").strip() for header in raw_headers])
313
+ if not headers:
314
+ raise InputValidationError(f"CSV {path.name!r} não possui cabeçalho")
315
+
316
+ records: list[TabularRecord] = []
317
+ previous_line = reader.line_num
318
+ for values in reader:
319
+ row_number = previous_line + 1
320
+ previous_line = reader.line_num
321
+ if len(values) > len(headers) and any(_table_value_present(value) for value in values[len(headers) :]):
322
+ raise InputValidationError(f"linha {row_number} de {path.name!r} contém valor sem cabeçalho")
323
+ positional = tuple(values[index] if index < len(values) else None for index in range(len(headers)))
324
+ records.append(TabularRecord(row_number, positional))
325
+ except (OSError, UnicodeError, csv.Error) as exc:
326
+ raise InputValidationError(f"não foi possível interpretar CSV {path}: {exc}") from exc
327
+ return _finish_tabular_table(headers, records)
328
+
329
+
330
+ def workbook_summary(path: Path, *, required: Iterable[str] = ()) -> dict[str, Any]:
331
+ """Resumo estrutural das abas de um XLSX para validação de insumos."""
332
+ load_workbook = openpyxl_workbook()
333
+ workbook = load_workbook(path, read_only=True, data_only=True)
334
+ try:
335
+ sheets: list[dict[str, Any]] = []
336
+ for position, worksheet in enumerate(workbook.worksheets):
337
+ header_row, headers = find_header_row(
338
+ worksheet,
339
+ required=required if position == 0 else (),
340
+ )
341
+ nonempty_rows = 0
342
+ for values in worksheet.iter_rows(values_only=True):
343
+ if row_has_values(values):
344
+ nonempty_rows += 1
345
+ sheets.append(
346
+ {
347
+ "name": worksheet.title,
348
+ "rows_with_values": nonempty_rows,
349
+ "max_row": worksheet.max_row,
350
+ "max_column": worksheet.max_column,
351
+ "header_row": header_row,
352
+ "headers": [header for header in headers if header],
353
+ }
354
+ )
355
+ finally:
356
+ workbook.close()
357
+ return {"path": str(path), "sha256": sha256_file(path), "sheets": sheets}
358
+
359
+
360
+ def _serialize_cell(value: Any) -> Any:
361
+ if isinstance(value, (dict, list, tuple, set)):
362
+ return json.dumps(value, ensure_ascii=False, default=str)
363
+ return value
364
+
365
+
366
+ def write_table_sheet(
367
+ workbook: Any,
368
+ title: str,
369
+ headers: Iterable[str],
370
+ rows: Iterable[Mapping[str, Any]],
371
+ ) -> Any:
372
+ worksheet = workbook.create_sheet(str(title)[:31])
373
+ header_list = [str(header) for header in headers]
374
+ worksheet.append(header_list)
375
+ for row in rows:
376
+ worksheet.append([_serialize_cell(row.get(header)) for header in header_list])
377
+ return worksheet
378
+
379
+
380
+ def audit_table_bytes(
381
+ tables: Mapping[str, list[Mapping[str, Any]]],
382
+ *,
383
+ empty_headers: Mapping[str, Iterable[str]] | None = None,
384
+ ) -> bytes:
385
+ try:
386
+ from openpyxl import Workbook
387
+ except ImportError as exc: # pragma: no cover
388
+ raise InputValidationError("a geração de tabelas requer openpyxl") from exc
389
+ workbook = Workbook()
390
+ default = workbook.active
391
+ workbook.remove(default)
392
+ for title, rows in tables.items():
393
+ headers = list(rows[0]) if rows else list((empty_headers or {}).get(title, ()))
394
+ if not headers:
395
+ continue
396
+ write_table_sheet(workbook, title, headers, rows)
397
+ buffer = io.BytesIO()
398
+ workbook.save(buffer)
399
+ return buffer.getvalue()
400
+
401
+
402
+ def xlsx_bytes_with_headers(
403
+ tables: Mapping[str, tuple[Iterable[str], Iterable[Mapping[str, Any]]]],
404
+ ) -> bytes:
405
+ """Serializa tabelas pequenas mantendo cabeçalhos mesmo sem linhas."""
406
+ try:
407
+ from openpyxl import Workbook
408
+ except ImportError as exc: # pragma: no cover
409
+ raise InputValidationError("a geração de planilhas requer openpyxl") from exc
410
+ workbook = Workbook()
411
+ workbook.remove(workbook.active)
412
+ for title, (headers, rows) in tables.items():
413
+ worksheet = write_table_sheet(workbook, title, headers, rows)
414
+ worksheet.freeze_panes = "A2"
415
+ worksheet.auto_filter.ref = worksheet.dimensions
416
+ for column in worksheet.columns:
417
+ values = [str(cell.value or "") for cell in column]
418
+ width = min(60, max(12, max((len(value) for value in values), default=12) + 2))
419
+ worksheet.column_dimensions[column[0].column_letter].width = width
420
+ buffer = io.BytesIO()
421
+ workbook.save(buffer)
422
+ return buffer.getvalue()
423
+
424
+
425
+ def workbook_bytes(workbook: Any) -> bytes:
426
+ """Serializa o XLSX com bytes estáveis entre execuções.
427
+
428
+ O ``openpyxl`` grava ``dcterms:modified`` com o horário atual e timestamps
429
+ de entrada no ZIP a cada save — o mesmo produto varia a cada execução,
430
+ quebrando hashes de proveniência (cenários imutáveis) e a
431
+ reprodutibilidade. Este helper normaliza o XML e os cabeçalhos do ZIP.
432
+ """
433
+ import zipfile
434
+
435
+ buffer = io.BytesIO()
436
+ workbook.save(buffer)
437
+ with zipfile.ZipFile(io.BytesIO(buffer.getvalue())) as fonte:
438
+ entradas = fonte.namelist()
439
+ conteudos = {nome: fonte.read(nome) for nome in entradas}
440
+ core = conteudos.get("docProps/core.xml", b"")
441
+ if core:
442
+ core = re.sub(
443
+ rb"(<dcterms:modified[^>]*>)[^<]*(</dcterms:modified>)",
444
+ rb"\g<1>2000-01-01T00:00:00Z\g<2>",
445
+ core,
446
+ )
447
+ conteudos["docProps/core.xml"] = core
448
+ saida = io.BytesIO()
449
+ with zipfile.ZipFile(saida, "w", compression=zipfile.ZIP_DEFLATED) as alvo:
450
+ for nome in entradas:
451
+ info = zipfile.ZipInfo(nome, date_time=(1980, 1, 1, 0, 0, 0))
452
+ info.compress_type = zipfile.ZIP_DEFLATED
453
+ alvo.writestr(info, conteudos[nome])
454
+ return saida.getvalue()