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
argos/adapters/ai.py ADDED
@@ -0,0 +1,1506 @@
1
+ """Providers de IA e processamento recursivo de anexos."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import io
7
+ import json
8
+ import math
9
+ import mimetypes
10
+ import os
11
+ import re
12
+ import shutil
13
+ import sys
14
+ import threading
15
+ import unicodedata
16
+ import zipfile
17
+ from collections import OrderedDict, defaultdict, deque
18
+ from dataclasses import dataclass, field, replace
19
+ from pathlib import Path
20
+ from typing import Any, Callable, Iterable, Mapping, Protocol
21
+ from ..booleans import parse_bool
22
+ from ..core import InputValidationError, sha256_bytes
23
+ from ..response_profiles import ResponseProfileRegistry
24
+ from .capabilities import Delivery, ModelCapabilities
25
+ from .model_call import AIServiceError, KeyRing, ModelCallPolicy, call_with_keys, raw_attempts
26
+ from .attachment_conversion import convert_office_bytes, extract_rar_members, safe_member_name
27
+ from .url_fetch import UrlFetcher
28
+ from .xlsx import openpyxl_workbook, row_has_values
29
+
30
+ _PROVIDER_ALIASES = {
31
+ "google": "gemini",
32
+ "google-genai": "gemini",
33
+ "opencode-go": "opencodego",
34
+ "opencode-go-ant": "opencodego-ant",
35
+ "open-router": "openrouter",
36
+ }
37
+ # O vocabulário de níveis é aberto (minimal, low, medium, high, xhigh, max, ultra...): quem valida é o provider.
38
+ _REASONING_LEVEL = re.compile(r"^[a-z][a-z0-9_-]{0,15}$")
39
+ IMAGE_TOKENS = 258
40
+ _PDF_CONVERSION_LOCK = threading.Lock()
41
+ # OCR das páginas sem texto: português a 200 dpi. Em 16 páginas reais de evidências (texto nativo como
42
+ # gabarito), `por` acertou 87% das palavras acentuadas contra 2% de `eng`; 300 dpi ganhou só 0,6 ponto.
43
+ _OCR_DPI = 200
44
+ _OCR_LANGUAGE = "por"
45
+ _OCR_FALLBACK_LANGUAGE = "eng"
46
+
47
+
48
+ def _provider_key(provider: str) -> str:
49
+ key = str(provider).casefold().replace("_", "-")
50
+ return _PROVIDER_ALIASES.get(key, key)
51
+
52
+
53
+ def normalize_reasoning_level(value: Any) -> str | None:
54
+ """Nível de raciocínio em minúsculas; ``None`` se vazio. O provider decide o que aceita."""
55
+ if value in (None, ""):
56
+ return None
57
+ level = str(value).strip().casefold()
58
+ if not _REASONING_LEVEL.match(level):
59
+ raise InputValidationError(
60
+ f"nível de raciocínio inválido: {value!r} (use letras minúsculas, como low, high, xhigh ou max)"
61
+ )
62
+ return level
63
+
64
+
65
+ def split_reasoning_suffix(spec: str) -> tuple[str, str | None]:
66
+ """Separa o sufixo ``@nivel`` de ``provider:modelo[:perfil]@nivel`` ou de um nome de modelo."""
67
+ if "@" not in spec:
68
+ return spec, None
69
+ if spec.count("@") > 1:
70
+ raise InputValidationError(f"mais de um nível de raciocínio em {spec!r}")
71
+ head, _, tail = spec.partition("@")
72
+ token, colon, remainder = tail.partition(":")
73
+ if not token.strip():
74
+ raise InputValidationError(f"nível de raciocínio vazio depois de '@' em {spec!r}")
75
+ return head + colon + remainder, normalize_reasoning_level(token)
76
+
77
+
78
+ def _non_negative(params: Mapping[str, Any], name: str, default: int) -> int:
79
+ value = params.get(name)
80
+ if value in (None, ""):
81
+ return default
82
+ try:
83
+ number = int(value)
84
+ except (TypeError, ValueError) as exc:
85
+ raise InputValidationError(f"{name} deve ser inteiro maior ou igual a zero") from exc
86
+ if number < 0:
87
+ raise InputValidationError(f"{name} deve ser inteiro maior ou igual a zero")
88
+ return number
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class AttachmentPolicy:
93
+ """Limites e opções que mudam o conteúdo preparado ou enviado ao modelo."""
94
+
95
+ max_pdf_pages: int = 100
96
+ min_image_bytes: int = 5120
97
+ max_images_per_request: int = 50
98
+ max_sheet_rows: int = 1000
99
+ ocr: bool = True
100
+ token_limits: Mapping[str, int] = field(default_factory=dict)
101
+ reasoning_level: str | None = None
102
+
103
+ def processing_key(self) -> tuple[Any, ...]:
104
+ """Campos que mudam o conteúdo preparado; entram no cache de anexos."""
105
+ return (self.max_pdf_pages, self.min_image_bytes, self.max_images_per_request, self.max_sheet_rows, self.ocr)
106
+
107
+ def token_limit(self, provider: str, default: int = 0) -> int:
108
+ """Limite pedido pelo usuário para o provider; sem ele, o padrão declarado pelo adapter."""
109
+ return int(self.token_limits.get(_provider_key(provider), default))
110
+
111
+ def as_dict(self) -> dict[str, Any]:
112
+ return {
113
+ "max_pdf_pages": self.max_pdf_pages,
114
+ "min_image_bytes": self.min_image_bytes,
115
+ "max_images_per_request": self.max_images_per_request,
116
+ "max_sheet_rows": self.max_sheet_rows,
117
+ "ocr": self.ocr,
118
+ "token_limits": dict(sorted(self.token_limits.items())),
119
+ "reasoning_level": self.reasoning_level,
120
+ }
121
+
122
+ @classmethod
123
+ def from_params(cls, params: Mapping[str, Any]) -> "AttachmentPolicy":
124
+ defaults = cls()
125
+ reasoning = normalize_reasoning_level(params.get("nivel_raciocinio"))
126
+ raw_limits = params.get("limite_tokens") or []
127
+ if isinstance(raw_limits, (str, Path)):
128
+ raw_limits = [part for part in str(raw_limits).split(",") if part.strip()]
129
+ limits: dict[str, int] = {}
130
+ for item in raw_limits:
131
+ name, separator, value = str(item).partition("=")
132
+ if not separator or not name.strip():
133
+ raise InputValidationError(f"limite_tokens deve usar provider=N: {item!r}")
134
+ try:
135
+ number = int(value)
136
+ except ValueError as exc:
137
+ raise InputValidationError(f"limite_tokens inválido: {item!r}") from exc
138
+ if number < 0:
139
+ raise InputValidationError(f"limite_tokens inválido: {item!r}")
140
+ limits[_provider_key(name.strip())] = number
141
+ return cls(
142
+ max_pdf_pages=_non_negative(params, "max_paginas_pdf", defaults.max_pdf_pages),
143
+ min_image_bytes=_non_negative(params, "min_bytes_imagem", defaults.min_image_bytes),
144
+ max_images_per_request=_non_negative(params, "max_imagens_requisicao", defaults.max_images_per_request),
145
+ max_sheet_rows=_non_negative(params, "max_linhas_planilha", defaults.max_sheet_rows),
146
+ ocr=parse_bool(params.get("ocr"), default=defaults.ocr),
147
+ token_limits=limits,
148
+ reasoning_level=reasoning,
149
+ )
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class ProcessedAttachment:
154
+ logical_path: str
155
+ mime_type: str
156
+ kind: str
157
+ content: bytes | str
158
+ metadata: Mapping[str, Any] = field(default_factory=dict)
159
+
160
+ def report(self) -> dict[str, Any]:
161
+ content = self.content.encode("utf-8") if isinstance(self.content, str) else self.content
162
+ return {
163
+ "path": self.logical_path,
164
+ "mime_type": self.mime_type,
165
+ "kind": self.kind,
166
+ "sha256": sha256_bytes(content),
167
+ "size_bytes": len(content),
168
+ "metadata": dict(self.metadata),
169
+ }
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class AttachmentIssue:
174
+ logical_path: str
175
+ reason: str
176
+ sha256: str | None = None
177
+
178
+ def as_dict(self) -> dict[str, Any]:
179
+ return {"path": self.logical_path, "reason": self.reason, "sha256": self.sha256}
180
+
181
+
182
+ _GAP_PATH_KEYS = frozenset({"arquivo", "arquivos"})
183
+
184
+
185
+ @dataclass(frozen=True)
186
+ class AttachmentReport:
187
+ processed: tuple[ProcessedAttachment, ...] = ()
188
+ pending: tuple[AttachmentIssue, ...] = ()
189
+ ignored: tuple[AttachmentIssue, ...] = ()
190
+ gaps: tuple[Mapping[str, Any], ...] = ()
191
+
192
+ def as_dict(self) -> dict[str, Any]:
193
+ return {
194
+ "processed": [item.report() for item in self.processed],
195
+ "pending": [item.as_dict() for item in self.pending],
196
+ "ignored": [item.as_dict() for item in self.ignored],
197
+ "gaps": [dict(item) for item in self.gaps],
198
+ }
199
+
200
+ def semantic_manifest(self) -> dict[str, Any]:
201
+ """Retorna somente o que pode alterar o conteúdo enviado ao modelo.
202
+
203
+ Caminhos físicos, ordem dos membros de ZIP e texto livre de erros são
204
+ metadados de rastreabilidade, não identidade semântica. A avaliação
205
+ não deve ser repetida porque o mesmo arquivo foi movido ou porque um
206
+ ZIP foi recriado em ordem diferente.
207
+ """
208
+
209
+ def processed_key(item: ProcessedAttachment) -> tuple[str, str, str, int]:
210
+ content = item.content.encode("utf-8") if isinstance(item.content, str) else item.content
211
+ return (item.kind, item.mime_type, sha256_bytes(content), len(content))
212
+
213
+ def issue_key(item: AttachmentIssue) -> tuple[str, str, str]:
214
+ suffix = Path(item.logical_path.split("!")[-1]).suffix.casefold()
215
+ reason = item.reason.casefold().split(":", 1)[0].strip()
216
+ return (suffix, reason, item.sha256 or "")
217
+
218
+ def gap_key(item: Mapping[str, Any]) -> str:
219
+ semantic = {key: value for key, value in item.items() if key not in _GAP_PATH_KEYS}
220
+ return json.dumps(semantic, sort_keys=True, ensure_ascii=False, default=str)
221
+
222
+ return {
223
+ "processed": [
224
+ {
225
+ "kind": kind,
226
+ "mime_type": mime_type,
227
+ "sha256": digest,
228
+ "size_bytes": size,
229
+ }
230
+ for kind, mime_type, digest, size in sorted(
231
+ (processed_key(item) for item in self.processed)
232
+ )
233
+ ],
234
+ "pending": [
235
+ {"suffix": suffix, "reason": reason, "sha256": digest}
236
+ for suffix, reason, digest in sorted(issue_key(item) for item in self.pending)
237
+ ],
238
+ "ignored": [
239
+ {"suffix": suffix, "reason": reason, "sha256": digest}
240
+ for suffix, reason, digest in sorted(issue_key(item) for item in self.ignored)
241
+ ],
242
+ "gaps": sorted(gap_key(item) for item in self.gaps),
243
+ }
244
+
245
+
246
+ class AttachmentProcessor(Protocol):
247
+ extensions: tuple[str, ...]
248
+
249
+ def process(
250
+ self, logical_path: str, content: bytes, *, delivery: Delivery
251
+ ) -> ProcessedAttachment | Iterable[ProcessedAttachment]: ...
252
+
253
+
254
+ def _text(content: bytes) -> str:
255
+ return content.decode("utf-8", errors="replace")
256
+
257
+
258
+ def _gap(logical_path: str, kind: str, **fields: Any) -> dict[str, Any]:
259
+ return {"arquivo": logical_path, "tipo": kind, **fields}
260
+
261
+
262
+ def dedupe_and_filter_derived_images(
263
+ images: list[tuple[str, bytes]],
264
+ markdown: str | None,
265
+ policy: AttachmentPolicy,
266
+ ) -> tuple[list[tuple[str, bytes]], str | None, dict[str, int]]:
267
+ """Remove imagens derivadas duplicadas (por SHA-256) e abaixo do tamanho mínimo.
268
+
269
+ As referências ``![..](img/<nome>)`` das imagens removidas saem do Markdown;
270
+ uma duplicata passa a apontar para a primeira ocorrência.
271
+ """
272
+ seen: dict[str, str] = {}
273
+ kept: list[tuple[str, bytes]] = []
274
+ counts = {"duplicadas": 0, "pequenas": 0}
275
+ text = markdown
276
+ for name, data in images:
277
+ digest = sha256_bytes(data)
278
+ if digest in seen:
279
+ counts["duplicadas"] += 1
280
+ if text is not None:
281
+ text = text.replace(f"img/{name}", f"img/{seen[digest]}")
282
+ continue
283
+ if policy.min_image_bytes > 0 and len(data) < policy.min_image_bytes:
284
+ counts["pequenas"] += 1
285
+ if text is not None:
286
+ text = re.sub(rf"!\[[^\]]*\]\((?:\./)?img/{re.escape(name)}(?:\s+[^)]*)?\)", "", text)
287
+ continue
288
+ seen[digest] = name
289
+ kept.append((name, data))
290
+ return kept, text, counts
291
+
292
+
293
+ class TextAttachmentProcessor:
294
+ extensions = (".txt", ".md", ".json", ".csv", ".xml", ".yaml", ".yml", ".html", ".log")
295
+ accepts_policy = True
296
+
297
+ def process(
298
+ self, logical_path: str, content: bytes, *, delivery: Delivery, policy: AttachmentPolicy | None = None
299
+ ) -> ProcessedAttachment:
300
+ extension = Path(logical_path).suffix.casefold()
301
+ mime = mimetypes.guess_type(logical_path)[0] or "text/plain"
302
+ return ProcessedAttachment(logical_path, mime, "text", _text(content), {"extension": extension})
303
+
304
+
305
+ class ImageAttachmentProcessor:
306
+ extensions = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff")
307
+ accepts_policy = True
308
+
309
+ def process(
310
+ self, logical_path: str, content: bytes, *, delivery: Delivery, policy: AttachmentPolicy | None = None
311
+ ) -> ProcessedAttachment:
312
+ if not delivery.images:
313
+ raise InputValidationError("o modelo escolhido não aceita imagem; use um modelo com visão")
314
+ mime = mimetypes.guess_type(logical_path)[0] or "application/octet-stream"
315
+ return ProcessedAttachment(logical_path, mime, "image", content, {"provider_mode": "image"})
316
+
317
+
318
+ class PDFAttachmentProcessor:
319
+ extensions = (".pdf",)
320
+ accepts_policy = True
321
+ version = "3"
322
+
323
+ def process(
324
+ self, logical_path: str, content: bytes, *, delivery: Delivery, policy: AttachmentPolicy | None = None
325
+ ) -> ProcessedAttachment | Iterable[ProcessedAttachment]:
326
+ policy = policy or AttachmentPolicy()
327
+ try:
328
+ import pymupdf
329
+ except ImportError as exc:
330
+ raise InputValidationError("PDF requer PyMuPDF; instale argos-cli[attachments]") from exc
331
+ try:
332
+ document = pymupdf.open(stream=content, filetype="pdf")
333
+ total = document.page_count
334
+ except Exception as exc: # noqa: BLE001 - PyMuPDF levanta tipos variados
335
+ raise InputValidationError(f"PDF ilegível: {exc}") from exc
336
+ try:
337
+ if total == 0:
338
+ raise InputValidationError("PDF sem páginas")
339
+ keep = total if policy.max_pdf_pages == 0 else min(total, policy.max_pdf_pages)
340
+ gaps: list[dict[str, Any]] = []
341
+ if keep < total:
342
+ gaps.append(_gap(logical_path, "paginas_truncadas", enviadas=keep, total=total))
343
+ base = {"pages_total": total, "pages_sent": keep}
344
+ if delivery.pdf == "native":
345
+ data = content
346
+ if keep < total:
347
+ cut = pymupdf.open()
348
+ try:
349
+ cut.insert_pdf(document, from_page=0, to_page=keep - 1)
350
+ data = cut.tobytes()
351
+ finally:
352
+ cut.close()
353
+ return ProcessedAttachment(
354
+ logical_path,
355
+ "application/pdf",
356
+ "native",
357
+ data,
358
+ {"provider_mode": "native-upload", **base, "gaps": gaps},
359
+ )
360
+ return self._text_parts(logical_path, content, document, keep, base, gaps, policy, delivery)
361
+ finally:
362
+ document.close()
363
+
364
+ _MIN_TEXT_CHARS = 20
365
+
366
+ def _text_parts(
367
+ self,
368
+ logical_path: str,
369
+ content: bytes,
370
+ document: Any,
371
+ keep: int,
372
+ base: dict[str, Any],
373
+ gaps: list[dict[str, Any]],
374
+ policy: AttachmentPolicy,
375
+ delivery: Delivery = Delivery(),
376
+ ) -> list[ProcessedAttachment]:
377
+ """Texto para modelos sem PDF nativo.
378
+
379
+ Páginas com camada de texto usam o texto nativo (rápido); só as páginas sem
380
+ texto passam por OCR do Tesseract, chamado pelo próprio PyMuPDF (lento). As imagens
381
+ embutidas são extraídas, deduplicadas e filtradas por tamanho.
382
+ """
383
+ pieces: dict[int, str] = {}
384
+ scanned: list[int] = []
385
+ try:
386
+ for number in range(keep):
387
+ text = document[number].get_text("text", sort=True).strip()
388
+ if len("".join(text.split())) >= self._MIN_TEXT_CHARS:
389
+ pieces[number] = text
390
+ else:
391
+ scanned.append(number)
392
+ except Exception as exc: # noqa: BLE001 - PDF protegido ou corrompido
393
+ raise InputValidationError(f"PDF ilegível: {type(exc).__name__}: {exc}") from exc
394
+ use_ocr = False
395
+ ocr_language = None
396
+ if scanned:
397
+ use_ocr = policy.ocr and shutil.which("tesseract") is not None
398
+ if use_ocr:
399
+ recognized, ocr_language = self._ocr_pages(document, scanned)
400
+ pieces.update(recognized)
401
+ if ocr_language != _OCR_LANGUAGE and not os.environ.get("ARGOS_OCR_LANG", "").strip():
402
+ gaps.append(
403
+ _gap(
404
+ logical_path,
405
+ "ocr_sem_idioma_portugues",
406
+ idioma=ocr_language,
407
+ motivo="dados do Tesseract em português ausentes; acentos podem sair errados",
408
+ )
409
+ )
410
+ missing = [number for number in scanned if number not in pieces]
411
+ if missing:
412
+ gaps.append(
413
+ _gap(
414
+ logical_path,
415
+ "paginas_sem_texto",
416
+ quantidade=len(missing),
417
+ paginas=[number + 1 for number in missing[:50]],
418
+ ocr=use_ocr,
419
+ )
420
+ )
421
+ embedded = self._embedded_images(document, keep)
422
+ if embedded and not delivery.images:
423
+ gaps.append(
424
+ _gap(logical_path, "imagens_nao_enviadas", quantidade=len(embedded), motivo="modelo sem entrada de imagem")
425
+ )
426
+ embedded = []
427
+ pages_by_name = {name: page for name, _, page in embedded}
428
+ images, _, counts = dedupe_and_filter_derived_images(
429
+ [(name, data) for name, data, _ in embedded], None, policy
430
+ )
431
+ if counts["pequenas"]:
432
+ gaps.append(
433
+ _gap(
434
+ logical_path,
435
+ "imagens_pequenas_descartadas",
436
+ quantidade=counts["pequenas"],
437
+ limite_bytes=policy.min_image_bytes,
438
+ )
439
+ )
440
+ if not pieces and not images:
441
+ raise InputValidationError(
442
+ "PDF sem texto extraível mesmo com OCR"
443
+ if use_ocr
444
+ else "PDF sem texto extraível (OCR indisponível ou desligado)"
445
+ )
446
+ text = "\n\n".join(f"[página {number + 1}]\n{pieces[number]}" for number in sorted(pieces))
447
+ parts: list[ProcessedAttachment] = [
448
+ ProcessedAttachment(
449
+ logical_path,
450
+ "text/plain",
451
+ "text",
452
+ text,
453
+ {
454
+ "processor": "pymupdf+tesseract" if use_ocr else "pymupdf",
455
+ "provider_mode": "pdf-text",
456
+ "ocr": use_ocr,
457
+ "ocr_language": ocr_language,
458
+ "ocr_pages": [number + 1 for number in scanned if number in pieces] if use_ocr else [],
459
+ "duplicate_images_removed": counts["duplicadas"],
460
+ **base,
461
+ "gaps": gaps,
462
+ },
463
+ )
464
+ ]
465
+ for name, data in images:
466
+ mime = mimetypes.guess_type(name)[0] or "image/png"
467
+ parts.append(
468
+ ProcessedAttachment(
469
+ f"{logical_path}#img/{name}",
470
+ mime,
471
+ "image",
472
+ data,
473
+ {
474
+ "processor": "pymupdf",
475
+ "provider_mode": "pdf-embedded-image",
476
+ "derived": True,
477
+ "parent": logical_path,
478
+ "page": pages_by_name.get(name),
479
+ },
480
+ )
481
+ )
482
+ return parts
483
+
484
+ @staticmethod
485
+ def _ocr_language(pymupdf: Any) -> str:
486
+ """Idioma do Tesseract: `ARGOS_OCR_LANG` manda; senão português, se instalado, ou inglês."""
487
+ override = os.environ.get("ARGOS_OCR_LANG", "").strip()
488
+ if override:
489
+ return override
490
+ try:
491
+ installed = {item.stem for item in Path(pymupdf.get_tessdata()).glob("*.traineddata")}
492
+ except Exception: # noqa: BLE001 - sem tessdata, o erro real aparece na chamada do OCR
493
+ installed = set()
494
+ return _OCR_LANGUAGE if _OCR_LANGUAGE in installed else _OCR_FALLBACK_LANGUAGE
495
+
496
+ @staticmethod
497
+ def _ocr_pages(document: Any, pages: list[int]) -> tuple[dict[int, str], str]:
498
+ """OCR do Tesseract só nas páginas sem texto; devolve o texto por página e o idioma usado.
499
+
500
+ Chama o OCR do próprio PyMuPDF, sem ``pymupdf4llm``: o texto sai simples, como o das páginas
501
+ com camada de texto, e o idioma é escolhido aqui (o ``pymupdf4llm`` fixa o inglês, que perde
502
+ os acentos do português).
503
+ """
504
+ import pymupdf
505
+
506
+ language = PDFAttachmentProcessor._ocr_language(pymupdf)
507
+ result: dict[int, str] = {}
508
+ # O MuPDF escreve mensagens por `pymupdf.message()` (stdout real do processo). O destino das
509
+ # mensagens e o redirecionamento são globais, por isso o OCR é serializado; depois dele as
510
+ # mensagens passam a ir para stderr, nunca para o stdout que carrega a saída `--json`.
511
+ with _PDF_CONVERSION_LOCK, contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
512
+ pymupdf.set_messages(stream=io.StringIO())
513
+ try:
514
+ for number in pages:
515
+ page = document[number] # referência viva: o PyMuPDF só guarda referência fraca
516
+ textpage = page.get_textpage_ocr(language=language, dpi=_OCR_DPI, full=True)
517
+ text = page.get_text("text", textpage=textpage, sort=True).strip()
518
+ if text:
519
+ result[number] = text
520
+ except Exception as exc: # noqa: BLE001 - o motivo real precisa chegar ao relatório
521
+ raise InputValidationError(f"falha no OCR do PDF: {type(exc).__name__}: {exc}") from exc
522
+ finally:
523
+ pymupdf.set_messages(stream=sys.stderr)
524
+ return result, language
525
+
526
+ @staticmethod
527
+ def _embedded_images(document: Any, keep: int) -> list[tuple[str, bytes, int]]:
528
+ """Imagens embutidas das páginas enviadas, como PNG/JPEG, sem repetir o mesmo objeto."""
529
+ import pymupdf
530
+
531
+ found: list[tuple[str, bytes, int]] = []
532
+ seen: set[int] = set()
533
+ for number in range(keep):
534
+ for item in document[number].get_images(full=True):
535
+ xref = int(item[0])
536
+ if xref in seen:
537
+ continue
538
+ seen.add(xref)
539
+ try:
540
+ info = document.extract_image(xref)
541
+ if not info:
542
+ continue
543
+ data, ext = info["image"], str(info.get("ext") or "").casefold()
544
+ if ext not in {"png", "jpeg", "jpg"}:
545
+ pixmap = pymupdf.Pixmap(document, xref)
546
+ if pixmap.alpha or (pixmap.colorspace and pixmap.colorspace.n not in (1, 3)):
547
+ pixmap = pymupdf.Pixmap(pymupdf.csRGB, pixmap)
548
+ data, ext = pixmap.tobytes("png"), "png"
549
+ except Exception: # noqa: BLE001 - imagem ilegível não bloqueia o texto
550
+ continue
551
+ found.append((f"pagina-{number + 1}-{xref}.{'jpg' if ext == 'jpeg' else ext}", data, number + 1))
552
+ return found
553
+
554
+
555
+ class DOCXAttachmentProcessor:
556
+ extensions = (".docx",)
557
+ accepts_policy = True
558
+ version = "2"
559
+
560
+ def process(
561
+ self, logical_path: str, content: bytes, *, delivery: Delivery, policy: AttachmentPolicy | None = None
562
+ ) -> ProcessedAttachment | Iterable[ProcessedAttachment]:
563
+ policy = policy or AttachmentPolicy()
564
+ with_images = delivery.images
565
+ try:
566
+ import mammoth
567
+
568
+ html = mammoth.convert_to_html(io.BytesIO(content)).value
569
+ prepared = ProcessedAttachment(
570
+ logical_path,
571
+ "text/html",
572
+ "html",
573
+ html,
574
+ {"processor": "mammoth", "provider_mode": "docx2html"},
575
+ )
576
+ except Exception: # noqa: BLE001 - tenta o leitor alternativo
577
+ try:
578
+ from docx import Document
579
+
580
+ document = Document(io.BytesIO(content))
581
+ text = "\n".join(paragraph.text for paragraph in document.paragraphs)
582
+ if not text.strip():
583
+ raise ValueError("DOCX sem texto de parágrafos")
584
+ prepared = ProcessedAttachment(
585
+ logical_path,
586
+ "text/plain",
587
+ "text",
588
+ text,
589
+ {"processor": "python-docx", "provider_mode": "docx-text"},
590
+ )
591
+ except Exception as exc:
592
+ raise InputValidationError(f"DOCX não pôde ser preparado: {exc}") from exc
593
+ if not with_images:
594
+ return prepared
595
+ images, gaps = self._extract_images(logical_path, content, policy)
596
+ if gaps:
597
+ prepared = replace(prepared, metadata={**prepared.metadata, "gaps": gaps})
598
+ return [prepared, *images]
599
+
600
+ @staticmethod
601
+ def _extract_images(
602
+ logical_path: str, content: bytes, policy: AttachmentPolicy
603
+ ) -> tuple[list[ProcessedAttachment], list[dict[str, Any]]]:
604
+ raw: list[tuple[str, bytes]] = []
605
+ try:
606
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
607
+ for member in archive.infolist():
608
+ name = member.filename.replace("\\", "/")
609
+ if not name.casefold().startswith("word/media/") or member.is_dir():
610
+ continue
611
+ raw.append((name, archive.read(member)))
612
+ except (zipfile.BadZipFile, OSError):
613
+ return [], []
614
+ unique, _, counts = dedupe_and_filter_derived_images(
615
+ [(str(index), data) for index, (_, data) in enumerate(raw)], None, policy
616
+ )
617
+ images: list[ProcessedAttachment] = []
618
+ for key, data in unique:
619
+ original = raw[int(key)][0]
620
+ mime = mimetypes.guess_type(original)[0] or "application/octet-stream"
621
+ images.append(
622
+ ProcessedAttachment(
623
+ f"{logical_path}!{original}",
624
+ mime,
625
+ "image",
626
+ data,
627
+ {"processor": "docx-zip", "provider_mode": "docx-image", "derived": True, "parent": logical_path},
628
+ )
629
+ )
630
+ gaps: list[dict[str, Any]] = []
631
+ if counts["pequenas"]:
632
+ gaps.append(
633
+ _gap(
634
+ logical_path,
635
+ "imagens_pequenas_descartadas",
636
+ quantidade=counts["pequenas"],
637
+ limite_bytes=policy.min_image_bytes,
638
+ )
639
+ )
640
+ return images, gaps
641
+
642
+
643
+ class XLSXAttachmentProcessor:
644
+ extensions = (".xlsx", ".xlsm")
645
+ accepts_policy = True
646
+ version = "2"
647
+
648
+ def process(
649
+ self, logical_path: str, content: bytes, *, delivery: Delivery, policy: AttachmentPolicy | None = None
650
+ ) -> ProcessedAttachment:
651
+ policy = policy or AttachmentPolicy()
652
+ sheets: dict[str, list[list[Any]]] = {}
653
+ hidden: list[str] = []
654
+ gaps: list[dict[str, Any]] = []
655
+ try:
656
+ workbook = openpyxl_workbook()(io.BytesIO(content), read_only=True, data_only=True)
657
+ try:
658
+ for worksheet in workbook.worksheets:
659
+ if worksheet.sheet_state != "visible":
660
+ hidden.append(worksheet.title)
661
+ continue
662
+ rows: list[list[Any]] = []
663
+ total = 0
664
+ for values in worksheet.iter_rows(values_only=True):
665
+ if not row_has_values(values):
666
+ continue
667
+ total += 1
668
+ if policy.max_sheet_rows == 0 or len(rows) < policy.max_sheet_rows:
669
+ rows.append(list(values))
670
+ if total > len(rows):
671
+ gaps.append(
672
+ _gap(
673
+ logical_path,
674
+ "linhas_truncadas",
675
+ aba=worksheet.title,
676
+ enviadas=len(rows),
677
+ total=total,
678
+ )
679
+ )
680
+ sheets[worksheet.title] = rows
681
+ finally:
682
+ workbook.close()
683
+ except Exception as exc:
684
+ raise InputValidationError(f"XLSX não pôde ser preparado: {exc}") from exc
685
+ if not sheets:
686
+ raise InputValidationError("planilha sem abas visíveis")
687
+ return ProcessedAttachment(
688
+ logical_path,
689
+ "application/json",
690
+ "structured",
691
+ json.dumps(sheets, ensure_ascii=False, default=str),
692
+ {
693
+ "processor": "openpyxl",
694
+ "provider_mode": "xlsx-structured",
695
+ "abas_ocultas_ignoradas": hidden,
696
+ "gaps": gaps,
697
+ },
698
+ )
699
+
700
+
701
+ @dataclass
702
+ class _Collector:
703
+ """Estado mutável de uma preparação: partes, pendências e dedup por hash."""
704
+
705
+ processed: list[ProcessedAttachment] = field(default_factory=list)
706
+ pending: list[AttachmentIssue] = field(default_factory=list)
707
+ ignored: list[AttachmentIssue] = field(default_factory=list)
708
+ seen: dict[str, str] = field(default_factory=dict)
709
+
710
+
711
+ class AttachmentProcessingService:
712
+ """Expande ZIP/RAR aninhados e prepara arquivos; pendências ficam no relatório."""
713
+
714
+ _ignored_names = {".ds_store", "thumbs.db"}
715
+ _ignored_suffixes = (".db", ".tmp", ".temp", ".bak", ".swp", ".lock")
716
+ _office_targets = {".doc": ("pdf", ".pdf"), ".pptx": ("pdf", ".pdf"), ".ods": ("xlsx", ".xlsx")}
717
+
718
+ def __init__(
719
+ self,
720
+ processors: Iterable[AttachmentProcessor] | None = None,
721
+ *,
722
+ max_depth: int = 8,
723
+ max_member_bytes: int = 100 * 1024 * 1024,
724
+ cache_entries: int = 128,
725
+ cache_bytes: int = 256 * 1024 * 1024,
726
+ office_converter: Callable[..., bytes] | None = None,
727
+ rar_extractor: Callable[[bytes], list[tuple[str, bytes]]] | None = None,
728
+ url_fetcher: Any = None,
729
+ ) -> None:
730
+ defaults: tuple[AttachmentProcessor, ...] = (
731
+ TextAttachmentProcessor(),
732
+ ImageAttachmentProcessor(),
733
+ PDFAttachmentProcessor(),
734
+ DOCXAttachmentProcessor(),
735
+ XLSXAttachmentProcessor(),
736
+ )
737
+ self.processors = tuple(processors or defaults)
738
+ self._by_extension = {
739
+ extension: processor
740
+ for processor in self.processors
741
+ for extension in processor.extensions
742
+ }
743
+ self.max_depth = max_depth
744
+ self.max_member_bytes = max_member_bytes
745
+ self.cache_entries = max(0, int(cache_entries))
746
+ self.cache_bytes = max(0, int(cache_bytes))
747
+ self._office_converter = office_converter or convert_office_bytes
748
+ self._rar_extractor = rar_extractor or extract_rar_members
749
+ self._url_fetcher = url_fetcher or UrlFetcher()
750
+ self._cache: OrderedDict[
751
+ tuple[Any, ...],
752
+ tuple[AttachmentReport, tuple[tuple[str, str, str], ...], int],
753
+ ] = OrderedDict()
754
+ self._cache_total_bytes = 0
755
+ self._inflight: dict[tuple[Any, ...], threading.Event] = {}
756
+ self._cache_lock = threading.Lock()
757
+
758
+ def prepare(
759
+ self,
760
+ paths: Iterable[str | Path],
761
+ *,
762
+ delivery: Delivery | None = None,
763
+ policy: AttachmentPolicy | None = None,
764
+ ) -> AttachmentReport:
765
+ delivery = delivery or Delivery()
766
+ policy = policy or AttachmentPolicy()
767
+ paths = tuple(Path(raw).expanduser() for raw in paths)
768
+ cache_key, sources = self._cache_key(paths, delivery, policy=policy)
769
+ if self.cache_entries and self.cache_bytes:
770
+ while True:
771
+ with self._cache_lock:
772
+ cached = self._cache.get(cache_key)
773
+ if cached is not None:
774
+ self._cache.move_to_end(cache_key)
775
+ return self._rebind_report(cached[0], cached[1], sources)
776
+ pending = self._inflight.get(cache_key)
777
+ if pending is None:
778
+ pending = threading.Event()
779
+ self._inflight[cache_key] = pending
780
+ owner = True
781
+ else:
782
+ owner = False
783
+ if owner:
784
+ break
785
+ pending.wait()
786
+ try:
787
+ report = self._prepare_uncached(sources, delivery=delivery, policy=policy)
788
+ except Exception:
789
+ with self._cache_lock:
790
+ event = self._inflight.pop(cache_key, None)
791
+ if event is not None:
792
+ event.set()
793
+ raise
794
+ if self.cache_entries and self.cache_bytes:
795
+ report_size = self._report_size(report)
796
+ with self._cache_lock:
797
+ while self._cache and (
798
+ len(self._cache) >= self.cache_entries
799
+ or self._cache_total_bytes + report_size > self.cache_bytes
800
+ ):
801
+ _, (_, _, evicted_size) = self._cache.popitem(last=False)
802
+ self._cache_total_bytes -= evicted_size
803
+ if report_size <= self.cache_bytes:
804
+ descriptors = tuple(
805
+ (path.name, path.suffix.casefold(), digest)
806
+ for path, _, digest in sources
807
+ )
808
+ self._cache[cache_key] = (report, descriptors, report_size)
809
+ self._cache_total_bytes += report_size
810
+ event = self._inflight.pop(cache_key, None)
811
+ if event is not None:
812
+ event.set()
813
+ return report
814
+
815
+ def _prepare_uncached(
816
+ self,
817
+ sources: Iterable[tuple[Path, bytes | None, str]],
818
+ *,
819
+ delivery: Delivery,
820
+ policy: AttachmentPolicy,
821
+ ) -> AttachmentReport:
822
+ state = _Collector()
823
+ for path, content, digest in sources:
824
+ if content is None and digest == "missing":
825
+ state.pending.append(AttachmentIssue(str(path), "arquivo ausente"))
826
+ continue
827
+ if content is None:
828
+ state.pending.append(AttachmentIssue(str(path), "não é arquivo"))
829
+ continue
830
+ try:
831
+ self._visit(content, path.name, delivery, policy, depth=0, state=state)
832
+ except Exception as exc: # noqa: BLE001 - a pendência fica registrada e bloqueia o pedido
833
+ state.pending.append(AttachmentIssue(str(path), f"falha ao abrir: {exc}"))
834
+ gaps = [dict(gap) for part in state.processed for gap in part.metadata.get("gaps", ())]
835
+ processed, duplicates, cap_gaps = self._limit_images(state.processed, policy)
836
+ return AttachmentReport(
837
+ tuple(processed),
838
+ tuple(state.pending),
839
+ tuple((*state.ignored, *duplicates)),
840
+ tuple((*gaps, *cap_gaps)),
841
+ )
842
+
843
+ @staticmethod
844
+ def _limit_images(
845
+ processed: list[ProcessedAttachment], policy: AttachmentPolicy
846
+ ) -> tuple[list[ProcessedAttachment], list[AttachmentIssue], list[dict[str, Any]]]:
847
+ """Dedup global de imagens por hash e teto de imagens por requisição."""
848
+ seen: dict[str, str] = {}
849
+ kept: list[ProcessedAttachment] = []
850
+ duplicates: list[AttachmentIssue] = []
851
+ for part in processed:
852
+ if part.kind != "image":
853
+ kept.append(part)
854
+ continue
855
+ raw = part.content.encode("utf-8") if isinstance(part.content, str) else part.content
856
+ digest = sha256_bytes(raw)
857
+ if digest in seen:
858
+ duplicates.append(
859
+ AttachmentIssue(part.logical_path, f"imagem duplicada: idêntica a {seen[digest]}", digest)
860
+ )
861
+ continue
862
+ seen[digest] = part.logical_path
863
+ kept.append(part)
864
+ gaps: list[dict[str, Any]] = []
865
+ images = [part for part in kept if part.kind == "image"]
866
+ cap = policy.max_images_per_request
867
+ if cap > 0 and len(images) > cap:
868
+ allowed = {id(part) for part in images[:cap]}
869
+ dropped = images[cap:]
870
+ kept = [part for part in kept if part.kind != "image" or id(part) in allowed]
871
+ gaps.append(
872
+ {
873
+ "tipo": "imagens_truncadas",
874
+ "enviadas": cap,
875
+ "descartadas": len(dropped),
876
+ "arquivos": sorted({str(part.metadata.get("parent") or part.logical_path) for part in dropped}),
877
+ }
878
+ )
879
+ return kept, duplicates, gaps
880
+
881
+ def _cache_key(
882
+ self,
883
+ paths: tuple[Path, ...],
884
+ delivery: Delivery,
885
+ *,
886
+ policy: AttachmentPolicy | None = None,
887
+ ) -> tuple[tuple[Any, ...], tuple[tuple[Path, bytes | None, str], ...]]:
888
+ sources: list[tuple[Path, bytes | None, str]] = []
889
+ files: list[tuple[str, str]] = []
890
+ for path in paths:
891
+ try:
892
+ if not path.exists():
893
+ sources.append((path, None, "missing"))
894
+ files.append((path.suffix.casefold(), "missing"))
895
+ elif not path.is_file():
896
+ sources.append((path, None, "not-file"))
897
+ files.append((path.suffix.casefold(), "not-file"))
898
+ else:
899
+ content = path.read_bytes()
900
+ digest = sha256_bytes(content)
901
+ sources.append((path, content, digest))
902
+ files.append((path.suffix.casefold(), digest))
903
+ except OSError:
904
+ sources.append((path, None, "missing"))
905
+ files.append((path.suffix.casefold(), "missing"))
906
+ processor_profile = tuple(
907
+ sorted(
908
+ (
909
+ type(processor).__module__,
910
+ type(processor).__qualname__,
911
+ str(getattr(processor, "version", "1")),
912
+ tuple(sorted(processor.extensions)),
913
+ )
914
+ for processor in self.processors
915
+ )
916
+ )
917
+ return (
918
+ (
919
+ delivery,
920
+ processor_profile,
921
+ tuple(sorted(files)),
922
+ self.max_depth,
923
+ self.max_member_bytes,
924
+ (policy or AttachmentPolicy()).processing_key(),
925
+ ),
926
+ tuple(sources),
927
+ )
928
+
929
+ @staticmethod
930
+ def _report_size(report: AttachmentReport) -> int:
931
+ size = 0
932
+ for item in report.processed:
933
+ content = item.content.encode("utf-8") if isinstance(item.content, str) else item.content
934
+ size += len(content)
935
+ size += sum(len(item.logical_path) + len(item.reason) for item in (*report.pending, *report.ignored))
936
+ return size
937
+
938
+ @staticmethod
939
+ def _rebind_report(
940
+ report: AttachmentReport,
941
+ cached_sources: tuple[tuple[str, str, str], ...],
942
+ current_sources: tuple[tuple[Path, bytes | None, str], ...],
943
+ ) -> AttachmentReport:
944
+ names: dict[tuple[str, str], deque[str]] = defaultdict(deque)
945
+ for path, _, digest in current_sources:
946
+ names[(path.suffix.casefold(), digest)].append(path.name)
947
+ replacements: dict[str, str] = {}
948
+ for old_name, suffix, digest in cached_sources:
949
+ bucket = names[(suffix, digest)]
950
+ replacements[old_name] = bucket.popleft() if bucket else old_name
951
+
952
+ def logical_path(value: str) -> str:
953
+ for old_name, new_name in replacements.items():
954
+ if value == old_name:
955
+ return new_name
956
+ if value.startswith(old_name + "!") or value.startswith(old_name + "#"):
957
+ return new_name + value[len(old_name) :]
958
+ if Path(value).name == old_name:
959
+ return str(Path(value).with_name(new_name))
960
+ return value
961
+
962
+ def gap(item: Mapping[str, Any]) -> Mapping[str, Any]:
963
+ result = dict(item)
964
+ if isinstance(result.get("arquivo"), str):
965
+ result["arquivo"] = logical_path(result["arquivo"])
966
+ if isinstance(result.get("arquivos"), list):
967
+ result["arquivos"] = [logical_path(str(value)) for value in result["arquivos"]]
968
+ return result
969
+
970
+ return AttachmentReport(
971
+ processed=tuple(
972
+ ProcessedAttachment(
973
+ logical_path(item.logical_path),
974
+ item.mime_type,
975
+ item.kind,
976
+ item.content,
977
+ {
978
+ **item.metadata,
979
+ **({"parent": logical_path(str(item.metadata["parent"]))} if "parent" in item.metadata else {}),
980
+ **({"gaps": [gap(entry) for entry in item.metadata["gaps"]]} if item.metadata.get("gaps") else {}),
981
+ },
982
+ )
983
+ for item in report.processed
984
+ ),
985
+ pending=tuple(
986
+ AttachmentIssue(logical_path(item.logical_path), item.reason, item.sha256)
987
+ for item in report.pending
988
+ ),
989
+ ignored=tuple(
990
+ AttachmentIssue(logical_path(item.logical_path), item.reason, item.sha256)
991
+ for item in report.ignored
992
+ ),
993
+ gaps=tuple(gap(item) for item in report.gaps),
994
+ )
995
+
996
+ def _process_with(
997
+ self,
998
+ processor: AttachmentProcessor,
999
+ content: bytes,
1000
+ logical_path: str,
1001
+ delivery: Delivery,
1002
+ policy: AttachmentPolicy,
1003
+ extra: Mapping[str, Any] | None = None,
1004
+ ) -> list[ProcessedAttachment]:
1005
+ if getattr(processor, "accepts_policy", False):
1006
+ prepared = processor.process(logical_path, content, delivery=delivery, policy=policy) # type: ignore[call-arg]
1007
+ else:
1008
+ prepared = processor.process(logical_path, content, delivery=delivery)
1009
+ parts = [prepared] if isinstance(prepared, ProcessedAttachment) else list(prepared)
1010
+ if extra:
1011
+ parts = [replace(part, metadata={**part.metadata, **extra}) for part in parts]
1012
+ return parts
1013
+
1014
+ def _visit(
1015
+ self,
1016
+ content: bytes,
1017
+ logical_path: str,
1018
+ delivery: Delivery,
1019
+ policy: AttachmentPolicy,
1020
+ *,
1021
+ depth: int,
1022
+ state: _Collector,
1023
+ ) -> None:
1024
+ digest = sha256_bytes(content)
1025
+ basename = Path(logical_path).name.casefold()
1026
+ suffix = Path(logical_path).suffix.casefold()
1027
+ if basename in self._ignored_names or suffix in self._ignored_suffixes or "__macosx" in logical_path.casefold():
1028
+ state.ignored.append(AttachmentIssue(logical_path, "regra explícita de arquivo ignorável", digest))
1029
+ return
1030
+ if depth > self.max_depth:
1031
+ state.pending.append(
1032
+ AttachmentIssue(logical_path, f"profundidade máxima de arquivo compactado excedida ({self.max_depth})", digest)
1033
+ )
1034
+ return
1035
+ first = state.seen.get(digest)
1036
+ if depth > 0 and first is not None:
1037
+ state.ignored.append(AttachmentIssue(logical_path, f"duplicado: idêntico a {first}", digest))
1038
+ return
1039
+ state.seen.setdefault(digest, logical_path)
1040
+ if suffix == ".zip":
1041
+ try:
1042
+ archive = zipfile.ZipFile(io.BytesIO(content))
1043
+ except (zipfile.BadZipFile, OSError) as exc:
1044
+ state.pending.append(AttachmentIssue(logical_path, f"ZIP não pôde ser expandido: {exc}", digest))
1045
+ return
1046
+ with archive:
1047
+ members = [
1048
+ (member.filename, member.file_size, (lambda member=member: archive.read(member)))
1049
+ for member in archive.infolist()
1050
+ if not member.is_dir()
1051
+ ]
1052
+ self._visit_members("ZIP", logical_path, members, delivery, policy, depth, state)
1053
+ return
1054
+ if suffix == ".rar":
1055
+ try:
1056
+ extracted = self._rar_extractor(content)
1057
+ except Exception as exc: # noqa: BLE001 - ferramenta ausente ou arquivo inválido
1058
+ state.pending.append(AttachmentIssue(logical_path, f"RAR não pôde ser expandido: {exc}", digest))
1059
+ return
1060
+ members = [(name, len(data), (lambda data=data: data)) for name, data in extracted]
1061
+ self._visit_members("RAR", logical_path, members, delivery, policy, depth, state)
1062
+ return
1063
+ if suffix == ".url":
1064
+ try:
1065
+ from .url_fetch import parse_url_shortcut
1066
+
1067
+ url = parse_url_shortcut(content)
1068
+ name, data, _ = self._url_fetcher.fetch(url)
1069
+ except Exception as exc: # noqa: BLE001 - qualquer recusa vira pendência
1070
+ state.pending.append(AttachmentIssue(logical_path, f"download recusado: {exc}", digest))
1071
+ return
1072
+ before = len(state.processed)
1073
+ self._visit(data, f"{logical_path}!{name}", delivery, policy, depth=depth + 1, state=state)
1074
+ for index in range(before, len(state.processed)):
1075
+ part = state.processed[index]
1076
+ state.processed[index] = replace(part, metadata={**part.metadata, "source_url": url})
1077
+ return
1078
+ extra: dict[str, Any] | None = None
1079
+ effective_suffix = suffix
1080
+ if suffix in self._office_targets:
1081
+ target, effective_suffix = self._office_targets[suffix]
1082
+ try:
1083
+ content = self._office_converter(content, suffix=suffix, target=target)
1084
+ except Exception as exc: # noqa: BLE001 - conversão falha vira pendência
1085
+ state.pending.append(AttachmentIssue(logical_path, str(exc), digest))
1086
+ return
1087
+ extra = {"converted_from": suffix}
1088
+ processor = self._by_extension.get(effective_suffix)
1089
+ if processor is None:
1090
+ state.pending.append(
1091
+ AttachmentIssue(
1092
+ logical_path,
1093
+ f"formato sem suporte explícito: {suffix or 'extensão sem nome'}",
1094
+ digest,
1095
+ )
1096
+ )
1097
+ return
1098
+ try:
1099
+ state.processed.extend(self._process_with(processor, content, logical_path, delivery, policy, extra))
1100
+ except Exception as exc: # noqa: BLE001 - a pendência bloqueia o pedido com o motivo real
1101
+ state.pending.append(AttachmentIssue(logical_path, str(exc), digest))
1102
+
1103
+ def _visit_members(
1104
+ self,
1105
+ label: str,
1106
+ logical_path: str,
1107
+ members: Iterable[tuple[str, int, Callable[[], bytes]]],
1108
+ delivery: Delivery,
1109
+ policy: AttachmentPolicy,
1110
+ depth: int,
1111
+ state: _Collector,
1112
+ ) -> None:
1113
+ members = list(members)
1114
+ if not members:
1115
+ state.pending.append(AttachmentIssue(logical_path, f"{label} sem arquivos"))
1116
+ return
1117
+ for name, size, reader in members:
1118
+ if size > self.max_member_bytes:
1119
+ state.pending.append(
1120
+ AttachmentIssue(
1121
+ f"{logical_path}!{name}", f"membro excede limite de {self.max_member_bytes} bytes"
1122
+ )
1123
+ )
1124
+ continue
1125
+ member_name = safe_member_name(name)
1126
+ if member_name is None:
1127
+ state.pending.append(AttachmentIssue(f"{logical_path}!{name}", f"caminho inseguro no {label}"))
1128
+ continue
1129
+ try:
1130
+ data = reader()
1131
+ except Exception as exc: # noqa: BLE001 - membro corrompido ou protegido
1132
+ state.pending.append(AttachmentIssue(f"{logical_path}!{member_name}", f"membro ilegível no {label}: {exc}"))
1133
+ continue
1134
+ self._visit(data, f"{logical_path}!{member_name}", delivery, policy, depth=depth + 1, state=state)
1135
+
1136
+ @staticmethod
1137
+ def _safe_member_name(name: str) -> str | None:
1138
+ return safe_member_name(name)
1139
+
1140
+
1141
+ @dataclass(frozen=True)
1142
+ class AIRequest:
1143
+ prompt: str
1144
+ subject: Mapping[str, Any] = field(default_factory=dict)
1145
+ context: Mapping[str, Any] = field(default_factory=dict)
1146
+ attachments: tuple[ProcessedAttachment, ...] = ()
1147
+ schema: Mapping[str, Any] = field(default_factory=dict)
1148
+ response_profile: str = "evidence"
1149
+ provider: str = "fake"
1150
+ model: str = "fake"
1151
+ metadata: Mapping[str, Any] = field(default_factory=dict)
1152
+ reasoning_level: str | None = None
1153
+ token_limit: int = 0
1154
+ # Aviso de andamento (retry, troca de chave); fica fora da identidade semântica da chamada.
1155
+ on_event: Callable[[str], None] | None = field(default=None, compare=False, repr=False)
1156
+
1157
+ def material_prompt(self) -> str:
1158
+ """Compõe o pacote textual comum sem esconder o contexto no caller."""
1159
+ sections = [self.prompt.rstrip()]
1160
+ if self.subject:
1161
+ sections.extend(
1162
+ (
1163
+ "Objeto estruturado da avaliação:",
1164
+ json.dumps(self.subject, ensure_ascii=False, sort_keys=True, default=str),
1165
+ )
1166
+ )
1167
+ if self.context:
1168
+ sections.extend(
1169
+ (
1170
+ "Contexto estruturado da avaliação:",
1171
+ json.dumps(self.context, ensure_ascii=False, sort_keys=True, default=str),
1172
+ )
1173
+ )
1174
+ return "\n\n".join(section for section in sections if section)
1175
+
1176
+
1177
+ _TEXT_KINDS = frozenset({"text", "markdown", "html", "structured"})
1178
+
1179
+
1180
+ def estimate_request_tokens(request: AIRequest) -> dict[str, int]:
1181
+ """Estimativa local de tokens: texto ≈ 1 token por 3,5 caracteres; imagem e página PDF ≈ 258."""
1182
+ text_chars = len(request.material_prompt())
1183
+ images = 0
1184
+ pdf_pages = 0
1185
+ for attachment in request.attachments:
1186
+ if attachment.kind in _TEXT_KINDS:
1187
+ text_chars += len(attachment.logical_path) + len(str(attachment.content))
1188
+ elif attachment.kind == "image":
1189
+ images += 1
1190
+ elif attachment.kind == "native":
1191
+ pdf_pages += max(1, int(attachment.metadata.get("pages_sent") or 1))
1192
+ text_tokens = math.ceil(text_chars / 3.5)
1193
+ return {
1194
+ "text_chars": text_chars,
1195
+ "text_tokens": text_tokens,
1196
+ "images": images,
1197
+ "image_tokens": images * IMAGE_TOKENS,
1198
+ "pdf_pages": pdf_pages,
1199
+ "pdf_tokens": pdf_pages * IMAGE_TOKENS,
1200
+ "total": text_tokens + images * IMAGE_TOKENS + pdf_pages * IMAGE_TOKENS,
1201
+ }
1202
+
1203
+
1204
+ @dataclass(frozen=True)
1205
+ class AIResponse:
1206
+ result: Mapping[str, Any]
1207
+ provider: str
1208
+ model: str
1209
+ status: str = "completed"
1210
+ raw: Mapping[str, Any] = field(default_factory=dict)
1211
+
1212
+
1213
+ class AIService(Protocol):
1214
+ def generate(self, request: AIRequest) -> AIResponse: ...
1215
+
1216
+
1217
+ class FakeAIService:
1218
+ """Adapter determinístico para preflight e testes sem custo externo.
1219
+
1220
+ A resposta vem do próprio *response profile* (``example``), então o provider falso
1221
+ nunca precisa conhecer a forma de cada contrato.
1222
+ """
1223
+
1224
+ def generate(self, request: AIRequest) -> AIResponse:
1225
+ prompt_hash = sha256_bytes(request.material_prompt().encode("utf-8"))
1226
+ codes = [str(item) for item in request.metadata.get("expected_item_codes") or []]
1227
+ if not codes:
1228
+ codes = [str(request.subject.get("item_codigo") or "item")]
1229
+ items = {
1230
+ str(item.get("codigo") or item.get("item_codigo") or ""): item
1231
+ for item in request.subject.get("itens") or []
1232
+ if isinstance(item, Mapping)
1233
+ }
1234
+
1235
+ def field(code: str, *names: str) -> str:
1236
+ item = items.get(code, {})
1237
+ return str(next((item[name] for name in names if item.get(name)), request.subject.get(names[-1]) or ""))
1238
+
1239
+ result = ResponseProfileRegistry().get(request.response_profile).example(
1240
+ codes,
1241
+ texts={code: field(code, "texto", "item_texto") for code in codes},
1242
+ assertions={code: field(code, "afirmacao", "afirmacao_auditado") for code in codes},
1243
+ files=[item.logical_path for item in request.attachments],
1244
+ reason_ids=[str(reason) for reason in request.metadata.get("expected_reason_ids") or []],
1245
+ )
1246
+ return AIResponse(
1247
+ result=result,
1248
+ provider=request.provider,
1249
+ model=request.model,
1250
+ raw={
1251
+ "adapter": "fake",
1252
+ "schema": dict(request.schema),
1253
+ "prompt_hash": prompt_hash,
1254
+ "attachment_count": len(request.attachments),
1255
+ },
1256
+ )
1257
+
1258
+
1259
+ _FENCED_JSON = re.compile(r"```(?:json)?\s*(.*?)```", re.IGNORECASE | re.DOTALL)
1260
+
1261
+
1262
+ def _decode_provider_result(value: Any) -> tuple[Mapping[str, Any], bool]:
1263
+ """Decodifica a resposta do modelo; devolve ``(resultado, reparado)``.
1264
+
1265
+ JSON malformado é reparado com ``json-repair``; a validação de schema do
1266
+ perfil de resposta continua sendo obrigatória depois.
1267
+ """
1268
+ if isinstance(value, Mapping):
1269
+ return dict(value), False
1270
+ text = str(value or "").strip()
1271
+ if not text:
1272
+ return {"status": "completed", "text": ""}, False
1273
+ fenced = _FENCED_JSON.search(text)
1274
+ candidate = fenced.group(1).strip() if fenced else text
1275
+ try:
1276
+ decoded: Any = json.loads(candidate)
1277
+ repaired = False
1278
+ except json.JSONDecodeError:
1279
+ try:
1280
+ from json_repair import repair_json
1281
+ except ImportError:
1282
+ return {"text": text}, False
1283
+ decoded = repair_json(candidate, return_objects=True)
1284
+ repaired = True
1285
+ if isinstance(decoded, Mapping):
1286
+ return dict(decoded), repaired
1287
+ if repaired:
1288
+ return {"text": text}, False
1289
+ return {"value": decoded}, False
1290
+
1291
+
1292
+ def _secret_values(explicit: str | None, *names: str) -> tuple[str, ...]:
1293
+ raw = explicit
1294
+ if not raw:
1295
+ for name in names:
1296
+ raw = os.environ.get(name)
1297
+ if raw:
1298
+ break
1299
+ if not raw:
1300
+ return ()
1301
+ return tuple(value.strip() for value in str(raw).split(",") if value.strip())
1302
+
1303
+
1304
+ def _credential_source(explicit: str | None, *names: str) -> str | None:
1305
+ if explicit:
1306
+ return "injected_adapter"
1307
+ for name in names:
1308
+ if os.environ.get(name):
1309
+ return f"environment:{name}"
1310
+ return None
1311
+
1312
+
1313
+ def safe_upload_name(name: str) -> str:
1314
+ """Nome ASCII seguro para a File API do Gemini, estável para o mesmo nome original."""
1315
+ path = Path(str(name) or "evidencia")
1316
+ stem = unicodedata.normalize("NFKD", path.stem).encode("ascii", "ignore").decode("ascii")
1317
+ stem = re.sub(r"[^A-Za-z0-9._-]+", "-", stem).strip("-._")[:60] or "evidencia"
1318
+ suffix = re.sub(r"[^a-z0-9.]", "", path.suffix.casefold())
1319
+ return f"{stem}-{sha256_bytes(str(name).encode('utf-8'))[:10]}{suffix}"
1320
+
1321
+
1322
+ class GeminiAIService:
1323
+ """Adapter Gemini baseado no SDK ``google-genai``.
1324
+
1325
+ PDFs e outros anexos nativos são enviados pelo File API em memória, com nome
1326
+ ASCII seguro. O identificador retornado pelo provider nunca é persistido e o
1327
+ arquivo é removido ao fim de cada tentativa quando a API permitir. Troca de
1328
+ chave, nova tentativa e timeout seguem a ``ModelCallPolicy`` comum.
1329
+ """
1330
+
1331
+ @staticmethod
1332
+ def capabilities(model: str) -> ModelCapabilities:
1333
+ return ModelCapabilities(
1334
+ pdf="native",
1335
+ token_limit=1_000_000,
1336
+ counts_tokens=True,
1337
+ reasoning_levels=("minimal", "low", "medium", "high"),
1338
+ )
1339
+
1340
+ def __init__(
1341
+ self,
1342
+ api_key: str | None = None,
1343
+ *,
1344
+ client_factory: Callable[[str], Any] | None = None,
1345
+ policy: ModelCallPolicy | None = None,
1346
+ ) -> None:
1347
+ names = ("GEMINI_API_KEY", "ARGOS_GEMINI_API_KEY")
1348
+ self._keys = _secret_values(api_key, *names)
1349
+ self._ring = KeyRing(self._keys)
1350
+ self.credential_source = _credential_source(api_key, *names)
1351
+ self._client_factory = client_factory
1352
+ self._policy = policy
1353
+
1354
+ @property
1355
+ def policy(self) -> ModelCallPolicy:
1356
+ """Política de chamada; o ambiente só é lido (e validado) no primeiro uso."""
1357
+ if self._policy is None:
1358
+ self._policy = ModelCallPolicy.from_env()
1359
+ return self._policy
1360
+
1361
+ def generate(self, request: AIRequest) -> AIResponse:
1362
+ try:
1363
+ from google import genai
1364
+ from google.genai import types
1365
+ except ImportError as exc: # pragma: no cover - depende do ambiente
1366
+ raise InputValidationError("provider gemini requer google-genai") from exc
1367
+ if not self._keys:
1368
+ raise InputValidationError("GEMINI_API_KEY não configurada; use provider=fake para preflight")
1369
+
1370
+ timeout_ms = int(self.policy.timeout * 1000)
1371
+ factory = self._client_factory or (
1372
+ lambda key: genai.Client(api_key=key, http_options=types.HttpOptions(timeout=timeout_ms))
1373
+ )
1374
+
1375
+ def send(key: str) -> AIResponse:
1376
+ client = factory(key)
1377
+ uploaded: list[Any] = []
1378
+ try:
1379
+ return self._generate_once(client, types, request, uploaded)
1380
+ finally:
1381
+ for uploaded_file in uploaded:
1382
+ name = getattr(uploaded_file, "name", None)
1383
+ if name:
1384
+ try:
1385
+ client.files.delete(name=name)
1386
+ except Exception: # noqa: BLE001, S110 - limpeza best effort
1387
+ pass
1388
+
1389
+ response, attempts = call_with_keys(
1390
+ send,
1391
+ self._ring,
1392
+ provider="gemini",
1393
+ policy=self.policy,
1394
+ secrets=self._keys,
1395
+ on_event=request.on_event,
1396
+ )
1397
+ return replace(response, raw={**response.raw, **raw_attempts(attempts)})
1398
+
1399
+ @staticmethod
1400
+ def _generate_once(client: Any, types: Any, request: AIRequest, uploaded: list[Any]) -> AIResponse:
1401
+ contents: list[Any] = [request.material_prompt()]
1402
+ for attachment in request.attachments:
1403
+ content = attachment.content
1404
+ raw = content.encode("utf-8") if isinstance(content, str) else content
1405
+ if attachment.kind == "native":
1406
+ file_obj = io.BytesIO(raw)
1407
+ file_obj.name = safe_upload_name(Path(attachment.logical_path).name or "attachment")
1408
+ uploaded_file = client.files.upload(
1409
+ file=file_obj,
1410
+ config={"mime_type": attachment.mime_type, "display_name": file_obj.name[:120]},
1411
+ )
1412
+ uploaded.append(uploaded_file)
1413
+ contents.append(uploaded_file)
1414
+ elif attachment.kind == "image":
1415
+ contents.append(types.Part.from_bytes(data=raw, mime_type=attachment.mime_type))
1416
+ else:
1417
+ contents.append(f"\n[{attachment.logical_path}]\n{content}")
1418
+ tokens_counted: int | None = None
1419
+ if request.token_limit > 0:
1420
+ counted = client.models.count_tokens(model=request.model, contents=contents)
1421
+ tokens_counted = int(getattr(counted, "total_tokens", 0) or 0)
1422
+ if tokens_counted > request.token_limit:
1423
+ raise AIServiceError(
1424
+ f"payload excede limite de tokens do Gemini: {tokens_counted} > {request.token_limit}",
1425
+ retryable=False,
1426
+ )
1427
+ config_kwargs: dict[str, Any] = {}
1428
+ if request.schema:
1429
+ config_kwargs.update(
1430
+ response_mime_type="application/json",
1431
+ response_json_schema=dict(request.schema),
1432
+ )
1433
+ if request.reasoning_level:
1434
+ config_kwargs["thinking_config"] = types.ThinkingConfig(thinking_level=request.reasoning_level)
1435
+ config = types.GenerateContentConfig(**config_kwargs) if config_kwargs else None
1436
+ response = client.models.generate_content(model=request.model, contents=contents, config=config)
1437
+ result, repaired = _decode_provider_result(getattr(response, "text", None))
1438
+ return AIResponse(
1439
+ result=result,
1440
+ provider="gemini",
1441
+ model=request.model,
1442
+ raw={
1443
+ "adapter": "google-genai",
1444
+ "uploaded_files": len(uploaded),
1445
+ "json_repaired": repaired,
1446
+ "tokens_counted": tokens_counted,
1447
+ },
1448
+ )
1449
+
1450
+
1451
+ class AIServiceRegistry:
1452
+ def __init__(self, adapters: Mapping[str, AIService] | None = None) -> None:
1453
+ from .ai_remote import (
1454
+ OpenAIProxyAIService,
1455
+ OpenCodeGoAIService,
1456
+ OpenCodeGoAnthropicAIService,
1457
+ OpenRouterAIService,
1458
+ )
1459
+
1460
+ defaults: dict[str, AIService] = {
1461
+ "fake": FakeAIService(),
1462
+ "gemini": GeminiAIService(),
1463
+ "opencodego": OpenCodeGoAIService(),
1464
+ "opencodego-ant": OpenCodeGoAnthropicAIService(),
1465
+ "openai-proxy": OpenAIProxyAIService(),
1466
+ "openrouter": OpenRouterAIService(),
1467
+ }
1468
+ for name, adapter in (adapters or {}).items():
1469
+ defaults[_provider_key(name)] = adapter
1470
+ self.adapters = defaults
1471
+
1472
+ def get(self, provider: str) -> AIService:
1473
+ key = _provider_key(provider)
1474
+ try:
1475
+ return self.adapters[key]
1476
+ except KeyError as exc:
1477
+ hint = "; o provider openai agora se chama openai-proxy" if key == "openai" else ""
1478
+ raise InputValidationError(
1479
+ f"provider {provider!r} não possui adapter instalado; use fake para preflight{hint}"
1480
+ ) from exc
1481
+
1482
+ def capabilities(self, provider: str, model: str) -> ModelCapabilities:
1483
+ """O que o modelo aceita; adapter que não declara herda o padrão permissivo."""
1484
+ hook = getattr(self.get(provider), "capabilities", None)
1485
+ return hook(model) if callable(hook) else ModelCapabilities()
1486
+
1487
+ def validate_reasoning(self, provider: str, model: str, level: str | None) -> None:
1488
+ """Recusa, antes de qualquer chamada, um nível que o provider declara não suportar."""
1489
+ level = normalize_reasoning_level(level)
1490
+ if level is None:
1491
+ return
1492
+ supported = self.capabilities(provider, model).reasoning_levels
1493
+ if supported is not None and level not in supported:
1494
+ raise InputValidationError(
1495
+ f"{provider}:{model} não suporta o nível de raciocínio {level!r}; "
1496
+ f"suportados: {', '.join(supported)}"
1497
+ )
1498
+
1499
+
1500
+ def __getattr__(name: str) -> Any:
1501
+ """Reexporta os adapters de ``ai_remote`` sem importação circular."""
1502
+ if name in {"OpenAIProxyAIService", "OpenCodeGoAIService", "OpenCodeGoAnthropicAIService", "OpenRouterAIService"}:
1503
+ from . import ai_remote
1504
+
1505
+ return getattr(ai_remote, name)
1506
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")