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,1530 @@
1
+ """Composição declarativa de documentos DOCX de relatório."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from copy import deepcopy
6
+ from dataclasses import dataclass
7
+ from hashlib import sha256
8
+ from io import BytesIO
9
+ import math
10
+ from pathlib import Path
11
+ from posixpath import dirname, join, normpath
12
+ import re
13
+ from typing import Any, Mapping
14
+ from zipfile import ZIP_DEFLATED, ZipFile
15
+
16
+ from ..errors import InputValidationError
17
+
18
+
19
+ _FORMAT = "argos.report-publication/v1"
20
+ _MARKER = re.compile(r"\[\[[A-Za-z0-9_.:-]+\]\]")
21
+ # Campos de modelo: `[[secao.chave]]`, em minúsculas, resolvidos pelo caminho no contexto do relatório.
22
+ _FIELD_MARKER = re.compile(r"\[\[([a-z][a-z0-9_]*(?:\.[a-z0-9_]+)*)\]\]")
23
+ _W_NAMESPACE = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
24
+ _XML_SPACE = "http://www.w3.org/XML/1998/namespace"
25
+ _XPATH_NAMESPACES = {
26
+ "w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main",
27
+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",
28
+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",
29
+ "wp": "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing",
30
+ "wps": "http://schemas.microsoft.com/office/word/2010/wordprocessingShape",
31
+ }
32
+ _VML_NAMESPACE = "urn:schemas-microsoft-com:vml"
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class _Insertion:
37
+ target: Any
38
+ source: Any
39
+ kind: str
40
+ target_layout: Any = None
41
+ table_formatting: Mapping[str, Any] | None = None
42
+
43
+
44
+ def _yaml():
45
+ try:
46
+ import yaml
47
+ except ImportError as exc: # pragma: no cover - PyYAML é dependência base
48
+ raise InputValidationError("configuração de publicação requer PyYAML") from exc
49
+ return yaml
50
+
51
+
52
+ def _load_config(path: Path) -> dict[str, Any]:
53
+ try:
54
+ payload = _yaml().safe_load(path.read_text(encoding="utf-8"))
55
+ except (_yaml().YAMLError, OSError, UnicodeError) as exc:
56
+ raise InputValidationError(f"não foi possível ler a configuração de publicação {path}: {exc}") from exc
57
+ if not isinstance(payload, Mapping):
58
+ raise InputValidationError("configuração de publicação deve ser um objeto YAML")
59
+ allowed = {
60
+ "formato", "modelo_institucional", "campos", "corpo", "anexos", "tabelas",
61
+ "insercoes", "sumario", "notas_legenda", "layout_documento",
62
+ }
63
+ unknown = sorted(str(key) for key in payload if key not in allowed)
64
+ if unknown:
65
+ raise InputValidationError(f"chaves desconhecidas na configuração de publicação: {', '.join(unknown)}")
66
+ if payload.get("formato") != _FORMAT:
67
+ raise InputValidationError(f"formato de publicação deve ser {_FORMAT}")
68
+ if payload.get("layout_documento") is not None:
69
+ from .docx_pdf import validate_report_layout
70
+
71
+ validate_report_layout(payload["layout_documento"])
72
+ model = payload.get("modelo_institucional")
73
+ if not isinstance(model, str) or not model.strip():
74
+ raise InputValidationError("modelo_institucional deve apontar para um DOCX")
75
+ body = payload.get("corpo")
76
+ if not isinstance(body, Mapping):
77
+ raise InputValidationError("corpo deve declarar marcador e inicio")
78
+ _require_marker(body.get("marcador"), "corpo.marcador")
79
+ _validate_anchor(body.get("inicio"), "corpo.inicio")
80
+ appendix = payload.get("anexos")
81
+ if appendix is not None:
82
+ if not isinstance(appendix, Mapping):
83
+ raise InputValidationError("anexos deve ser um objeto")
84
+ _require_marker(appendix.get("marcador"), "anexos.marcador")
85
+ _validate_anchor(appendix.get("inicio"), "anexos.inicio")
86
+ fields = payload.get("campos") or {}
87
+ if not isinstance(fields, Mapping):
88
+ raise InputValidationError("campos deve mapear marcadores para fontes de valor")
89
+ for marker, source in fields.items():
90
+ _require_marker(marker, "campos")
91
+ if not isinstance(source, Mapping):
92
+ raise InputValidationError(f"campo {marker} deve declarar contexto ou valor")
93
+ unknown_field_keys = sorted(str(key) for key in source if key not in {"contexto", "valor", "caixa_texto"})
94
+ if unknown_field_keys:
95
+ raise InputValidationError(
96
+ f"campo {marker} contém chaves desconhecidas: {', '.join(unknown_field_keys)}"
97
+ )
98
+ value_sources = {key for key in source if key in {"contexto", "valor"}}
99
+ if len(value_sources) != 1:
100
+ raise InputValidationError(f"campo {marker} deve declarar exatamente uma fonte: contexto ou valor")
101
+ if "contexto" in source and (not isinstance(source["contexto"], str) or not source["contexto"].strip()):
102
+ raise InputValidationError(f"campo {marker} requer um caminho contexto não vazio")
103
+ if "valor" in source and isinstance(source["valor"], (Mapping, list, tuple)):
104
+ raise InputValidationError(f"campo {marker} deve ter um valor escalar")
105
+ textbox = source.get("caixa_texto")
106
+ if textbox is not None:
107
+ if not isinstance(textbox, Mapping) or not textbox:
108
+ raise InputValidationError(f"campo {marker}.caixa_texto deve ser um objeto não vazio")
109
+ unknown_textbox_keys = sorted(str(key) for key in textbox if key not in {"largura_pt", "tamanho_fonte_pt"})
110
+ if unknown_textbox_keys:
111
+ raise InputValidationError(
112
+ f"campo {marker}.caixa_texto contém chaves desconhecidas: {', '.join(unknown_textbox_keys)}"
113
+ )
114
+ for key in ("largura_pt", "tamanho_fonte_pt"):
115
+ if key not in textbox:
116
+ continue
117
+ value = textbox.get(key)
118
+ if (
119
+ not isinstance(value, (int, float))
120
+ or isinstance(value, bool)
121
+ or not math.isfinite(float(value))
122
+ or value <= 0
123
+ or (key == "tamanho_fonte_pt" and round(float(value) * 2) < 1)
124
+ ):
125
+ raise InputValidationError(f"campo {marker}.caixa_texto.{key} deve ser número finito positivo")
126
+ tables = payload.get("tabelas") or []
127
+ if not isinstance(tables, list):
128
+ raise InputValidationError("tabelas deve ser uma lista")
129
+ for position, table in enumerate(tables, start=1):
130
+ if not isinstance(table, Mapping):
131
+ raise InputValidationError(f"tabelas[{position}] deve ser um objeto")
132
+ unknown_table_keys = sorted(str(key) for key in table if key not in {"marcador", "indice_origem", "formatacao"})
133
+ if unknown_table_keys:
134
+ raise InputValidationError(
135
+ f"tabelas[{position}] contém chaves desconhecidas: {', '.join(unknown_table_keys)}"
136
+ )
137
+ _require_marker(table.get("marcador"), f"tabelas[{position}].marcador")
138
+ if not isinstance(table.get("indice_origem"), int) or isinstance(table.get("indice_origem"), bool) or table["indice_origem"] < 0:
139
+ raise InputValidationError(f"tabelas[{position}].indice_origem deve ser inteiro não negativo")
140
+ formatting = table.get("formatacao")
141
+ if formatting is not None:
142
+ allowed_formatting = {
143
+ "fonte",
144
+ "tamanho_fonte_pt",
145
+ "entrelinha_pt",
146
+ "regra_entrelinha",
147
+ "espaco_antes_pt",
148
+ "espaco_depois_pt",
149
+ "repetir_cabecalho",
150
+ "impedir_quebra_linhas",
151
+ }
152
+ if not isinstance(formatting, Mapping) or not formatting:
153
+ raise InputValidationError(f"tabelas[{position}].formatacao deve ser um objeto não vazio")
154
+ unknown_formatting = sorted(str(key) for key in formatting if key not in allowed_formatting)
155
+ if unknown_formatting:
156
+ raise InputValidationError(
157
+ f"tabelas[{position}].formatacao contém chaves desconhecidas: {', '.join(unknown_formatting)}"
158
+ )
159
+ font = formatting.get("fonte")
160
+ if font is not None and (not isinstance(font, str) or not font.strip()):
161
+ raise InputValidationError(f"tabelas[{position}].formatacao.fonte deve ser texto não vazio")
162
+ line_rule = formatting.get("regra_entrelinha")
163
+ if line_rule is not None and (
164
+ not isinstance(line_rule, str) or line_rule not in {"auto", "exact", "atLeast"}
165
+ ):
166
+ raise InputValidationError(
167
+ f"tabelas[{position}].formatacao.regra_entrelinha deve ser auto, exact ou atLeast"
168
+ )
169
+ if line_rule == "auto" and "entrelinha_pt" in formatting:
170
+ raise InputValidationError(
171
+ f"tabelas[{position}].formatacao.regra_entrelinha auto não aceita entrelinha_pt"
172
+ )
173
+ if line_rule in {"exact", "atLeast"} and "entrelinha_pt" not in formatting:
174
+ raise InputValidationError(
175
+ f"tabelas[{position}].formatacao.regra_entrelinha {line_rule} requer entrelinha_pt"
176
+ )
177
+ for key in ("tamanho_fonte_pt", "entrelinha_pt", "espaco_antes_pt", "espaco_depois_pt"):
178
+ value = formatting.get(key)
179
+ if value is not None:
180
+ if (
181
+ not isinstance(value, (int, float))
182
+ or isinstance(value, bool)
183
+ or not math.isfinite(float(value))
184
+ or value < 0
185
+ or (key in {"tamanho_fonte_pt", "entrelinha_pt"} and value == 0)
186
+ ):
187
+ raise InputValidationError(
188
+ f"tabelas[{position}].formatacao.{key} deve ser número finito positivo"
189
+ if key in {"tamanho_fonte_pt", "entrelinha_pt"}
190
+ else f"tabelas[{position}].formatacao.{key} deve ser número finito não negativo"
191
+ )
192
+ for key in ("repetir_cabecalho", "impedir_quebra_linhas"):
193
+ if key in formatting and not isinstance(formatting[key], bool):
194
+ raise InputValidationError(f"tabelas[{position}].formatacao.{key} deve ser booleano")
195
+ insertions = payload.get("insercoes") or []
196
+ if not isinstance(insertions, list):
197
+ raise InputValidationError("insercoes deve ser uma lista")
198
+ for position, insertion in enumerate(insertions, start=1):
199
+ if not isinstance(insertion, Mapping):
200
+ raise InputValidationError(f"insercoes[{position}] deve ser um objeto")
201
+ _require_marker(insertion.get("marcador"), f"insercoes[{position}].marcador")
202
+ files = insertion.get("arquivos")
203
+ if not isinstance(files, list) or not files or any(not isinstance(item, str) or not item.strip() for item in files):
204
+ raise InputValidationError(f"insercoes[{position}].arquivos deve conter ao menos um caminho")
205
+ for flag in ("uma_pagina_por_arquivo", "quebrar_apos", "ajustar_a_pagina", "preencher_a_pagina"):
206
+ if flag in insertion and not isinstance(insertion[flag], bool):
207
+ raise InputValidationError(f"insercoes[{position}].{flag} deve ser booleano")
208
+ if insertion.get("preencher_a_pagina") and not insertion.get("ajustar_a_pagina"):
209
+ raise InputValidationError(
210
+ f"insercoes[{position}].preencher_a_pagina requer ajustar_a_pagina: true"
211
+ )
212
+ caption_notes = payload.get("notas_legenda")
213
+ if caption_notes is None:
214
+ caption_notes = []
215
+ if not isinstance(caption_notes, list):
216
+ raise InputValidationError("notas_legenda deve ser uma lista")
217
+ seen_figures: set[str] = set()
218
+ for position, rule in enumerate(caption_notes, start=1):
219
+ if not isinstance(rule, Mapping):
220
+ raise InputValidationError(f"notas_legenda[{position}] deve ser um objeto")
221
+ unknown_rule_keys = sorted(str(key) for key in rule if key not in {"figura", "apos"})
222
+ if unknown_rule_keys:
223
+ raise InputValidationError(
224
+ f"notas_legenda[{position}] contém chaves desconhecidas: {', '.join(unknown_rule_keys)}"
225
+ )
226
+ if "figura" not in rule or "apos" not in rule:
227
+ raise InputValidationError(f"notas_legenda[{position}] requer figura e apos")
228
+ figure = rule.get("figura")
229
+ anchor = rule.get("apos")
230
+ if not isinstance(figure, str) or not figure.strip():
231
+ raise InputValidationError(f"notas_legenda[{position}].figura deve ser texto não vazio")
232
+ if not isinstance(anchor, str) or not anchor.strip():
233
+ raise InputValidationError(f"notas_legenda[{position}].apos deve ser texto não vazio")
234
+ figure = figure.strip()
235
+ if figure in seen_figures:
236
+ raise InputValidationError(f"notas_legenda[{position}].figura deve ser única")
237
+ seen_figures.add(figure)
238
+ toc = payload.get("sumario")
239
+ if toc is not None:
240
+ if not isinstance(toc, Mapping) or set(toc) - {"atualizar", "titulo"}:
241
+ raise InputValidationError("sumario aceita atualizar e titulo")
242
+ if "atualizar" not in toc or not isinstance(toc.get("atualizar"), bool):
243
+ raise InputValidationError("sumario.atualizar deve ser booleano")
244
+ title = toc.get("titulo")
245
+ if title is not None:
246
+ if not isinstance(title, Mapping) or set(title) - {"texto", "estilo", "formatacao"}:
247
+ raise InputValidationError("sumario.titulo aceita texto, estilo e formatacao")
248
+ selector = {key: title[key] for key in ("texto", "estilo") if key in title}
249
+ _validate_anchor(selector, "sumario.titulo")
250
+ if "formatacao" not in title:
251
+ raise InputValidationError("sumario.titulo requer formatacao")
252
+ _validate_run_formatting(title["formatacao"], "sumario.titulo.formatacao")
253
+ markers = [str(body["marcador"])]
254
+ if appendix is not None:
255
+ markers.append(str(appendix["marcador"]))
256
+ markers.extend(str(table["marcador"]) for table in tables)
257
+ markers.extend(str(insertion["marcador"]) for insertion in insertions)
258
+ if len(set(markers)) != len(markers):
259
+ raise InputValidationError("cada marcador de slot deve ser único na configuração")
260
+ if set(markers) & set(fields):
261
+ raise InputValidationError("marcadores de campo e de slot devem ser distintos")
262
+ return dict(payload)
263
+
264
+
265
+ def resolve_report_layout(config_path: Path | None, context_layout: Any = None) -> Any:
266
+ """Combina perfis globais do YAML com perfis contextuais por documento.
267
+
268
+ Perfis declarados no YAML vêm primeiro e prevalecem em cabeçalhos idênticos;
269
+ os perfis contextuais específicos continuam disponíveis para outros alvos.
270
+ """
271
+ if config_path is None:
272
+ return context_layout
273
+ config = _load_config(config_path)
274
+ publication_layout = config.get("layout_documento")
275
+ if publication_layout is None:
276
+ return context_layout
277
+ if context_layout is None:
278
+ return publication_layout
279
+
280
+ from .docx_pdf import validate_report_layout
281
+
282
+ validate_report_layout(context_layout)
283
+ merged: dict[str, Any] = {"tabelas": [], "paragrafos": []}
284
+ configured_defaults = publication_layout.get("padrao_tabelas", {})
285
+ contextual_defaults = context_layout.get("padrao_tabelas", {})
286
+ table_look = dict(contextual_defaults.get("tbl_look", {}))
287
+ table_look.update(configured_defaults.get("tbl_look", {}))
288
+ if table_look:
289
+ merged["padrao_tabelas"] = {"tbl_look": table_look}
290
+ for key_field, key_fn in (
291
+ ("tabelas", lambda item: tuple(" ".join(name.split()) for name in item["cabecalhos"])),
292
+ ("paragrafos", lambda item: " ".join(item["prefixo"].split())),
293
+ ):
294
+ configured = publication_layout.get(key_field, [])
295
+ contextual = context_layout.get(key_field, [])
296
+ configured_keys = {key_fn(item) for item in configured}
297
+ merged[key_field].extend(dict(item) for item in configured)
298
+ merged[key_field].extend(dict(item) for item in contextual if key_fn(item) not in configured_keys)
299
+ return {key: value for key, value in merged.items() if value}
300
+
301
+
302
+ def _require_marker(value: Any, label: str) -> str:
303
+ if not isinstance(value, str) or not _MARKER.fullmatch(value):
304
+ raise InputValidationError(f"{label} deve ter formato [[NOME_DO_MARCADOR]]")
305
+ return value
306
+
307
+
308
+ def _validate_anchor(value: Any, label: str) -> Mapping[str, Any]:
309
+ if not isinstance(value, Mapping) or not value:
310
+ raise InputValidationError(f"{label} deve declarar texto e/ou estilo")
311
+ if set(value) - {"texto", "estilo"}:
312
+ raise InputValidationError(f"{label} aceita somente texto e estilo")
313
+ if not any(isinstance(value.get(key), str) and value[key].strip() for key in ("texto", "estilo")):
314
+ raise InputValidationError(f"{label} deve ter texto ou estilo não vazio")
315
+ return value
316
+
317
+
318
+ def _validate_run_formatting(value: Any, label: str) -> Mapping[str, Any]:
319
+ allowed = {"fonte", "tamanho_fonte_pt", "negrito", "italico", "cor"}
320
+ if not isinstance(value, Mapping) or not value:
321
+ raise InputValidationError(f"{label} deve ser um objeto não vazio")
322
+ unknown = sorted(str(key) for key in value if key not in allowed)
323
+ if unknown:
324
+ raise InputValidationError(f"{label} contém chaves desconhecidas: {', '.join(unknown)}")
325
+ font = value.get("fonte")
326
+ if font is not None and (not isinstance(font, str) or not font.strip()):
327
+ raise InputValidationError(f"{label}.fonte deve ser texto não vazio")
328
+ size = value.get("tamanho_fonte_pt")
329
+ if size is not None and (
330
+ not isinstance(size, (int, float))
331
+ or isinstance(size, bool)
332
+ or not math.isfinite(float(size))
333
+ or size <= 0
334
+ or round(float(size) * 2) < 1
335
+ ):
336
+ raise InputValidationError(f"{label}.tamanho_fonte_pt deve ser número finito positivo")
337
+ for key in ("negrito", "italico"):
338
+ if key in value and not isinstance(value[key], bool):
339
+ raise InputValidationError(f"{label}.{key} deve ser booleano")
340
+ color = value.get("cor")
341
+ if color is not None and (not isinstance(color, str) or re.fullmatch(r"#?[0-9A-Fa-f]{6}", color) is None):
342
+ raise InputValidationError(f"{label}.cor deve ser hexadecimal RGB no formato #RRGGBB")
343
+ return value
344
+
345
+
346
+ def _resolve_value(context: Mapping[str, Any], path: str, marker: str) -> str:
347
+ value: Any = context
348
+ for key in path.split("."):
349
+ if not key or not isinstance(value, Mapping) or key not in value:
350
+ raise InputValidationError(f"campo de publicação {marker} não existe no contexto: {path}")
351
+ value = value[key]
352
+ if value is None or isinstance(value, (Mapping, list, tuple)):
353
+ raise InputValidationError(f"campo de publicação {marker} não contém valor escalar: {path}")
354
+ text = str(value)
355
+ if not text.strip():
356
+ raise InputValidationError(f"campo de publicação {marker} está vazio: {path}")
357
+ return text
358
+
359
+
360
+ def _field_values(fields: Mapping[str, Any], context: Mapping[str, Any]) -> dict[str, str]:
361
+ result = {}
362
+ for marker, source in fields.items():
363
+ if "contexto" in source:
364
+ result[str(marker)] = _resolve_value(context, str(source["contexto"]), str(marker))
365
+ else:
366
+ value = source["valor"]
367
+ if value is None:
368
+ raise InputValidationError(f"campo de publicação {marker} tem valor nulo")
369
+ result[str(marker)] = str(value)
370
+ return result
371
+
372
+
373
+ def _resolve_resources(config: Mapping[str, Any], config_path: Path) -> tuple[Path, list[tuple[Mapping[str, Any], list[Path]]]]:
374
+ base = config_path.parent
375
+ model = (base / str(config["modelo_institucional"])).resolve()
376
+ if not model.is_file():
377
+ raise InputValidationError(f"modelo institucional não encontrado: {model}")
378
+ if model.suffix.lower() != ".docx":
379
+ raise InputValidationError("modelo_institucional deve ter extensão .docx")
380
+ from PIL import Image
381
+
382
+ resolved = []
383
+ for insertion in config.get("insercoes") or []:
384
+ images = []
385
+ for raw in insertion["arquivos"]:
386
+ path = (base / raw).resolve()
387
+ if not path.is_file():
388
+ raise InputValidationError(f"imagem da publicação não encontrada: {path}")
389
+ try:
390
+ with Image.open(path) as image:
391
+ image.verify()
392
+ except Exception as exc: # noqa: BLE001 - imagem inválida é entrada da operação
393
+ raise InputValidationError(f"imagem da publicação inválida: {path}") from exc
394
+ images.append(path)
395
+ resolved.append((insertion, images))
396
+ return model, resolved
397
+
398
+
399
+ def _paragraph_text(paragraph: Any) -> str:
400
+ return "".join(node.text or "" for node in paragraph._p.xpath(".//w:t")).strip()
401
+
402
+
403
+ def _matching_paragraphs(document: Any, selector: Mapping[str, Any]) -> list[Any]:
404
+ from docx.text.paragraph import Paragraph
405
+
406
+ matches = []
407
+ for child in document.element.body:
408
+ if child.tag.rsplit("}", 1)[-1] != "p":
409
+ continue
410
+ paragraph = Paragraph(child, document)
411
+ text_match = "texto" not in selector or _paragraph_text(paragraph) == str(selector["texto"]).strip()
412
+ style_match = "estilo" not in selector or paragraph.style.name == str(selector["estilo"]).strip()
413
+ if text_match and style_match:
414
+ matches.append(child)
415
+ return matches
416
+
417
+
418
+ def _unique_paragraph(document: Any, marker: str, *, label: str) -> Any:
419
+ matches = [paragraph._p for paragraph in document.paragraphs if paragraph.text.strip() == marker]
420
+ if len(matches) != 1:
421
+ raise InputValidationError(f"marcador {label} {marker} deve ocorrer uma vez no modelo (encontrado: {len(matches)})")
422
+ return matches[0]
423
+
424
+
425
+ def _figure_bookmark_name(figure_id: str) -> str:
426
+ return "argos_fig_" + sha256(figure_id.encode("utf-8")).hexdigest()[:30]
427
+
428
+
429
+ def _direct_run_text(run: Any, text_tag: str) -> str:
430
+ return "".join(node.text or "" for node in run.iter() if node.tag == text_tag)
431
+
432
+
433
+ def _split_text_run(run: Any, position: int, *, run_tag: str, properties_tag: str, text_tag: str, qn: Any) -> tuple[Any, Any]:
434
+ """Divide um run textual sem perder propriedades de formatação."""
435
+ from lxml import etree
436
+
437
+ children = list(run)
438
+ if any(child.tag not in {properties_tag, text_tag} for child in children):
439
+ raise InputValidationError("não foi possível posicionar nota: o run da legenda tem conteúdo não textual")
440
+ text_nodes = [child for child in children if child.tag == text_tag]
441
+ text_length = sum(len(node.text or "") for node in text_nodes)
442
+ if not 0 < position < text_length:
443
+ raise InputValidationError("posição interna inválida ao dividir texto da legenda")
444
+
445
+ def fragment(start: int, end: int) -> Any:
446
+ result = etree.Element(run_tag)
447
+ properties = run.find(properties_tag)
448
+ if properties is not None:
449
+ result.append(deepcopy(properties))
450
+ cursor = 0
451
+ for original in text_nodes:
452
+ value = original.text or ""
453
+ left = max(start, cursor)
454
+ right = min(end, cursor + len(value))
455
+ if right > left:
456
+ node = deepcopy(original)
457
+ node.text = value[left - cursor : right - cursor]
458
+ if node.text[:1].isspace() or node.text[-1:].isspace():
459
+ node.set(qn("xml:space"), "preserve")
460
+ elif qn("xml:space") in node.attrib:
461
+ del node.attrib[qn("xml:space")]
462
+ result.append(node)
463
+ cursor += len(value)
464
+ return result
465
+
466
+ return fragment(0, position), fragment(position, text_length)
467
+
468
+
469
+ def _position_figure_notes(document: Any, rules: list[Mapping[str, Any]]) -> None:
470
+ """Move chamadas de notas para o ponto declarado dentro da legenda da figura."""
471
+ if not rules:
472
+ return
473
+ from docx.oxml.ns import qn
474
+
475
+ paragraph_tag = qn("w:p")
476
+ run_tag = qn("w:r")
477
+ text_tag = qn("w:t")
478
+ properties_tag = qn("w:rPr")
479
+ reference_tag = qn("w:footnoteReference")
480
+ for rule in rules:
481
+ figure_id = str(rule["figura"]).strip()
482
+ anchor = str(rule["apos"]).strip()
483
+ bookmark_name = _figure_bookmark_name(figure_id)
484
+ paragraphs = []
485
+ for element in document.element.body.iter():
486
+ if element.tag != paragraph_tag:
487
+ continue
488
+ if any(
489
+ child.tag == qn("w:bookmarkStart") and child.get(qn("w:name")) == bookmark_name
490
+ for child in element.iter()
491
+ ):
492
+ paragraphs.append(element)
493
+ if len(paragraphs) != 1:
494
+ raise InputValidationError(
495
+ f"notas_legenda figura {figure_id} deve corresponder a uma legenda (encontrado: {len(paragraphs)})"
496
+ )
497
+ paragraph = paragraphs[0]
498
+ references = [node for node in paragraph.iter() if node.tag == reference_tag]
499
+ reference_runs = [
500
+ child for child in paragraph
501
+ if child.tag == run_tag and any(node.tag == reference_tag for node in child.iter())
502
+ ]
503
+ if not references:
504
+ raise InputValidationError(f"notas_legenda figura {figure_id} não tem chamada de nota na legenda")
505
+ if sum(sum(1 for node in run.iter() if node.tag == reference_tag) for run in reference_runs) != len(references):
506
+ raise InputValidationError(
507
+ f"notas_legenda figura {figure_id} usa estrutura de nota não suportada na legenda"
508
+ )
509
+ for run in reference_runs:
510
+ if any(child.tag not in {properties_tag, reference_tag} for child in run):
511
+ raise InputValidationError(
512
+ f"notas_legenda figura {figure_id} requer chamadas de nota sem texto visível"
513
+ )
514
+
515
+ direct_runs = [child for child in paragraph if child.tag == run_tag and child not in reference_runs]
516
+ visible_text = "".join(_direct_run_text(run, text_tag) for run in direct_runs)
517
+ all_visible_text = "".join(node.text or "" for node in paragraph.iter() if node.tag == text_tag)
518
+ if visible_text != all_visible_text:
519
+ raise InputValidationError(
520
+ f"notas_legenda figura {figure_id} requer texto da legenda em runs diretos do parágrafo"
521
+ )
522
+ first = visible_text.find(anchor)
523
+ if first < 0:
524
+ raise InputValidationError(
525
+ f"âncora notas_legenda.apos não encontrada na legenda da figura {figure_id}: {anchor}"
526
+ )
527
+ if visible_text.find(anchor, first + 1) >= 0:
528
+ raise InputValidationError(
529
+ f"âncora notas_legenda.apos deve ocorrer uma vez na legenda da figura {figure_id}: {anchor}"
530
+ )
531
+ insertion_offset = first + len(anchor)
532
+ for run in reference_runs:
533
+ paragraph.remove(run)
534
+
535
+ visible_offset = 0
536
+ insertion_index = None
537
+ for run in [child for child in paragraph if child.tag == run_tag]:
538
+ run_text = _direct_run_text(run, text_tag)
539
+ next_offset = visible_offset + len(run_text)
540
+ if insertion_offset == next_offset:
541
+ insertion_index = paragraph.index(run) + 1
542
+ break
543
+ if visible_offset < insertion_offset < next_offset:
544
+ left, right = _split_text_run(
545
+ run,
546
+ insertion_offset - visible_offset,
547
+ run_tag=run_tag,
548
+ properties_tag=properties_tag,
549
+ text_tag=text_tag,
550
+ qn=qn,
551
+ )
552
+ index = paragraph.index(run)
553
+ paragraph.remove(run)
554
+ paragraph.insert(index, left)
555
+ paragraph.insert(index + 1, right)
556
+ insertion_index = index + 1
557
+ break
558
+ visible_offset = next_offset
559
+ if insertion_index is None:
560
+ raise InputValidationError(
561
+ f"não foi possível localizar o ponto de inserção na legenda da figura {figure_id}"
562
+ )
563
+ for offset, run in enumerate(reference_runs):
564
+ paragraph.insert(insertion_index + offset, run)
565
+
566
+
567
+ def _document_segment(source_bytes: bytes, selected_indexes: set[int]) -> Any:
568
+ from docx import Document
569
+
570
+ document = Document(BytesIO(source_bytes))
571
+ body = document.element.body
572
+ children = [child for child in body if child.tag.rsplit("}", 1)[-1] != "sectPr"]
573
+ for index, child in enumerate(children):
574
+ if index in selected_indexes:
575
+ continue
576
+ body.remove(child)
577
+ return document
578
+
579
+
580
+ def _is_page_break_only_paragraph(element: Any) -> bool:
581
+ from docx.oxml.ns import qn
582
+
583
+ if element.tag != qn("w:p"):
584
+ return False
585
+ if not element.xpath(".//w:br[@w:type='page']"):
586
+ return False
587
+ if element.xpath(".//w:t[normalize-space(.)!=''] | .//w:drawing | .//w:object | .//w:footnoteReference | .//w:sym"):
588
+ return False
589
+ return True
590
+
591
+
592
+ def _source_segment(
593
+ source_bytes: bytes,
594
+ selector: Mapping[str, Any],
595
+ end_selector: Mapping[str, Any] | None,
596
+ *,
597
+ boundary_page_break: str | None = None,
598
+ ) -> Any:
599
+ from docx import Document
600
+
601
+ document = Document(BytesIO(source_bytes))
602
+ body = document.element.body
603
+ children = [child for child in body if child.tag.rsplit("}", 1)[-1] != "sectPr"]
604
+ start_matches = _matching_paragraphs(document, selector)
605
+ if len(start_matches) != 1:
606
+ raise InputValidationError(f"âncora de início do corpo deve ocorrer uma vez (encontrado: {len(start_matches)})")
607
+ start = children.index(start_matches[0])
608
+ end = len(children)
609
+ if end_selector is not None:
610
+ end_matches = _matching_paragraphs(document, end_selector)
611
+ if len(end_matches) != 1:
612
+ raise InputValidationError(f"âncora de início dos anexos deve ocorrer uma vez (encontrado: {len(end_matches)})")
613
+ end = children.index(end_matches[0])
614
+ if end <= start:
615
+ raise InputValidationError("âncora dos anexos deve vir depois do início do corpo")
616
+ if boundary_page_break == "end" and _is_page_break_only_paragraph(children[end - 1]):
617
+ end -= 1
618
+ if boundary_page_break == "start" and start > 0 and _is_page_break_only_paragraph(children[start - 1]):
619
+ start -= 1
620
+ return _document_segment(source_bytes, set(range(start, end)))
621
+
622
+
623
+ def _source_table(source_bytes: bytes, index: int) -> Any:
624
+ from docx import Document
625
+
626
+ document = Document(BytesIO(source_bytes))
627
+ if index >= len(document.tables):
628
+ raise InputValidationError(f"tabela de origem {index} não existe; o documento tem {len(document.tables)} tabelas")
629
+ element = document.tables[index]._tbl
630
+ body_index = [child for child in document.element.body if child.tag.rsplit("}", 1)[-1] != "sectPr"].index(element)
631
+ return _document_segment(source_bytes, {body_index})
632
+
633
+
634
+ def _table_by_marker(document: Any, marker: str) -> Any:
635
+ matches = []
636
+ for table in document.tables:
637
+ text = "\n".join(cell.text for row in table.rows for cell in row.cells)
638
+ if marker in text:
639
+ matches.append(table._tbl)
640
+ if len(matches) != 1:
641
+ raise InputValidationError(f"marcador de tabela {marker} deve ocorrer em uma tabela (encontrado: {len(matches)})")
642
+ return matches[0]
643
+
644
+
645
+ def _set_table_row_flag(row: Any, flag: str, enabled: bool) -> None:
646
+ from docx.oxml import OxmlElement
647
+ from docx.oxml.ns import qn
648
+
649
+ properties = row.find(qn("w:trPr"))
650
+ if properties is None:
651
+ if not enabled:
652
+ return
653
+ properties = OxmlElement("w:trPr")
654
+ row.insert(0, properties)
655
+ node = properties.find(qn(f"w:{flag}"))
656
+ if enabled and node is None:
657
+ properties.append(OxmlElement(f"w:{flag}"))
658
+ elif not enabled and node is not None:
659
+ properties.remove(node)
660
+
661
+
662
+ def _apply_table_formatting(table: Any, formatting: Mapping[str, Any]) -> None:
663
+ from docx.oxml import OxmlElement
664
+ from docx.oxml.ns import qn
665
+
666
+ rows = table.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tr")
667
+ if "repetir_cabecalho" in formatting:
668
+ for position, row in enumerate(rows):
669
+ _set_table_row_flag(row, "tblHeader", formatting["repetir_cabecalho"] and position == 0)
670
+ if "impedir_quebra_linhas" in formatting:
671
+ for row in rows:
672
+ _set_table_row_flag(row, "cantSplit", formatting["impedir_quebra_linhas"])
673
+
674
+ for row in rows:
675
+ for cell in row.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tc"):
676
+ for paragraph in cell.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}p"):
677
+ paragraph_properties = paragraph.find(qn("w:pPr"))
678
+ if paragraph_properties is None and any(
679
+ key in formatting
680
+ for key in ("entrelinha_pt", "regra_entrelinha", "espaco_antes_pt", "espaco_depois_pt")
681
+ ):
682
+ paragraph_properties = OxmlElement("w:pPr")
683
+ paragraph.insert(0, paragraph_properties)
684
+ has_spacing_override = any(
685
+ key in formatting
686
+ for key in ("entrelinha_pt", "regra_entrelinha", "espaco_antes_pt", "espaco_depois_pt")
687
+ )
688
+ spacing = paragraph_properties.find(qn("w:spacing")) if paragraph_properties is not None else None
689
+ if spacing is None and paragraph_properties is not None and has_spacing_override:
690
+ spacing = OxmlElement("w:spacing")
691
+ paragraph_properties.append(spacing)
692
+ if spacing is not None:
693
+ if "entrelinha_pt" in formatting or "regra_entrelinha" in formatting:
694
+ line_rule = formatting.get("regra_entrelinha", "exact")
695
+ line_value = (
696
+ 240
697
+ if line_rule == "auto"
698
+ else round(float(formatting["entrelinha_pt"]) * 20)
699
+ )
700
+ spacing.set(qn("w:line"), str(line_value))
701
+ spacing.set(qn("w:lineRule"), line_rule)
702
+ for key, attribute in (("espaco_antes_pt", "before"), ("espaco_depois_pt", "after")):
703
+ if key in formatting:
704
+ spacing.set(qn(f"w:{attribute}"), str(round(float(formatting[key]) * 20)))
705
+ for run in paragraph.findall(".//{http://schemas.openxmlformats.org/wordprocessingml/2006/main}r"):
706
+ run_properties = run.find(qn("w:rPr"))
707
+ if run_properties is None and ("fonte" in formatting or "tamanho_fonte_pt" in formatting):
708
+ run_properties = OxmlElement("w:rPr")
709
+ run.insert(0, run_properties)
710
+ if run_properties is None:
711
+ continue
712
+ if "fonte" in formatting:
713
+ fonts = run_properties.find(qn("w:rFonts"))
714
+ if fonts is None:
715
+ fonts = OxmlElement("w:rFonts")
716
+ run_properties.insert(0, fonts)
717
+ for attribute in ("ascii", "hAnsi", "eastAsia", "cs"):
718
+ fonts.set(qn(f"w:{attribute}"), str(formatting["fonte"]))
719
+ if "tamanho_fonte_pt" in formatting:
720
+ half_points = str(round(float(formatting["tamanho_fonte_pt"]) * 2))
721
+ for tag in ("sz", "szCs"):
722
+ size = run_properties.find(qn(f"w:{tag}"))
723
+ if size is None:
724
+ size = OxmlElement(f"w:{tag}")
725
+ run_properties.append(size)
726
+ size.set(qn("w:val"), half_points)
727
+
728
+
729
+ def _copy_table_layout(
730
+ inserted: Any,
731
+ target: Any,
732
+ formatting: Mapping[str, Any] | None = None,
733
+ ) -> None:
734
+ source_rows = inserted.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tr")
735
+ target_rows = target.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tr")
736
+ if len(source_rows) != len(target_rows):
737
+ raise InputValidationError(
738
+ f"tabela de origem e slot devem ter o mesmo número de linhas ({len(source_rows)} != {len(target_rows)})"
739
+ )
740
+ source_pr = inserted.find("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tblPr")
741
+ target_pr = target.find("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tblPr")
742
+ if source_pr is not None:
743
+ inserted.replace(source_pr, deepcopy(target_pr)) if target_pr is not None else None
744
+ source_grid = inserted.find("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tblGrid")
745
+ target_grid = target.find("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tblGrid")
746
+ if source_grid is not None and target_grid is not None:
747
+ inserted.replace(source_grid, deepcopy(target_grid))
748
+ for row_position, (source_row, target_row) in enumerate(zip(source_rows, target_rows, strict=True), start=1):
749
+ source_cells = source_row.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tc")
750
+ target_cells = target_row.findall("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tc")
751
+ if len(source_cells) != len(target_cells):
752
+ raise InputValidationError(f"tabelas divergem no número de células da linha {row_position}")
753
+ for source_cell, target_cell in zip(source_cells, target_cells, strict=True):
754
+ source_tcpr = source_cell.find("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tcPr")
755
+ target_tcpr = target_cell.find("./{http://schemas.openxmlformats.org/wordprocessingml/2006/main}tcPr")
756
+ if source_tcpr is not None and target_tcpr is not None:
757
+ source_cell.replace(source_tcpr, deepcopy(target_tcpr))
758
+ elif target_tcpr is not None:
759
+ source_cell.insert(0, deepcopy(target_tcpr))
760
+ if formatting:
761
+ _apply_table_formatting(inserted, formatting)
762
+
763
+
764
+ def _composer_class():
765
+ from docx.oxml import parse_xml
766
+ from docx.oxml.ns import qn
767
+ from docx.opc.constants import RELATIONSHIP_TYPE as RT
768
+ from docxcompose.composer import Composer
769
+ from docxcompose.composer import NS, REFERENCED_PARTS_IGNORED_RELTYPES, serialize_part_xml, xpath
770
+
771
+ class ReportComposer(Composer):
772
+ def add_referenced_parts(self, source_part: Any, destination_part: Any, element: Any) -> None:
773
+ for node in xpath(element, ".//*[@r:id]"):
774
+ relationship_id = node.get(f"{{{NS['r']}}}id")
775
+ relation = source_part.rels[relationship_id]
776
+ if relation.reltype in REFERENCED_PARTS_IGNORED_RELTYPES:
777
+ continue
778
+ # VML images are copied by add_shapes; copying the relationship
779
+ # here as well creates an orphan duplicate media part.
780
+ if node.tag == "{urn:schemas-microsoft-com:vml}imagedata":
781
+ continue
782
+ new_relation = self.add_relationship(source_part, destination_part, relation)
783
+ node.set(f"{{{NS['r']}}}id", new_relation.rId)
784
+
785
+ def add_footnotes(self, doc: Any, element: Any) -> None:
786
+ references = element.findall(f".//{qn('w:footnoteReference')}")
787
+ if not references:
788
+ return
789
+ try:
790
+ source_part = doc.part.rels.part_with_reltype(RT.FOOTNOTES)
791
+ except KeyError as exc:
792
+ raise InputValidationError("documento de origem contém chamada de nota sem word/footnotes.xml") from exc
793
+ target_part = self.footnote_part()
794
+ source_notes = parse_xml(source_part.blob)
795
+ target_notes = parse_xml(target_part.blob)
796
+ positive_ids = [
797
+ int(note.get(qn("w:id")))
798
+ for note in target_notes.findall(f"./{qn('w:footnote')}")
799
+ if int(note.get(qn("w:id"), "-1")) >= 0
800
+ ]
801
+ next_id = max(positive_ids, default=0) + 1
802
+ for reference in references:
803
+ source_id = reference.get(qn("w:id"))
804
+ definitions = source_notes.xpath(f"./w:footnote[@w:id='{source_id}']", namespaces=_XPATH_NAMESPACES)
805
+ if len(definitions) != 1:
806
+ raise InputValidationError(f"chamada de nota referencia definição inexistente: {source_id}")
807
+ note = deepcopy(definitions[0])
808
+ note.set(qn("w:id"), str(next_id))
809
+ reference.set(qn("w:id"), str(next_id))
810
+ self.add_styles(doc, note)
811
+ self.add_numberings(doc, note)
812
+ for relationship_node in note.xpath(".//*[@r:id]", namespaces=_XPATH_NAMESPACES):
813
+ relationship_id = relationship_node.get(qn("r:id"))
814
+ relation = source_part.rels.get(relationship_id)
815
+ relation_part = source_part
816
+ if relation is None:
817
+ relation = doc.part.rels.get(relationship_id)
818
+ relation_part = doc.part
819
+ if relation is None:
820
+ raise InputValidationError(
821
+ f"nota {source_id} referencia relação DOCX inexistente: {relationship_id}"
822
+ )
823
+ new_relation = self.add_relationship(relation_part, target_part, relation)
824
+ relationship_node.set(qn("r:id"), new_relation.rId)
825
+ target_notes.append(note)
826
+ next_id += 1
827
+ target_part._blob = serialize_part_xml(target_notes)
828
+
829
+ return ReportComposer
830
+
831
+
832
+ def _section_for_paragraph(document: Any, paragraph: Any) -> Any:
833
+ from docx.oxml.ns import qn
834
+
835
+ body = document.element.body
836
+ section_index = 0
837
+ target_index = body.index(paragraph._p)
838
+ boundaries = 0
839
+ for index, child in enumerate(body):
840
+ if index >= target_index:
841
+ break
842
+ if child.find(f"./{qn('w:pPr')}/{qn('w:sectPr')}") is not None:
843
+ boundaries += 1
844
+ section_index = min(boundaries, len(document.sections) - 1)
845
+ return document.sections[section_index]
846
+
847
+
848
+ def _anchor_picture_to_page(
849
+ inline: Any,
850
+ *,
851
+ horizontal_offset: int,
852
+ vertical_offset: int,
853
+ relative_height: int,
854
+ ) -> None:
855
+ """Move a picture from text flow to a page-relative floating position."""
856
+ from docx.oxml import OxmlElement
857
+
858
+ anchor = OxmlElement("wp:anchor")
859
+ for name, value in {
860
+ "distT": "0",
861
+ "distB": "0",
862
+ "distL": "0",
863
+ "distR": "0",
864
+ "simplePos": "0",
865
+ "relativeHeight": str(relative_height),
866
+ "behindDoc": "0",
867
+ "locked": "0",
868
+ "layoutInCell": "0",
869
+ "allowOverlap": "1",
870
+ }.items():
871
+ anchor.set(name, value)
872
+
873
+ simple_position = OxmlElement("wp:simplePos")
874
+ simple_position.set("x", "0")
875
+ simple_position.set("y", "0")
876
+ anchor.append(simple_position)
877
+
878
+ for axis, offset in (("H", horizontal_offset), ("V", vertical_offset)):
879
+ position = OxmlElement(f"wp:position{axis}")
880
+ position.set("relativeFrom", "page")
881
+ position_offset = OxmlElement("wp:posOffset")
882
+ position_offset.text = str(offset)
883
+ position.append(position_offset)
884
+ anchor.append(position)
885
+
886
+ copied_children = {
887
+ child.tag.rsplit("}", 1)[-1]: deepcopy(child)
888
+ for child in inline
889
+ }
890
+ for name in ("extent", "effectExtent"):
891
+ if name in copied_children:
892
+ anchor.append(copied_children[name])
893
+ anchor.append(OxmlElement("wp:wrapNone"))
894
+ for name in ("docPr", "cNvGraphicFramePr", "graphic"):
895
+ child = copied_children.get(name)
896
+ if child is not None:
897
+ anchor.append(child)
898
+
899
+ parent = inline.getparent()
900
+ if parent is None:
901
+ raise InputValidationError("imagem de página não tem elemento DrawingML pai")
902
+ parent.replace(inline, anchor)
903
+
904
+
905
+ def _set_page_break_before(paragraph: Any) -> None:
906
+ from docx.oxml import OxmlElement
907
+ from docx.oxml.ns import qn
908
+
909
+ properties = paragraph.find(qn("w:pPr"))
910
+ if properties is None:
911
+ properties = OxmlElement("w:pPr")
912
+ paragraph.insert(0, properties)
913
+ if properties.find(qn("w:pageBreakBefore")) is None:
914
+ properties.append(OxmlElement("w:pageBreakBefore"))
915
+
916
+
917
+ def _add_images(document: Any, marker: str, images: list[Path], settings: Mapping[str, Any]) -> None:
918
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
919
+ from docx.oxml import OxmlElement
920
+ from docx.shared import Emu, Pt
921
+ from PIL import Image
922
+
923
+ paragraph = _unique_paragraph(document, marker, label="de inserção")
924
+ from docx.text.paragraph import Paragraph as ParagraphClass
925
+
926
+ target = ParagraphClass(paragraph, document)
927
+ section = _section_for_paragraph(document, target)
928
+ insertion_anchor = paragraph
929
+ if settings.get("ajustar_a_pagina"):
930
+ max_width = section.page_width
931
+ max_height = section.page_height
932
+ else:
933
+ max_width = section.page_width - section.left_margin - section.right_margin
934
+ max_height = section.page_height - section.top_margin - section.bottom_margin
935
+ page_per_file = settings.get("uma_pagina_por_arquivo", False)
936
+ for position, image_path in enumerate(images):
937
+ if position == 0:
938
+ current = target
939
+ for child in list(paragraph):
940
+ if child.tag.rsplit("}", 1)[-1] != "pPr":
941
+ paragraph.remove(child)
942
+ else:
943
+ element = OxmlElement("w:p")
944
+ insertion_anchor.addnext(element)
945
+ current = ParagraphClass(element, target._parent)
946
+ insertion_anchor = element
947
+ with Image.open(image_path) as image:
948
+ aspect = image.width / image.height
949
+ if settings.get("ajustar_a_pagina") and settings.get("preencher_a_pagina"):
950
+ width, height = max_width, max_height
951
+ else:
952
+ width = min(max_width, int(max_height * aspect))
953
+ height = int(width / aspect)
954
+ current.paragraph_format.space_before = 0
955
+ current.paragraph_format.space_after = 0
956
+ if page_per_file:
957
+ current.paragraph_format.page_break_before = True
958
+ picture = current.add_run().add_picture(str(image_path), width=Emu(width), height=Emu(height))
959
+ if settings.get("ajustar_a_pagina"):
960
+ current.alignment = None
961
+ current.paragraph_format.left_indent = 0
962
+ # A drawing anchored to the page still inherits a paragraph's
963
+ # first-line indent in LibreOffice. That shifts full-page images
964
+ # from the page origin and clips the right edge.
965
+ current.paragraph_format.first_line_indent = Pt(0)
966
+ current.paragraph_format.right_indent = 0
967
+ current.paragraph_format.line_spacing = Pt(1)
968
+ current.paragraph_format.keep_with_next = False
969
+ current.paragraph_format.keep_together = False
970
+ _anchor_picture_to_page(
971
+ picture._inline,
972
+ horizontal_offset=max(0, (section.page_width - width) // 2),
973
+ vertical_offset=max(0, (section.page_height - height) // 2),
974
+ relative_height=position + 2,
975
+ )
976
+ else:
977
+ current.alignment = WD_ALIGN_PARAGRAPH.CENTER
978
+ if settings.get("quebrar_apos"):
979
+ following = insertion_anchor.getnext()
980
+ if following is not None and following.tag.rsplit("}", 1)[-1] == "p":
981
+ _set_page_break_before(following)
982
+ else:
983
+ element = OxmlElement("w:p")
984
+ insertion_anchor.addnext(element)
985
+ _set_page_break_before(element)
986
+
987
+
988
+ def _replace_text_marker(paragraph: Any, marker: str, replacement: str) -> int:
989
+ nodes = list(paragraph.xpath(".//w:t", namespaces=paragraph.nsmap))
990
+ if not nodes:
991
+ return 0
992
+ combined = "".join(node.text or "" for node in nodes)
993
+ matches = list(re.finditer(re.escape(marker), combined))
994
+ if not matches:
995
+ return 0
996
+ offsets = []
997
+ offset = 0
998
+ for node in nodes:
999
+ value = node.text or ""
1000
+ offsets.append((offset, offset + len(value)))
1001
+ offset += len(value)
1002
+ for match in reversed(matches):
1003
+ first_index = next(index for index, (_, end) in enumerate(offsets) if end > match.start() or (end == match.start() and offsets[index][0] == end))
1004
+ last_index = next(index for index, (start, end) in enumerate(offsets) if start < match.end() <= end)
1005
+ first_start, _ = offsets[first_index]
1006
+ last_start, _ = offsets[last_index]
1007
+ first_text = nodes[first_index].text or ""
1008
+ last_text = nodes[last_index].text or ""
1009
+ if first_index == last_index:
1010
+ value = first_text[: match.start() - first_start] + replacement + first_text[match.end() - first_start :]
1011
+ nodes[first_index].text = value
1012
+ else:
1013
+ nodes[first_index].text = first_text[: match.start() - first_start] + replacement
1014
+ for index in range(first_index + 1, last_index):
1015
+ nodes[index].text = ""
1016
+ nodes[last_index].text = last_text[match.end() - last_start :]
1017
+ for node in nodes:
1018
+ value = node.text or ""
1019
+ if value[:1].isspace() or value[-1:].isspace():
1020
+ node.set(f"{{{_XML_SPACE}}}space", "preserve")
1021
+ else:
1022
+ node.attrib.pop(f"{{{_XML_SPACE}}}space", None)
1023
+ return len(matches)
1024
+
1025
+
1026
+ def _paragraph_contains_marker(paragraph: Any, marker: str) -> bool:
1027
+ combined = "".join(node.text or "" for node in paragraph.xpath(".//w:t", namespaces=_XPATH_NAMESPACES))
1028
+ return marker in combined
1029
+
1030
+
1031
+ def _textbox_for_paragraph(paragraph: Any) -> tuple[Any | None, Any | None]:
1032
+ textbox_content = None
1033
+ for ancestor in paragraph.iterancestors():
1034
+ if ancestor.tag == f"{{{_XPATH_NAMESPACES['w']}}}txbxContent":
1035
+ textbox_content = ancestor
1036
+ break
1037
+ if textbox_content is None:
1038
+ return None, None
1039
+ for ancestor in textbox_content.iterancestors():
1040
+ if ancestor.tag in {f"{{{_VML_NAMESPACE}}}shape", f"{{{_XPATH_NAMESPACES['wps']}}}wsp"}:
1041
+ return textbox_content, ancestor
1042
+ return textbox_content, None
1043
+
1044
+
1045
+ def _set_vml_shape_width(shape: Any, width_pt: float) -> None:
1046
+ declarations = [item.strip() for item in shape.get("style", "").split(";") if item.strip()]
1047
+ replacement = f"width:{width_pt:g}pt"
1048
+ replaced = False
1049
+ updated = []
1050
+ for declaration in declarations:
1051
+ property_name, separator, _ = declaration.partition(":")
1052
+ if separator and property_name.strip().lower() == "width":
1053
+ if not replaced:
1054
+ updated.append(replacement)
1055
+ replaced = True
1056
+ continue
1057
+ updated.append(declaration)
1058
+ if not replaced:
1059
+ updated.append(replacement)
1060
+ shape.set("style", ";".join(updated))
1061
+
1062
+
1063
+ def _set_drawingml_shape_width(shape: Any, width_pt: float) -> None:
1064
+ width_emu = str(round(width_pt * 12700))
1065
+ transforms = shape.xpath("./wps:spPr/a:xfrm/a:ext", namespaces=_XPATH_NAMESPACES)
1066
+ if not transforms:
1067
+ raise InputValidationError("caixa de texto DrawingML não contém geometria de largura compatível")
1068
+ for extent in transforms:
1069
+ extent.set("cx", width_emu)
1070
+ for ancestor in shape.iterancestors():
1071
+ if ancestor.tag in {
1072
+ f"{{{_XPATH_NAMESPACES['wp']}}}anchor",
1073
+ f"{{{_XPATH_NAMESPACES['wp']}}}inline",
1074
+ }:
1075
+ extents = ancestor.xpath("./wp:extent", namespaces=_XPATH_NAMESPACES)
1076
+ if extents:
1077
+ extents[0].set("cx", width_emu)
1078
+ break
1079
+
1080
+
1081
+ def _apply_textbox_formatting(textbox_content: Any, shape: Any, formatting: Mapping[str, Any]) -> None:
1082
+ from lxml import etree
1083
+
1084
+ width = formatting.get("largura_pt")
1085
+ if width is not None:
1086
+ if shape.tag == f"{{{_VML_NAMESPACE}}}shape":
1087
+ _set_vml_shape_width(shape, float(width))
1088
+ elif shape.tag == f"{{{_XPATH_NAMESPACES['wps']}}}wsp":
1089
+ _set_drawingml_shape_width(shape, float(width))
1090
+ font_size = formatting.get("tamanho_fonte_pt")
1091
+ if font_size is not None:
1092
+ half_points = str(round(float(font_size) * 2))
1093
+ for run in textbox_content.xpath(".//w:r", namespaces=_XPATH_NAMESPACES):
1094
+ run_properties = run.find(f"{{{_XPATH_NAMESPACES['w']}}}rPr")
1095
+ if run_properties is None:
1096
+ run_properties = etree.Element(f"{{{_XPATH_NAMESPACES['w']}}}rPr")
1097
+ run.insert(0, run_properties)
1098
+ for local_name in ("sz", "szCs"):
1099
+ size = run_properties.find(f"{{{_XPATH_NAMESPACES['w']}}}{local_name}")
1100
+ if size is None:
1101
+ size = etree.SubElement(run_properties, f"{{{_XPATH_NAMESPACES['w']}}}{local_name}")
1102
+ size.set(f"{{{_XPATH_NAMESPACES['w']}}}val", half_points)
1103
+
1104
+
1105
+ def _apply_run_formatting(paragraph: Any, formatting: Mapping[str, Any]) -> None:
1106
+ from docx.oxml import OxmlElement
1107
+ from docx.oxml.ns import qn
1108
+
1109
+ runs = paragraph._p.xpath(".//w:r[w:t]")
1110
+ if not runs:
1111
+ raise InputValidationError("o título do sumário selecionado não contém trechos de texto formatáveis")
1112
+ for run in runs:
1113
+ properties = run.find(qn("w:rPr"))
1114
+ if properties is None:
1115
+ properties = OxmlElement("w:rPr")
1116
+ run.insert(0, properties)
1117
+ if "fonte" in formatting:
1118
+ fonts = properties.find(qn("w:rFonts"))
1119
+ if fonts is None:
1120
+ fonts = OxmlElement("w:rFonts")
1121
+ properties.insert(0, fonts)
1122
+ for attribute in ("ascii", "hAnsi", "eastAsia", "cs"):
1123
+ fonts.set(qn(f"w:{attribute}"), str(formatting["fonte"]))
1124
+ if "tamanho_fonte_pt" in formatting:
1125
+ half_points = str(round(float(formatting["tamanho_fonte_pt"]) * 2))
1126
+ for local_name in ("sz", "szCs"):
1127
+ size = properties.find(qn(f"w:{local_name}"))
1128
+ if size is None:
1129
+ size = OxmlElement(f"w:{local_name}")
1130
+ properties.append(size)
1131
+ size.set(qn("w:val"), half_points)
1132
+ if "cor" in formatting:
1133
+ color = properties.find(qn("w:color"))
1134
+ if color is None:
1135
+ color = OxmlElement("w:color")
1136
+ properties.append(color)
1137
+ color.set(qn("w:val"), str(formatting["cor"]).lstrip("#").upper())
1138
+ color.attrib.pop(qn("w:themeColor"), None)
1139
+ for key, local_name in (("negrito", "b"), ("italico", "i")):
1140
+ if key not in formatting:
1141
+ continue
1142
+ enabled = formatting[key]
1143
+ for target in (local_name, f"{local_name}Cs"):
1144
+ node = properties.find(qn(f"w:{target}"))
1145
+ if node is None:
1146
+ node = OxmlElement(f"w:{target}")
1147
+ properties.append(node)
1148
+ if enabled:
1149
+ node.attrib.pop(qn("w:val"), None)
1150
+ else:
1151
+ node.set(qn("w:val"), "0")
1152
+
1153
+
1154
+ def _apply_fields(
1155
+ package_bytes: bytes,
1156
+ fields: Mapping[str, str],
1157
+ textbox_formatting: Mapping[str, Mapping[str, Any]] | None = None,
1158
+ ) -> bytes:
1159
+ from lxml import etree
1160
+
1161
+ output = BytesIO()
1162
+ counts = {marker: 0 for marker in fields}
1163
+ formatted_counts = {marker: 0 for marker in (textbox_formatting or {})}
1164
+ with ZipFile(BytesIO(package_bytes), "r") as source, ZipFile(output, "w", ZIP_DEFLATED) as target:
1165
+ for item in source.infolist():
1166
+ payload = source.read(item.filename)
1167
+ if item.filename.startswith("word/") and item.filename.endswith(".xml"):
1168
+ root = etree.fromstring(payload)
1169
+ for marker, value in fields.items():
1170
+ paragraphs = root.xpath(".//w:p", namespaces=_XPATH_NAMESPACES)
1171
+ paragraphs.sort(key=lambda paragraph: sum(1 for _ in paragraph.iterancestors()), reverse=True)
1172
+ for paragraph in paragraphs:
1173
+ if not _paragraph_contains_marker(paragraph, marker):
1174
+ continue
1175
+ formatting = (textbox_formatting or {}).get(marker)
1176
+ if formatting:
1177
+ textbox_content, shape = _textbox_for_paragraph(paragraph)
1178
+ if textbox_content is not None and shape is not None:
1179
+ _apply_textbox_formatting(textbox_content, shape, formatting)
1180
+ replaced = _replace_text_marker(paragraph, marker, value)
1181
+ formatted_counts[marker] += replaced
1182
+ counts[marker] += replaced
1183
+ continue
1184
+ replaced = _replace_text_marker(paragraph, marker, value)
1185
+ counts[marker] += replaced
1186
+ payload = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes")
1187
+ target.writestr(item, payload)
1188
+ missing = [marker for marker, count in counts.items() if count == 0]
1189
+ if missing:
1190
+ raise InputValidationError(f"marcadores de campo não encontrados no modelo institucional: {', '.join(missing)}")
1191
+ unformatted = [marker for marker in formatted_counts if formatted_counts[marker] == 0]
1192
+ if unformatted:
1193
+ raise InputValidationError(
1194
+ f"campos com caixa_texto não apareceram em uma caixa de texto compatível: {', '.join(unformatted)}"
1195
+ )
1196
+ with ZipFile(BytesIO(output.getvalue())) as package:
1197
+ for name in package.namelist():
1198
+ if not (name.startswith("word/") and name.endswith(".xml")):
1199
+ continue
1200
+ root = etree.fromstring(package.read(name))
1201
+ text = "".join(root.xpath(".//w:t/text()", namespaces=_XPATH_NAMESPACES))
1202
+ remaining = sorted(set(_MARKER.findall(text)))
1203
+ if remaining:
1204
+ raise InputValidationError(f"marcadores de publicação sem resolução em {name}: {', '.join(remaining)}")
1205
+ return output.getvalue()
1206
+
1207
+
1208
+ def _field_value(context: Mapping[str, Any], path: str, marker: str) -> str:
1209
+ """Valor de um campo de modelo; listas viram uma linha por item."""
1210
+ value: Any = context
1211
+ for key in path.split("."):
1212
+ if isinstance(value, Mapping) and key in value:
1213
+ value = value[key]
1214
+ elif isinstance(value, (list, tuple)) and key.isdigit() and int(key) < len(value):
1215
+ value = value[int(key)]
1216
+ else:
1217
+ raise InputValidationError(
1218
+ f"campo de modelo {marker} não existe: informe {path} em fiscalizacao.yml ou no front matter do Markdown"
1219
+ )
1220
+ if isinstance(value, (list, tuple)):
1221
+ if any(isinstance(item, (Mapping, list, tuple)) or item is None for item in value):
1222
+ raise InputValidationError(f"campo de modelo {marker} deve ser texto ou lista de textos: {path}")
1223
+ text = "\n".join(str(item).strip() for item in value if str(item).strip())
1224
+ elif value is None or isinstance(value, Mapping):
1225
+ raise InputValidationError(f"campo de modelo {marker} deve ser texto ou lista de textos: {path}")
1226
+ else:
1227
+ text = str(value).strip()
1228
+ if not text:
1229
+ raise InputValidationError(
1230
+ f"campo de modelo {marker} está vazio: preencha {path} em fiscalizacao.yml ou no front matter do Markdown"
1231
+ )
1232
+ return text
1233
+
1234
+
1235
+ def _expand_line_breaks(paragraph: Any) -> None:
1236
+ """Converte `\\n` do texto substituído em quebra de linha do Word."""
1237
+ from lxml import etree
1238
+
1239
+ for node in paragraph.xpath(".//w:t", namespaces=_XPATH_NAMESPACES):
1240
+ if "\n" not in (node.text or ""):
1241
+ continue
1242
+ parts = node.text.split("\n")
1243
+ parent = node.getparent()
1244
+ position = parent.index(node)
1245
+ node.text = parts[0]
1246
+ for offset, part in enumerate(parts[1:], start=1):
1247
+ parent.insert(position + 2 * offset - 1, etree.Element(f"{{{_W_NAMESPACE}}}br"))
1248
+ text = etree.Element(f"{{{_W_NAMESPACE}}}t")
1249
+ text.text = part
1250
+ text.set(f"{{{_XML_SPACE}}}space", "preserve")
1251
+ parent.insert(position + 2 * offset, text)
1252
+
1253
+
1254
+ def fill_template_fields(package_bytes: bytes, context: Mapping[str, Any]) -> bytes:
1255
+ """Preenche os campos `[[secao.chave]]` de um DOCX com valores do contexto.
1256
+
1257
+ Vale para corpo, cabeçalhos, rodapés e caixas de texto. Sem campos no modelo, devolve o DOCX intacto.
1258
+ Campo ausente ou vazio interrompe a publicação com o caminho a preencher.
1259
+ """
1260
+ from lxml import etree
1261
+
1262
+ with ZipFile(BytesIO(package_bytes), "r") as source:
1263
+ parts = [name for name in source.namelist() if name.startswith("word/") and name.endswith(".xml")]
1264
+ found: dict[str, set[str]] = {}
1265
+ for name in parts:
1266
+ text = "".join(etree.fromstring(source.read(name)).xpath(".//w:t/text()", namespaces=_XPATH_NAMESPACES))
1267
+ paths = set(_FIELD_MARKER.findall(text))
1268
+ if paths:
1269
+ found[name] = paths
1270
+ if not found:
1271
+ return package_bytes
1272
+ resolved = {
1273
+ path: _field_value(context, path, f"[[{path}]]")
1274
+ for path in sorted({path for paths in found.values() for path in paths})
1275
+ }
1276
+ output = BytesIO()
1277
+ with ZipFile(output, "w", ZIP_DEFLATED) as target:
1278
+ for item in source.infolist():
1279
+ payload = source.read(item.filename)
1280
+ if item.filename in found:
1281
+ root = etree.fromstring(payload)
1282
+ paragraphs = root.xpath(".//w:p", namespaces=_XPATH_NAMESPACES)
1283
+ paragraphs.sort(key=lambda paragraph: sum(1 for _ in paragraph.iterancestors()), reverse=True)
1284
+ for paragraph in paragraphs:
1285
+ combined = "".join(node.text or "" for node in paragraph.xpath(".//w:t", namespaces=_XPATH_NAMESPACES))
1286
+ replaced = False
1287
+ for path in sorted(set(_FIELD_MARKER.findall(combined))):
1288
+ replaced |= bool(_replace_text_marker(paragraph, f"[[{path}]]", resolved[path]))
1289
+ if replaced:
1290
+ _expand_line_breaks(paragraph)
1291
+ payload = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone="yes")
1292
+ target.writestr(item, payload)
1293
+ return output.getvalue()
1294
+
1295
+
1296
+ def _normalize_footnotes(package_bytes: bytes) -> bytes:
1297
+ from docx.oxml.ns import qn
1298
+ from lxml import etree
1299
+
1300
+ output = BytesIO()
1301
+ with ZipFile(BytesIO(package_bytes), "r") as source:
1302
+ names = set(source.namelist())
1303
+ if "word/footnotes.xml" not in names or "word/document.xml" not in names:
1304
+ return package_bytes
1305
+ document_xml = etree.fromstring(source.read("word/document.xml"))
1306
+ notes_xml = etree.fromstring(source.read("word/footnotes.xml"))
1307
+ references = document_xml.xpath(".//w:footnoteReference", namespaces=_XPATH_NAMESPACES)
1308
+ referenced_order: list[str] = []
1309
+ for reference in references:
1310
+ note_id = reference.get(qn("w:id"))
1311
+ if note_id not in referenced_order:
1312
+ referenced_order.append(note_id)
1313
+ definitions = {
1314
+ note.get(qn("w:id")): note
1315
+ for note in notes_xml.findall(f"./{qn('w:footnote')}")
1316
+ }
1317
+ missing = [note_id for note_id in referenced_order if note_id not in definitions]
1318
+ if missing:
1319
+ raise InputValidationError(f"chamadas de notas sem definição após composição: {', '.join(missing)}")
1320
+ mapping = {old: str(index) for index, old in enumerate(referenced_order, start=1)}
1321
+ for reference in references:
1322
+ reference.set(qn("w:id"), mapping[reference.get(qn("w:id"))])
1323
+ special = [
1324
+ note for note in notes_xml.findall(f"./{qn('w:footnote')}")
1325
+ if note.get(qn("w:id")) in {"-1", "0"}
1326
+ ]
1327
+ reordered = [deepcopy(note) for note in special]
1328
+ for old_id in referenced_order:
1329
+ note = deepcopy(definitions[old_id])
1330
+ note.set(qn("w:id"), mapping[old_id])
1331
+ reordered.append(note)
1332
+ for child in list(notes_xml):
1333
+ notes_xml.remove(child)
1334
+ for note in reordered:
1335
+ notes_xml.append(note)
1336
+ document_payload = etree.tostring(document_xml, xml_declaration=True, encoding="UTF-8", standalone="yes")
1337
+ notes_payload = etree.tostring(notes_xml, xml_declaration=True, encoding="UTF-8", standalone="yes")
1338
+ with ZipFile(output, "w", ZIP_DEFLATED) as target, ZipFile(BytesIO(package_bytes), "r") as source:
1339
+ for item in source.infolist():
1340
+ payload = source.read(item.filename)
1341
+ if item.filename == "word/document.xml":
1342
+ payload = document_payload
1343
+ elif item.filename == "word/footnotes.xml":
1344
+ payload = notes_payload
1345
+ target.writestr(item, payload)
1346
+ return output.getvalue()
1347
+
1348
+
1349
+ def _prune_unused_media(package_bytes: bytes) -> bytes:
1350
+ from lxml import etree
1351
+
1352
+ output = BytesIO()
1353
+ with ZipFile(BytesIO(package_bytes), "r") as source:
1354
+ names = set(source.namelist())
1355
+ changed_relationships: dict[str, bytes] = {}
1356
+ used_media: set[str] = set()
1357
+ for relationship_path in sorted(name for name in names if name.endswith(".rels")):
1358
+ if "/_rels/" not in relationship_path:
1359
+ continue
1360
+ prefix, filename = relationship_path.rsplit("/_rels/", 1)
1361
+ owner = join(prefix, filename.removesuffix(".rels"))
1362
+ owner_xml = etree.fromstring(source.read(owner)) if owner in names and owner.endswith(".xml") else None
1363
+ referenced_ids = set()
1364
+ if owner_xml is not None:
1365
+ for node in owner_xml.xpath(".//*[@r:id or @r:embed or @r:link]", namespaces=_XPATH_NAMESPACES):
1366
+ for attribute in ("id", "embed", "link"):
1367
+ value = node.get(f"{{{_XPATH_NAMESPACES['r']}}}{attribute}")
1368
+ if value:
1369
+ referenced_ids.add(value)
1370
+ relations = etree.fromstring(source.read(relationship_path))
1371
+ changed = False
1372
+ for relation in list(relations):
1373
+ if not relation.get("Type", "").endswith("/image") or relation.get("TargetMode") == "External":
1374
+ continue
1375
+ target = relation.get("Target", "")
1376
+ target_path = normpath(target.lstrip("/") if target.startswith("/") else join(dirname(owner), target))
1377
+ if relation.get("Id") not in referenced_ids:
1378
+ relations.remove(relation)
1379
+ changed = True
1380
+ elif target_path.startswith("word/media/"):
1381
+ used_media.add(target_path)
1382
+ if changed:
1383
+ changed_relationships[relationship_path] = etree.tostring(
1384
+ relations, xml_declaration=True, encoding="UTF-8", standalone="yes"
1385
+ )
1386
+ removed_media = {name for name in names if name.startswith("word/media/")} - used_media
1387
+ with ZipFile(output, "w", ZIP_DEFLATED) as target:
1388
+ for item in source.infolist():
1389
+ if item.filename in removed_media:
1390
+ continue
1391
+ payload = changed_relationships.get(item.filename)
1392
+ if payload is None:
1393
+ payload = source.read(item.filename)
1394
+ target.writestr(item, payload)
1395
+ return output.getvalue()
1396
+
1397
+
1398
+ def compose_report_document(
1399
+ body_docx: bytes,
1400
+ config_path: Path,
1401
+ context: Mapping[str, Any],
1402
+ *,
1403
+ layout: Any = None,
1404
+ ) -> tuple[bytes, dict[str, Any]]:
1405
+ """Aplica o modelo, slots e campos da configuração de publicação a um corpo DOCX."""
1406
+ from docx import Document
1407
+
1408
+ config = _load_config(config_path)
1409
+ if layout is None:
1410
+ layout = config.get("layout_documento")
1411
+ model_path, resolved_insertions = _resolve_resources(config, config_path)
1412
+ master = Document(str(model_path))
1413
+ source_document = Document(BytesIO(body_docx))
1414
+ body_marker = str(config["corpo"]["marcador"])
1415
+ body_target = _unique_paragraph(master, body_marker, label="do corpo")
1416
+ appendix_target = None
1417
+ appendix_config = config.get("anexos")
1418
+ end_selector = appendix_config.get("inicio") if appendix_config else None
1419
+ if appendix_config:
1420
+ appendix_target = _unique_paragraph(master, str(appendix_config["marcador"]), label="dos anexos")
1421
+ appendix_matches = _matching_paragraphs(source_document, end_selector)
1422
+ if len(appendix_matches) != 1:
1423
+ raise InputValidationError(f"âncora de início dos anexos deve ocorrer uma vez (encontrado: {len(appendix_matches)})")
1424
+ start_matches = _matching_paragraphs(source_document, config["corpo"]["inicio"])
1425
+ if len(start_matches) != 1:
1426
+ raise InputValidationError(f"âncora de início do corpo deve ocorrer uma vez (encontrado: {len(start_matches)})")
1427
+ if appendix_config:
1428
+ end_matches = _matching_paragraphs(source_document, end_selector)
1429
+ if source_document.element.body.index(end_matches[0]) <= source_document.element.body.index(start_matches[0]):
1430
+ raise InputValidationError("âncora dos anexos deve vir depois do início do corpo")
1431
+
1432
+ image_inputs: list[dict[str, str]] = []
1433
+ for insertion, images in resolved_insertions:
1434
+ _add_images(master, str(insertion["marcador"]), images, insertion)
1435
+ for path in images:
1436
+ image_inputs.append({"path": str(path), "sha256": _file_sha256(path)})
1437
+
1438
+ table_tasks = []
1439
+ for table_spec in config.get("tabelas") or []:
1440
+ target = _table_by_marker(master, str(table_spec["marcador"]))
1441
+ target_layout = deepcopy(target)
1442
+ segment = _source_table(body_docx, table_spec["indice_origem"])
1443
+ table_tasks.append(_Insertion(target, segment, "table", target_layout, table_spec.get("formatacao")))
1444
+ body_segment = _source_segment(
1445
+ body_docx,
1446
+ config["corpo"]["inicio"],
1447
+ end_selector,
1448
+ boundary_page_break="end" if end_selector is not None else None,
1449
+ )
1450
+ target_properties = body_target.find("{http://schemas.openxmlformats.org/wordprocessingml/2006/main}pPr")
1451
+ if target_properties is not None and target_properties.find(
1452
+ "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}pageBreakBefore"
1453
+ ) is not None:
1454
+ first_source_block = next(
1455
+ (
1456
+ child
1457
+ for child in body_segment.element.body
1458
+ if child.tag.rsplit("}", 1)[-1] != "sectPr"
1459
+ ),
1460
+ None,
1461
+ )
1462
+ if first_source_block is not None and first_source_block.tag.rsplit("}", 1)[-1] == "p":
1463
+ _set_page_break_before(first_source_block)
1464
+ tasks = table_tasks + [_Insertion(body_target, body_segment, "body")]
1465
+ if appendix_config and appendix_target is not None:
1466
+ appendices = _source_segment(body_docx, end_selector, None, boundary_page_break="start")
1467
+ tasks.append(_Insertion(appendix_target, appendices, "appendix"))
1468
+
1469
+ composer = _composer_class()(master)
1470
+ for task in sorted(tasks, key=lambda item: master.element.body.index(item.target), reverse=True):
1471
+ index = master.element.body.index(task.target)
1472
+ inserted_count = sum(1 for element in task.source.element.body if element.tag.rsplit("}", 1)[-1] != "sectPr")
1473
+ composer.insert(index, task.source)
1474
+ if inserted_count == 0:
1475
+ raise InputValidationError(f"slot {task.kind} não recebeu conteúdo")
1476
+ body = master.element.body
1477
+ inserted_elements = list(body)[index : index + inserted_count]
1478
+ if task.kind == "table":
1479
+ if len(inserted_elements) != 1 or inserted_elements[0].tag.rsplit("}", 1)[-1] != "tbl":
1480
+ raise InputValidationError("slot de tabela deve receber exatamente uma tabela DOCX")
1481
+ _copy_table_layout(inserted_elements[0], task.target_layout, task.table_formatting)
1482
+ body.remove(task.target)
1483
+
1484
+ _position_figure_notes(master, config.get("notas_legenda") or [])
1485
+
1486
+ toc_title = (config.get("sumario") or {}).get("titulo")
1487
+ if toc_title:
1488
+ from docx.text.paragraph import Paragraph
1489
+
1490
+ selector = {key: toc_title[key] for key in ("texto", "estilo") if key in toc_title}
1491
+ matches = _matching_paragraphs(master, selector)
1492
+ if len(matches) != 1:
1493
+ raise InputValidationError(
1494
+ f"sumario.titulo deve selecionar um parágrafo do documento (encontrado: {len(matches)})"
1495
+ )
1496
+ paragraph = Paragraph(matches[0], master)
1497
+ _apply_run_formatting(paragraph, toc_title["formatacao"])
1498
+
1499
+ if layout is not None:
1500
+ from .docx_pdf import apply_report_layout
1501
+
1502
+ apply_report_layout(master, layout)
1503
+
1504
+ output = BytesIO()
1505
+ composer.save(output)
1506
+ composed = fill_template_fields(_prune_unused_media(_normalize_footnotes(output.getvalue())), context)
1507
+ configured_fields = config.get("campos") or {}
1508
+ field_values = _field_values(configured_fields, context)
1509
+ textbox_formatting = {
1510
+ str(marker): source["caixa_texto"]
1511
+ for marker, source in configured_fields.items()
1512
+ if source.get("caixa_texto")
1513
+ }
1514
+ final = _apply_fields(composed, field_values, textbox_formatting)
1515
+ sources = [{"path": str(model_path), "sha256": _file_sha256(model_path)}, *image_inputs]
1516
+ return final, {
1517
+ "config": {"path": str(config_path), "sha256": _file_sha256(config_path)},
1518
+ "model": {"path": str(model_path), "sha256": _file_sha256(model_path)},
1519
+ "resources": image_inputs,
1520
+ "sumario": dict(config["sumario"]) if "sumario" in config else {"atualizar": None},
1521
+ "sources": sources,
1522
+ }
1523
+
1524
+
1525
+ def _file_sha256(path: Path) -> str:
1526
+ digest = sha256()
1527
+ with path.open("rb") as file:
1528
+ for chunk in iter(lambda: file.read(1024 * 1024), b""):
1529
+ digest.update(chunk)
1530
+ return digest.hexdigest()