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,2953 @@
1
+ """Renderização Markdown→DOCX, templates OOXML e conversão DOCX→PDF."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import tempfile
11
+
12
+ import io
13
+ import re
14
+ import zipfile
15
+ from hashlib import sha256
16
+ from pathlib import Path
17
+ from typing import Any, Iterable, Mapping
18
+ from ..errors import InputValidationError
19
+ import json
20
+ import unicodedata
21
+ from math import isfinite
22
+ from html import escape as escape_html
23
+ from html.parser import HTMLParser
24
+ from typing import Callable
25
+ from urllib.parse import quote, unquote, urlparse
26
+
27
+ _EMU_PER_POINT = 12_700
28
+
29
+
30
+ def render_docx_template(template_path: Path, context: Mapping[str, Any]) -> bytes:
31
+ """Renderiza um template DOCX (docxtpl) e devolve os bytes do documento."""
32
+ try:
33
+ from docxtpl import DocxTemplate
34
+ except ImportError as exc: # pragma: no cover - opcional no pacote base
35
+ raise InputValidationError(
36
+ "templates DOCX requerem docxtpl; instale argos-cli[reports]"
37
+ ) from exc
38
+ try:
39
+ document = DocxTemplate(str(template_path))
40
+ document.render(dict(context))
41
+ except Exception as exc: # noqa: BLE001 - preserva o erro do template no evento
42
+ raise InputValidationError(f"falha ao renderizar template DOCX {template_path}: {exc}") from exc
43
+ buffer = io.BytesIO()
44
+ document.save(buffer)
45
+ return buffer.getvalue()
46
+
47
+
48
+ def _mark_update_fields_entries(entries: Mapping[str, bytes]) -> dict[str, bytes]:
49
+ settings_name = "word/settings.xml"
50
+ if settings_name in entries:
51
+ settings_text = entries[settings_name].decode("utf-8")
52
+ else:
53
+ settings_text = (
54
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
55
+ '<w:settings xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
56
+ "</w:settings>"
57
+ )
58
+
59
+ update_fields = '<w:updateFields w:val="true"/>'
60
+ if "<w:updateFields" in settings_text:
61
+ settings_text = re.sub(
62
+ r"<w:updateFields\b[^>]*/>",
63
+ update_fields,
64
+ settings_text,
65
+ count=1,
66
+ )
67
+ settings_text = re.sub(
68
+ r"<w:updateFields\b[^>]*>.*?</w:updateFields>",
69
+ update_fields,
70
+ settings_text,
71
+ count=1,
72
+ flags=re.DOTALL,
73
+ )
74
+ elif "</w:settings>" in settings_text:
75
+ settings_text = settings_text.replace("</w:settings>", update_fields + "</w:settings>", 1)
76
+ else:
77
+ raise InputValidationError(
78
+ "settings.xml inválido: elemento </w:settings> ausente no DOCX"
79
+ )
80
+
81
+ entries = dict(entries)
82
+ entries[settings_name] = settings_text.encode("utf-8")
83
+ return entries
84
+
85
+
86
+ def mark_update_fields(docx_bytes: bytes) -> bytes:
87
+ """Marca ``w:updateFields`` no DOCX para o Word atualizar campos ao abrir."""
88
+ with zipfile.ZipFile(io.BytesIO(docx_bytes), "r") as source:
89
+ entries = {name: source.read(name) for name in source.namelist()}
90
+
91
+ entries = _mark_update_fields_entries(entries)
92
+
93
+ output = io.BytesIO()
94
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as target:
95
+ for name, data in entries.items():
96
+ target.writestr(name, data)
97
+ return output.getvalue()
98
+
99
+
100
+ def build_docx_zip(
101
+ entries: Iterable[tuple[str, bytes]],
102
+ *,
103
+ compression: int = zipfile.ZIP_STORED,
104
+ ) -> bytes:
105
+ """Monta o ZIP de anexos DOCX em memória."""
106
+ output = io.BytesIO()
107
+ with zipfile.ZipFile(output, "w", compression=compression) as archive:
108
+ for filename, content in entries:
109
+ archive.writestr(filename, content)
110
+ return output.getvalue()
111
+
112
+
113
+ _FRONT_MATTER = re.compile(r"\A---\s*\n(?P<metadata>.*?)\n---\s*(?:\n|$)", re.DOTALL)
114
+ _FOOTNOTE_DEFINITION = re.compile(r"^\[\^(?P<id>[^]]+)\]:\s*(?P<text>.*)$")
115
+ _FOOTNOTE_REFERENCE = re.compile(r"\[\^(?P<id>[^]]+)\]")
116
+ _FOOTNOTE_MARKER = re.compile(r"\ue000(?P<number>\d+)\ue001")
117
+ _CROSS_REFERENCE = re.compile(r"\{#(?P<kind>fig|tbl):(?P<decl>[^#]+)#\}|\[@(?P<refkind>fig|tbl):(?P<ref>[^]]+)\]")
118
+ _IMAGE_LINE = re.compile(
119
+ r"^(?P<indent>[ \t]*)!\[(?P<alt>(?:\\.|[^\]])*)\]"
120
+ r"\((?P<source>[^)\n]+)\)(?P<attrs>(?:\{[^}\n]*\})*)[ \t]*$"
121
+ )
122
+ _TABLE_CAPTION = re.compile(
123
+ r"^(?P<indent>[ \t]*)(?::|Table:)\s*(?P<caption>.*?)\s*\{#tbl:(?P<id>[^#]+)#\}\s*$",
124
+ re.IGNORECASE,
125
+ )
126
+ _TOC_OPEN = re.compile(r"^ {0,3}:{3,}[ \t]*\{\.toc\}[ \t]*(?:\r?\n)?$")
127
+ _TOC_CLOSE = re.compile(r"^ {0,3}:{3,}[ \t]*(?:\r?\n)?$")
128
+ _PAGE_BREAK = re.compile(r"(?m)^[ \t]*\\newpage(?:\{\})?[ \t]*$")
129
+ _INLINE_CODE = re.compile(r"(`+).*?\1")
130
+ _UNDERLINE = re.compile(r"(?<!_)__(.+?)__(?!_)")
131
+ _HONORIFIC_NAME_SPACE = re.compile(
132
+ r"\b(?P<title>Sr)\.(?P<space>[ \t]+)(?=[^\W\d_])",
133
+ re.IGNORECASE,
134
+ )
135
+ _COMPACT_ABBREVIATION_SPACE = re.compile(
136
+ r"\b(?P<abbreviation>p|vs)\.(?P<space>[ \t]+)(?=\S)", re.IGNORECASE
137
+ )
138
+ _ENUMERATION_SENTENCE_SPACE = re.compile(
139
+ r"(?P<item>[,;][ \t]*[A-Za-z])\.(?P<space>[ \t]+)(?=[A-ZÀ-ÖØ-Þ])"
140
+ )
141
+
142
+
143
+ class _HTMLText(HTMLParser):
144
+ def __init__(self) -> None:
145
+ super().__init__(convert_charrefs=True)
146
+ self.parts: list[str] = []
147
+ self.elements: list[tuple[str, dict[str, str | None]]] = []
148
+
149
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
150
+ self.elements.append((tag.casefold(), {key.casefold(): value for key, value in attrs}))
151
+
152
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
153
+ self.handle_starttag(tag, attrs)
154
+
155
+ def handle_data(self, data: str) -> None:
156
+ self.parts.append(data)
157
+
158
+
159
+ def _parse_scalar(value: str) -> str:
160
+ value = value.strip()
161
+ if value.startswith('"') and value.endswith('"'):
162
+ try:
163
+ parsed = json.loads(value)
164
+ if isinstance(parsed, str):
165
+ return parsed
166
+ except ValueError:
167
+ pass
168
+ if value.startswith("'") and value.endswith("'"):
169
+ return value[1:-1].replace("''", "'")
170
+ return value
171
+
172
+
173
+ def _take_front_matter(markdown: str) -> tuple[str, dict[str, str]]:
174
+ match = _FRONT_MATTER.match(markdown)
175
+ if not match:
176
+ return markdown, {}
177
+ metadata: dict[str, str] = {}
178
+ for line in match.group("metadata").splitlines():
179
+ key, separator, value = line.partition(":")
180
+ if separator and key.strip():
181
+ metadata[key.strip().casefold()] = _parse_scalar(value)
182
+ return markdown[match.end():], metadata
183
+
184
+
185
+ def _markdown_code_lines(markdown: str) -> set[int]:
186
+ """Localiza código real, inclusive dentro de listas e citações."""
187
+ try:
188
+ from markdown_it import MarkdownIt
189
+ except ImportError:
190
+ # Snapshots also inspect Markdown without the optional reports extra.
191
+ # Including literal-code resources is conservative; rendering validates
192
+ # its own required dependencies before calling this helper.
193
+ return set()
194
+
195
+ return {
196
+ line
197
+ for token in MarkdownIt("commonmark").enable("table").parse(markdown)
198
+ if token.type in {"fence", "code_block"} and token.map
199
+ for line in range(*token.map)
200
+ }
201
+
202
+
203
+ def _container_prefix(line: str) -> tuple[str, str, str]:
204
+ """Separa marcadores de contêiner da linha e preserva sua continuação."""
205
+ first = ""
206
+ following = ""
207
+ while line:
208
+ match = re.match(r"([ \t]+|>[ \t]?|(?:[-+*]|\d+[.)])[ \t]+)", line)
209
+ if match is None:
210
+ break
211
+ part = match.group(0)
212
+ first += part
213
+ following += " " * len(part) if re.match(r"(?:[-+*]|\d+[.)])[ \t]+", part) else part
214
+ line = line[len(part):]
215
+ return first, following, line
216
+
217
+
218
+ def _map_unfenced_lines(markdown: str, transform: Callable[[str], str]) -> str:
219
+ """Transforma conteúdo Markdown preservando contêineres e código literal."""
220
+ code_lines = _markdown_code_lines(markdown)
221
+ output: list[str] = []
222
+ for number, line in enumerate(markdown.splitlines(keepends=True)):
223
+ if number in code_lines:
224
+ output.append(line)
225
+ continue
226
+ newline = "\n" if line.endswith("\n") else ""
227
+ body = line[:-1] if newline else line
228
+ first, following, body = _container_prefix(body)
229
+ protected: list[str] = []
230
+
231
+ def hold_code(match: re.Match[str]) -> str:
232
+ marker = f"\x01ARGOSCODE{len(protected)}\x02"
233
+ protected.append(match.group(0))
234
+ return marker
235
+
236
+ body = transform(_INLINE_CODE.sub(hold_code, body))
237
+ for position, code in enumerate(protected):
238
+ body = body.replace(f"\x01ARGOSCODE{position}\x02", code)
239
+ lines = body.split("\n")
240
+ output.append(first + lines[0])
241
+ output.extend("\n" + following + value for value in lines[1:])
242
+ output.append(newline)
243
+ return "".join(output)
244
+
245
+
246
+ def _visible_markdown(markdown: str) -> str:
247
+ """Texto indexável: código real e spans literais não declaram referências."""
248
+ code_lines = _markdown_code_lines(markdown)
249
+ output: list[str] = []
250
+ for number, line in enumerate(markdown.splitlines(keepends=True)):
251
+ newline = "\n" if line.endswith("\n") else ""
252
+ if number in code_lines:
253
+ output.append(newline)
254
+ else:
255
+ body = line[:-1] if newline else line
256
+ output.append(_INLINE_CODE.sub(lambda match: " " * len(match.group(0)), body) + newline)
257
+ return "".join(output)
258
+
259
+
260
+ def _extract_footnotes(markdown: str) -> tuple[str, dict[str, str]]:
261
+ body: list[str] = []
262
+ notes: dict[str, list[str]] = {}
263
+ current: str | None = None
264
+ for line in markdown.splitlines():
265
+ definition = _FOOTNOTE_DEFINITION.match(line)
266
+ if definition:
267
+ current = definition.group("id")
268
+ if current in notes:
269
+ raise InputValidationError(f"definição de nota repetida: {current}")
270
+ notes[current] = [definition.group("text")]
271
+ elif current is not None and (line.startswith((" ", "\t")) or not line.strip()):
272
+ notes[current].append(line.strip())
273
+ else:
274
+ current = None
275
+ body.append(line)
276
+ return "\n".join(body), {key: "\n".join(value).strip() for key, value in notes.items()}
277
+
278
+
279
+ def _replace_toc_directive(markdown: str, *, depth: str, title: str) -> str:
280
+ """Substitui o bloco Pandoc de sumário sem tocar exemplos em código."""
281
+ lines = markdown.splitlines(keepends=True)
282
+ output: list[str] = []
283
+ index = 0
284
+ fence_character: str | None = None
285
+ fence_size = 0
286
+ replacement = f'<argos-toc depth="{depth}" title="{escape_html(title, quote=True)}" />\n\n'
287
+ while index < len(lines):
288
+ line = lines[index]
289
+ fence = re.match(r"^ {0,3}(`{3,}|~{3,})", line)
290
+ if fence_character is not None:
291
+ output.append(line)
292
+ if fence and fence.group(1)[0] == fence_character and len(fence.group(1)) >= fence_size:
293
+ fence_character = None
294
+ fence_size = 0
295
+ index += 1
296
+ continue
297
+ if fence:
298
+ fence_character = fence.group(1)[0]
299
+ fence_size = len(fence.group(1))
300
+ output.append(line)
301
+ index += 1
302
+ continue
303
+ if not _TOC_OPEN.match(line):
304
+ output.append(line)
305
+ index += 1
306
+ continue
307
+ cursor = index + 1
308
+ while cursor < len(lines) and not lines[cursor].strip():
309
+ cursor += 1
310
+ if cursor < len(lines) and _TOC_CLOSE.match(lines[cursor]):
311
+ output.append(replacement)
312
+ index = cursor + 1
313
+ continue
314
+ output.append(line)
315
+ index += 1
316
+ return "".join(output)
317
+
318
+
319
+ def _note_pending(markdown: str, footnotes: Mapping[str, str]) -> list[dict[str, str]]:
320
+ return [
321
+ {"type": "unresolved_document_note", "reference": identifier}
322
+ for identifier in dict.fromkeys(match.group("id") for match in _FOOTNOTE_REFERENCE.finditer(_visible_markdown(markdown)))
323
+ if identifier not in footnotes
324
+ ]
325
+
326
+
327
+ def _prepare_markdown(
328
+ markdown: str,
329
+ ) -> tuple[
330
+ str,
331
+ dict[str, str],
332
+ dict[tuple[str, str], list[str]],
333
+ dict[str, str],
334
+ dict[str, int],
335
+ list[dict[str, str]],
336
+ ]:
337
+ markdown, metadata = _take_front_matter(markdown)
338
+ markdown, footnotes = _extract_footnotes(markdown)
339
+ reference_source = _visible_markdown(markdown + "\n" + "\n".join(footnotes.values()))
340
+ declarations = {kind: set() for kind in ("fig", "tbl")}
341
+ numbers: dict[str, dict[str, int]] = {kind: {} for kind in ("fig", "tbl")}
342
+ duplicate_declarations: list[dict[str, str]] = []
343
+ for match in _CROSS_REFERENCE.finditer(reference_source):
344
+ is_declaration = match.group("decl") is not None
345
+ kind = match.group("kind") if is_declaration else match.group("refkind")
346
+ identifier = match.group("decl") if is_declaration else match.group("ref")
347
+ if is_declaration:
348
+ if identifier in declarations[kind]:
349
+ duplicate_declarations.append({"type": "duplicate_document_reference", "kind": kind, "reference": identifier})
350
+ declarations[kind].add(identifier)
351
+ if identifier not in numbers[kind]:
352
+ # The legacy Pandoc preprocessor numbers IDs by their first textual
353
+ # reference or declaration. Preserve that ordering for valid docs.
354
+ numbers[kind][identifier] = len(numbers[kind]) + 1
355
+
356
+ pending: list[dict[str, str]] = list(duplicate_declarations)
357
+ for match in _CROSS_REFERENCE.finditer(reference_source):
358
+ if match.group("decl") is None:
359
+ kind = match.group("refkind")
360
+ identifier = match.group("ref")
361
+ if identifier not in declarations[kind]:
362
+ pending.append({"type": "unresolved_document_reference", "kind": kind, "reference": identifier})
363
+ pending.extend(_note_pending(reference_source, footnotes))
364
+ pending_keys: set[tuple[tuple[str, str], ...]] = set()
365
+ unique_pending: list[dict[str, str]] = []
366
+ for item in pending:
367
+ key = tuple(sorted(item.items()))
368
+ if key not in pending_keys:
369
+ pending_keys.add(key)
370
+ unique_pending.append(item)
371
+ pending = unique_pending
372
+ image_widths: dict[tuple[str, str], list[str]] = {}
373
+
374
+ def image_attributes(line: str) -> str:
375
+ match = _IMAGE_LINE.match(line)
376
+ if not match:
377
+ return line
378
+ raw_source = match.group("source").strip()
379
+ source = raw_source[1:-1] if raw_source.startswith("<") and raw_source.endswith(">") else raw_source
380
+ source_key = unquote(source)
381
+ alt = match.group("alt")
382
+ attributes = re.findall(r"\{([^{}]*)\}", match.group("attrs"))
383
+ figure_id = None
384
+ width = None
385
+ unknown: list[str] = []
386
+ for attribute in attributes:
387
+ figure = re.fullmatch(r"#fig:([^#]+)#?", attribute.strip())
388
+ width_match = re.fullmatch(r"width\s*=\s*([^\s]+)", attribute.strip())
389
+ if figure:
390
+ figure_id = figure.group(1)
391
+ elif width_match:
392
+ width = width_match.group(1)
393
+ elif attribute.strip():
394
+ unknown.append(attribute.strip())
395
+ if width:
396
+ image_widths.setdefault((source_key, alt), []).append(width)
397
+ if unknown:
398
+ pending.extend(
399
+ {"type": "unsupported_document_attribute", "attribute": item, "resource": source}
400
+ for item in unknown
401
+ )
402
+ replacement = f"{match.group('indent')}![{alt}]({match.group('source')})"
403
+ if figure_id is None:
404
+ return replacement
405
+ number = numbers["fig"].get(figure_id)
406
+ if number is None or figure_id not in declarations["fig"]:
407
+ pending.append({"type": "unresolved_document_reference", "kind": "fig", "reference": figure_id})
408
+ return replacement
409
+ caption = f"Figura {number} - {alt} <!--argos-figure:{figure_id}-->"
410
+ if metadata.get("figure-caption-position", "above").casefold() == "below":
411
+ return f"{replacement}\n\n{match.group('indent')}{caption}"
412
+ return f"{match.group('indent')}{caption}\n\n{replacement}"
413
+
414
+ markdown = _map_unfenced_lines(markdown, image_attributes)
415
+
416
+ def table_caption(match: re.Match[str]) -> str:
417
+ identifier = match.group("id")
418
+ number = numbers["tbl"].get(identifier)
419
+ if number is None or identifier not in declarations["tbl"]:
420
+ pending.append({"type": "unresolved_document_reference", "kind": "tbl", "reference": identifier})
421
+ return match.group(0)
422
+ return f"{match.group('indent')}Tabela {number} - {match.group('caption')}"
423
+
424
+ def convert_table_caption(line: str) -> str:
425
+ match = _TABLE_CAPTION.match(line)
426
+ return table_caption(match) if match else line
427
+
428
+ markdown = _map_unfenced_lines(markdown, convert_table_caption)
429
+
430
+ def expand_cross_references(value: str) -> str:
431
+ def replace(match: re.Match[str]) -> str:
432
+ if match.group("decl") is not None:
433
+ return match.group(0)
434
+ kind = match.group("refkind")
435
+ identifier = match.group("ref")
436
+ if identifier not in numbers[kind] or identifier not in declarations[kind]:
437
+ return match.group(0)
438
+ return f"{'Figura' if kind == 'fig' else 'Tabela'} {numbers[kind][identifier]}"
439
+ return _CROSS_REFERENCE.sub(replace, value)
440
+
441
+ markdown = _map_unfenced_lines(markdown, expand_cross_references)
442
+ footnotes = {key: _map_unfenced_lines(value, expand_cross_references) for key, value in footnotes.items()}
443
+
444
+ # Assign note numbers by their first appearance in the body, then replace
445
+ # markers in both body and note text without touching code blocks.
446
+ note_order: list[str] = []
447
+ def replace_note_line(line: str) -> str:
448
+ for match in _FOOTNOTE_REFERENCE.finditer(line):
449
+ identifier = match.group("id")
450
+ if identifier in footnotes and identifier not in note_order:
451
+ note_order.append(identifier)
452
+ return line
453
+
454
+ markdown = _map_unfenced_lines(markdown, replace_note_line)
455
+ for value in footnotes.values():
456
+ _map_unfenced_lines(value, replace_note_line)
457
+ note_numbers = {identifier: number for number, identifier in enumerate(note_order, start=1)}
458
+
459
+ def replace_note_refs(value: str) -> str:
460
+ def replace(match: re.Match[str]) -> str:
461
+ number = note_numbers.get(match.group("id"))
462
+ return f"\ue000{number}\ue001" if number is not None else match.group(0)
463
+ return _map_unfenced_lines(value, lambda line: _FOOTNOTE_REFERENCE.sub(replace, line))
464
+
465
+ markdown = replace_note_refs(markdown)
466
+ footnotes = {key: replace_note_refs(value) for key, value in footnotes.items()}
467
+ markdown = _map_unfenced_lines(markdown, lambda line: _UNDERLINE.sub(r"<u>\1</u>", line))
468
+ footnotes = {key: _map_unfenced_lines(value, lambda line: _UNDERLINE.sub(r"<u>\1</u>", line)) for key, value in footnotes.items()}
469
+ markdown = _map_unfenced_lines(markdown, lambda line: _PAGE_BREAK.sub("<argos-page-break />", line))
470
+ toc_depth = metadata.get("toc-depth", "3")
471
+ toc_title = metadata.get("toc-title", "SUMÁRIO")
472
+ try:
473
+ toc_depth = str(max(1, min(int(toc_depth), 9)))
474
+ except ValueError:
475
+ toc_depth = "3"
476
+ markdown = _replace_toc_directive(markdown, depth=toc_depth, title=toc_title)
477
+ # A completed publication must not leak unprocessed declarations or refs.
478
+ known = {(item.get("kind"), item.get("reference")) for item in pending}
479
+ for match in _CROSS_REFERENCE.finditer(_visible_markdown(markdown + "\n" + "\n".join(footnotes.values()))):
480
+ kind = match.group("kind") or match.group("refkind")
481
+ identifier = match.group("decl") or match.group("ref")
482
+ if (kind, identifier) not in known:
483
+ pending.append({"type": "unprocessed_document_reference", "kind": kind, "reference": identifier})
484
+ known.add((kind, identifier))
485
+ return markdown, metadata, image_widths, footnotes, note_numbers, pending
486
+
487
+
488
+ def _normalize_style_name(value: str) -> str:
489
+ decomposed = unicodedata.normalize("NFKD", value.casefold())
490
+ return " ".join("".join(char for char in decomposed if not unicodedata.combining(char)).split())
491
+
492
+
493
+ def _apply_paragraph_style(paragraph: Any, document: Any, *names: str) -> bool:
494
+ style = _find_style(document, *names)
495
+ if style is None:
496
+ return False
497
+ paragraph.style = style
498
+ return True
499
+
500
+
501
+ def _find_style(document: Any, *names: str) -> Any | None:
502
+ styles = list(document.styles)
503
+ for name in names:
504
+ for style in styles:
505
+ if str(style.style_id).casefold() == name.casefold():
506
+ return style
507
+ for name in names:
508
+ candidate = _normalize_style_name(name)
509
+ for style in styles:
510
+ if _normalize_style_name(str(style.name)) == candidate:
511
+ return style
512
+ return None
513
+
514
+
515
+ class _DocxListNumbering:
516
+ """Numeração OOXML por lista; níveis e reinícios pertencem ao documento."""
517
+
518
+ def __init__(self, document: Any):
519
+ self.root = document.part.numbering_part.element
520
+ self.abstracts: dict[tuple[bool, str, tuple[str, str] | None], int] = {}
521
+
522
+ def new_list(
523
+ self,
524
+ *,
525
+ ordered: bool,
526
+ start: int,
527
+ level: int,
528
+ delimiter: str,
529
+ bullet_style: tuple[str, str] | None = None,
530
+ ) -> int:
531
+ from docx.oxml import OxmlElement
532
+ from docx.oxml.ns import qn
533
+
534
+ key = ordered, delimiter, bullet_style
535
+ if key not in self.abstracts:
536
+ existing = [int(value) for value in self.root.xpath("./w:abstractNum/@w:abstractNumId")]
537
+ identifier = max(existing, default=-1) + 1
538
+ abstract = OxmlElement("w:abstractNum")
539
+ abstract.set(qn("w:abstractNumId"), str(identifier))
540
+ kind = OxmlElement("w:multiLevelType")
541
+ kind.set(qn("w:val"), "multilevel")
542
+ abstract.append(kind)
543
+ for depth in range(9):
544
+ node = OxmlElement("w:lvl")
545
+ node.set(qn("w:ilvl"), str(depth))
546
+ if bullet_style is None:
547
+ bullet, font = (("\uf0b7", "Symbol"), ("o", "Courier New"), ("\uf0a7", "Wingdings"))[depth % 3]
548
+ else:
549
+ bullet, font = bullet_style
550
+ for tag, value in (("start", "1"), ("numFmt", "decimal" if ordered else "bullet"),
551
+ ("lvlText", f"%{depth + 1}{delimiter}" if ordered else bullet), ("lvlJc", "left")):
552
+ child = OxmlElement("w:" + tag)
553
+ child.set(qn("w:val"), value)
554
+ node.append(child)
555
+ properties = OxmlElement("w:pPr")
556
+ indent = OxmlElement("w:ind")
557
+ indent.set(qn("w:left"), str(720 * (depth + 1)))
558
+ indent.set(qn("w:hanging"), "360")
559
+ properties.append(indent)
560
+ node.append(properties)
561
+ if not ordered:
562
+ run = OxmlElement("w:rPr")
563
+ fonts = OxmlElement("w:rFonts")
564
+ for attribute in ("ascii", "hAnsi", "cs"):
565
+ fonts.set(qn("w:" + attribute), font)
566
+ run.append(fonts)
567
+ node.append(run)
568
+ abstract.append(node)
569
+ # Abstract definitions precede concrete numbering instances.
570
+ first_num = self.root.find(qn("w:num"))
571
+ if first_num is None:
572
+ self.root.append(abstract)
573
+ else:
574
+ first_num.addprevious(abstract)
575
+ self.abstracts[key] = identifier
576
+ nums = [int(value) for value in self.root.xpath("./w:num/@w:numId")]
577
+ identifier = max(nums, default=0) + 1
578
+ num = OxmlElement("w:num")
579
+ num.set(qn("w:numId"), str(identifier))
580
+ abstract_ref = OxmlElement("w:abstractNumId")
581
+ abstract_ref.set(qn("w:val"), str(self.abstracts[key]))
582
+ num.append(abstract_ref)
583
+ override = OxmlElement("w:lvlOverride")
584
+ override.set(qn("w:ilvl"), str(level))
585
+ restart = OxmlElement("w:startOverride")
586
+ restart.set(qn("w:val"), str(start))
587
+ override.append(restart)
588
+ num.append(override)
589
+ self.root.append(num)
590
+ return identifier
591
+
592
+ @staticmethod
593
+ def apply(paragraph: Any, number: int, level: int) -> None:
594
+ from docx.oxml import OxmlElement
595
+ from docx.oxml.ns import qn
596
+
597
+ properties = OxmlElement("w:numPr")
598
+ for tag, value in (("ilvl", level), ("numId", number)):
599
+ child = OxmlElement("w:" + tag)
600
+ child.set(qn("w:val"), str(value))
601
+ properties.append(child)
602
+ paragraph._p.get_or_add_pPr().append(properties)
603
+
604
+
605
+ def _append_footnote_reference(paragraph: Any, number: str, style_id: str) -> None:
606
+ from docx.oxml import OxmlElement
607
+ from docx.oxml.ns import qn
608
+
609
+ run = OxmlElement("w:r")
610
+ properties = OxmlElement("w:rPr")
611
+ style = OxmlElement("w:rStyle")
612
+ style.set(qn("w:val"), style_id)
613
+ properties.append(style)
614
+ run.append(properties)
615
+ reference = OxmlElement("w:footnoteReference")
616
+ reference.set(qn("w:id"), number)
617
+ run.append(reference)
618
+ paragraph._p.append(run)
619
+
620
+
621
+ def _build_footnotes_xml(definitions: list[Any]) -> bytes:
622
+ from docx.oxml import OxmlElement
623
+ from docx.oxml.ns import qn
624
+ from lxml import etree
625
+
626
+ root = OxmlElement("w:footnotes")
627
+ for identifier, kind, marker in (
628
+ ("-1", "separator", "w:separator"),
629
+ ("0", "continuationSeparator", "w:continuationSeparator"),
630
+ ):
631
+ note = OxmlElement("w:footnote")
632
+ note.set(qn("w:type"), kind)
633
+ note.set(qn("w:id"), identifier)
634
+ paragraph = OxmlElement("w:p")
635
+ run = OxmlElement("w:r")
636
+ run.append(OxmlElement(marker))
637
+ paragraph.append(run)
638
+ note.append(paragraph)
639
+ root.append(note)
640
+ for definition in definitions:
641
+ root.append(definition)
642
+ return etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone=True)
643
+
644
+
645
+ def _attach_footnotes(docx_bytes: bytes, footnotes_xml: bytes) -> bytes:
646
+ """Inclui a parte de notas de rodapé e seu relacionamento no pacote DOCX."""
647
+ from lxml import etree
648
+
649
+ relationship_ns = "http://schemas.openxmlformats.org/package/2006/relationships"
650
+ content_type_ns = "http://schemas.openxmlformats.org/package/2006/content-types"
651
+ office_relationship = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes"
652
+ footnote_content_type = "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"
653
+ with zipfile.ZipFile(io.BytesIO(docx_bytes), "r") as source:
654
+ entries = {name: source.read(name) for name in source.namelist()}
655
+
656
+ relationships_path = "word/_rels/document.xml.rels"
657
+ relationships = etree.fromstring(entries[relationships_path])
658
+ existing = relationships.xpath("./*[local-name()='Relationship' and @Type=$kind]", kind=office_relationship)
659
+ if existing:
660
+ existing[0].set("Target", "footnotes.xml")
661
+ else:
662
+ numeric_ids = [
663
+ int(match.group(1))
664
+ for element in relationships
665
+ if (match := re.fullmatch(r"rId(\d+)", str(element.get("Id", ""))))
666
+ ]
667
+ relationship = etree.SubElement(
668
+ relationships,
669
+ f"{{{relationship_ns}}}Relationship",
670
+ )
671
+ relationship.set("Id", f"rId{max(numeric_ids, default=0) + 1}")
672
+ relationship.set("Type", office_relationship)
673
+ relationship.set("Target", "footnotes.xml")
674
+ entries[relationships_path] = etree.tostring(
675
+ relationships, xml_declaration=True, encoding="UTF-8", standalone=True
676
+ )
677
+
678
+ content_types_path = "[Content_Types].xml"
679
+ content_types = etree.fromstring(entries[content_types_path])
680
+ override = content_types.xpath(
681
+ "./*[local-name()='Override' and @PartName='/word/footnotes.xml']"
682
+ )
683
+ if not override:
684
+ override = [
685
+ etree.SubElement(content_types, f"{{{content_type_ns}}}Override")
686
+ ]
687
+ override[0].set("PartName", "/word/footnotes.xml")
688
+ override[0].set("ContentType", footnote_content_type)
689
+ entries[content_types_path] = etree.tostring(
690
+ content_types, xml_declaration=True, encoding="UTF-8", standalone=True
691
+ )
692
+ entries["word/footnotes.xml"] = footnotes_xml
693
+
694
+ output = io.BytesIO()
695
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as target:
696
+ for name, data in entries.items():
697
+ target.writestr(name, data)
698
+ return output.getvalue()
699
+
700
+
701
+ def _prune_unreferenced_footnotes(docx_bytes: bytes) -> bytes:
702
+ """Remove definições de nota que não têm chamada no corpo do documento."""
703
+ from docx.oxml.ns import qn
704
+ from lxml import etree
705
+
706
+ namespaces = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
707
+ with zipfile.ZipFile(io.BytesIO(docx_bytes), "r") as source:
708
+ names = set(source.namelist())
709
+ if "word/document.xml" not in names or "word/footnotes.xml" not in names:
710
+ return docx_bytes
711
+ document_xml = etree.fromstring(source.read("word/document.xml"))
712
+ footnotes_xml = etree.fromstring(source.read("word/footnotes.xml"))
713
+ referenced = {
714
+ reference.get(qn("w:id"))
715
+ for reference in document_xml.xpath(
716
+ ".//w:footnoteReference", namespaces=namespaces
717
+ )
718
+ }
719
+ definitions = footnotes_xml.findall(f"./{qn('w:footnote')}")
720
+ available = {
721
+ note.get(qn("w:id"))
722
+ for note in definitions
723
+ if note.get(qn("w:type")) is None and note.get(qn("w:id")) not in {"-1", "0"}
724
+ }
725
+ missing = sorted(identifier for identifier in referenced if identifier not in available)
726
+ if missing:
727
+ raise InputValidationError(
728
+ "chamadas de notas sem definição no DOCX: " + ", ".join(missing)
729
+ )
730
+ retained = [
731
+ note for note in definitions
732
+ if note.get(qn("w:type")) is not None
733
+ or note.get(qn("w:id")) in {"-1", "0"}
734
+ or note.get(qn("w:id")) in referenced
735
+ ]
736
+ if len(retained) == len(definitions):
737
+ return docx_bytes
738
+ for note in definitions:
739
+ footnotes_xml.remove(note)
740
+ for note in retained:
741
+ footnotes_xml.append(note)
742
+ notes_payload = etree.tostring(
743
+ footnotes_xml, xml_declaration=True, encoding="UTF-8", standalone=True
744
+ )
745
+ entries = {name: source.read(name) for name in names}
746
+
747
+ output = io.BytesIO()
748
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as target:
749
+ for name, payload in entries.items():
750
+ target.writestr(name, notes_payload if name == "word/footnotes.xml" else payload)
751
+ return output.getvalue()
752
+
753
+
754
+ def _report_table_layouts(layout: Any) -> list[tuple[tuple[str, ...], tuple[Any, ...], dict[str, Any]]]:
755
+ from decimal import Decimal, InvalidOperation
756
+
757
+ if layout is None:
758
+ return []
759
+ if not isinstance(layout, Mapping) or set(layout) - {"tabelas", "paragrafos", "padrao_tabelas"}:
760
+ raise InputValidationError("layout_documento aceita somente os mapeamentos tabelas, paragrafos e padrao_tabelas")
761
+ tables = layout.get("tabelas", [])
762
+ if not isinstance(tables, list):
763
+ raise InputValidationError("layout_documento.tabelas deve ser uma lista")
764
+ profiles = []
765
+ seen = set()
766
+ for item in tables:
767
+ required = {"cabecalhos"}
768
+ optional = {
769
+ "larguras_percentuais",
770
+ "larguras_grade_twips",
771
+ "largura_total_twips",
772
+ "recuo_esquerdo_twips",
773
+ "ajuste_automatico",
774
+ "largura_automatica",
775
+ "alinhamento",
776
+ "alinhar_legenda_fonte",
777
+ "impedir_quebra_linhas",
778
+ "obrigatorio",
779
+ "tbl_look",
780
+ }
781
+ if not isinstance(item, Mapping) or not required <= set(item) or set(item) - required - optional:
782
+ raise InputValidationError("layout de tabela exige cabecalhos e opções válidas")
783
+ options = {key: item[key] for key in optional if key in item}
784
+ automatic = options.get("ajuste_automatico", False)
785
+ if not isinstance(automatic, bool):
786
+ raise InputValidationError("ajuste_automatico deve ser booleano")
787
+ automatic_width = options.get("largura_automatica", "area_texto")
788
+ if not isinstance(automatic_width, str) or automatic_width not in {"area_texto", "conteudo"}:
789
+ raise InputValidationError("largura_automatica deve ser area_texto ou conteudo")
790
+ if "largura_automatica" in options and not automatic:
791
+ raise InputValidationError("largura_automatica requer ajuste_automatico: true")
792
+ if automatic and "largura_total_twips" in options:
793
+ raise InputValidationError("largura_total_twips não pode ser combinado com ajuste_automatico")
794
+ for name in ("largura_total_twips", "recuo_esquerdo_twips"):
795
+ if name in options and (isinstance(options[name], bool) or not isinstance(options[name], int)
796
+ or options[name] < (1 if name == "largura_total_twips" else 0)):
797
+ raise InputValidationError(f"{name} deve ser inteiro válido em twips")
798
+ if options.get("alinhamento", "centro") not in {"esquerda", "centro", "direita"}:
799
+ raise InputValidationError("alinhamento de tabela inválido")
800
+ if "alinhar_legenda_fonte" in options and not isinstance(options["alinhar_legenda_fonte"], bool):
801
+ raise InputValidationError("alinhar_legenda_fonte deve ser booleano")
802
+ if "impedir_quebra_linhas" in options and not isinstance(options["impedir_quebra_linhas"], bool):
803
+ raise InputValidationError("impedir_quebra_linhas deve ser booleano")
804
+ if "obrigatorio" in options and not isinstance(options["obrigatorio"], bool):
805
+ raise InputValidationError("obrigatorio deve ser booleano")
806
+ if "tbl_look" in options:
807
+ options["tbl_look"] = _validated_table_look(options["tbl_look"])
808
+ names = item["cabecalhos"]
809
+ if not isinstance(names, list) or not names or not all(isinstance(name, str) and name.strip() for name in names):
810
+ raise InputValidationError("cabecalhos deve ser uma lista de textos não vazios")
811
+ values = item.get("larguras_percentuais")
812
+ grid_values = options.get("larguras_grade_twips")
813
+ if values is None and (not automatic or grid_values is None):
814
+ raise InputValidationError("larguras_percentuais é obrigatória, exceto quando ajuste_automatico usa larguras_grade_twips")
815
+ widths: tuple[Decimal, ...] = ()
816
+ if values is not None:
817
+ if not isinstance(values, list) or len(values) != len(names):
818
+ raise InputValidationError("larguras_percentuais deve corresponder à lista de cabecalhos")
819
+ try:
820
+ if any(isinstance(value, bool) for value in values):
821
+ raise ValueError("booleano")
822
+ widths = tuple(Decimal(str(value)) for value in values)
823
+ if any(not value.is_finite() or value <= 0 for value in widths) or sum(widths) != 100:
824
+ raise ValueError("soma")
825
+ except (InvalidOperation, ValueError) as exc:
826
+ raise InputValidationError("larguras_percentuais deve conter números positivos com soma 100") from exc
827
+ if grid_values is not None:
828
+ if (not automatic or not isinstance(grid_values, list) or len(grid_values) != len(names)
829
+ or any(isinstance(value, bool) or not isinstance(value, int) or value <= 0 for value in grid_values)):
830
+ raise InputValidationError("larguras_grade_twips exige ajuste_automatico e um inteiro positivo por cabeçalho")
831
+ key = tuple(" ".join(name.split()) for name in names)
832
+ if key in seen:
833
+ raise InputValidationError("layout de tabela duplicado para os mesmos cabeçalhos")
834
+ seen.add(key)
835
+ profiles.append((key, widths, options))
836
+ return profiles
837
+
838
+
839
+ def _validated_table_look(value: Any) -> dict[str, bool]:
840
+ allowed = {"firstRow", "lastRow", "firstColumn", "lastColumn", "noHBand", "noVBand"}
841
+ if not isinstance(value, Mapping) or set(value) - allowed:
842
+ raise InputValidationError("tbl_look deve mapear somente opções OOXML de tabela conhecidas")
843
+ if any(not isinstance(flag, bool) for flag in value.values()):
844
+ raise InputValidationError("tbl_look aceita somente valores booleanos")
845
+ return dict(value)
846
+
847
+
848
+ def _report_default_table_look(layout: Any) -> dict[str, bool]:
849
+ if layout is None:
850
+ return {}
851
+ if not isinstance(layout, Mapping) or set(layout) - {"tabelas", "paragrafos", "padrao_tabelas"}:
852
+ raise InputValidationError("layout_documento aceita somente os mapeamentos tabelas, paragrafos e padrao_tabelas")
853
+ defaults = layout.get("padrao_tabelas", {})
854
+ if not isinstance(defaults, Mapping) or set(defaults) - {"tbl_look"}:
855
+ raise InputValidationError("padrao_tabelas aceita somente tbl_look")
856
+ return _validated_table_look(defaults.get("tbl_look", {})) if "tbl_look" in defaults else {}
857
+
858
+
859
+ def _table_header_pattern_matches(pattern: tuple[str, ...], headers: tuple[str, ...]) -> bool:
860
+ """Match complete normalized header cells; only ``*`` is a wildcard."""
861
+ import re
862
+
863
+ if len(pattern) != len(headers):
864
+ return False
865
+ for expected, actual in zip(pattern, headers, strict=True):
866
+ if "*" not in expected:
867
+ if expected != actual:
868
+ return False
869
+ continue
870
+ expression = "^" + ".*".join(re.escape(part) for part in expected.split("*")) + "$"
871
+ if re.fullmatch(expression, actual) is None:
872
+ return False
873
+ return True
874
+
875
+
876
+ def _markdown_list_tightness(tokens: list[Any], markdown: str) -> dict[int, bool]:
877
+ """Calcula quais listas devem usar parágrafos compactos no DOCX.
878
+
879
+ O ``hidden`` do markdown-it diverge do Pandoc em listas com sublistas: uma
880
+ quebra em branco depois de uma sublista não torna a lista externa folgada,
881
+ mas uma quebra depois de um item que termina em parágrafo torna. Os mapas
882
+ de linha dos tokens permitem reproduzir essa distinção sem depender do
883
+ executável Pandoc em tempo de execução.
884
+ """
885
+ list_open_types = {"bullet_list_open", "ordered_list_open"}
886
+ list_close_types = {"bullet_list_close", "ordered_list_close"}
887
+ block_open_types = list_open_types | {
888
+ "blockquote_open",
889
+ "heading_open",
890
+ "paragraph_open",
891
+ "table_open",
892
+ }
893
+ lines = markdown.splitlines()
894
+ list_ends: dict[int, int] = {}
895
+ item_ends: dict[int, int] = {}
896
+ list_stack: list[tuple[str, int]] = []
897
+ item_stack: list[int] = []
898
+
899
+ for index, token in enumerate(tokens):
900
+ if token.type in list_open_types:
901
+ list_stack.append((token.type.removesuffix("_open"), index))
902
+ elif token.type in list_close_types:
903
+ expected = token.type.removesuffix("_close")
904
+ if list_stack and list_stack[-1][0] == expected:
905
+ _, start = list_stack.pop()
906
+ list_ends[start] = index
907
+ elif token.type == "list_item_open":
908
+ item_stack.append(index)
909
+ elif token.type == "list_item_close" and item_stack:
910
+ item_ends[item_stack.pop()] = index
911
+
912
+ def has_blank_line(start: int, end: int) -> bool:
913
+ return any(not lines[line].strip() for line in range(max(0, start), min(end, len(lines))))
914
+
915
+ tightness: dict[int, bool] = {}
916
+ for list_start, list_end in list_ends.items():
917
+ list_token = tokens[list_start]
918
+ direct_items = [
919
+ item_start
920
+ for item_start in item_ends
921
+ if list_start < item_start < list_end
922
+ and tokens[item_start].level == list_token.level + 1
923
+ ]
924
+ direct_items.sort()
925
+ is_tight = True
926
+ for item_position, item_start in enumerate(direct_items):
927
+ item_token = tokens[item_start]
928
+ item_end = item_ends[item_start]
929
+ blocks = [
930
+ (index, tokens[index])
931
+ for index in range(item_start + 1, item_end)
932
+ if tokens[index].level == item_token.level + 1
933
+ and tokens[index].type in block_open_types
934
+ and tokens[index].map
935
+ ]
936
+ for (_, previous), (_, following) in zip(blocks, blocks[1:]):
937
+ if has_blank_line(previous.map[1], following.map[0]):
938
+ is_tight = False
939
+ break
940
+ if not is_tight:
941
+ break
942
+ if (
943
+ item_position + 1 < len(direct_items)
944
+ and blocks
945
+ and blocks[-1][1].type not in list_open_types
946
+ ):
947
+ next_item_start = direct_items[item_position + 1]
948
+ if has_blank_line(blocks[-1][1].map[1], tokens[next_item_start].map[0]):
949
+ is_tight = False
950
+ break
951
+ tightness[list_start] = is_tight
952
+ return tightness
953
+
954
+
955
+ def _report_paragraph_layouts(layout: Any) -> list[tuple[str, float]]:
956
+ if layout is None:
957
+ return []
958
+ if not isinstance(layout, Mapping) or set(layout) - {"tabelas", "paragrafos", "padrao_tabelas"}:
959
+ raise InputValidationError("layout_documento aceita somente os mapeamentos tabelas, paragrafos e padrao_tabelas")
960
+ paragraphs = layout.get("paragrafos", [])
961
+ if not isinstance(paragraphs, list):
962
+ raise InputValidationError("layout_documento.paragrafos deve ser uma lista")
963
+ profiles: list[tuple[str, float]] = []
964
+ seen: set[str] = set()
965
+ for item in paragraphs:
966
+ if not isinstance(item, Mapping) or set(item) != {"prefixo", "tamanho_fonte_pt"}:
967
+ raise InputValidationError("cada perfil de parágrafo exige prefixo e tamanho_fonte_pt")
968
+ prefix = item["prefixo"]
969
+ if not isinstance(prefix, str) or not prefix.strip():
970
+ raise InputValidationError("layout_documento.paragrafos.prefixo deve ser texto não vazio")
971
+ normalized_prefix = " ".join(prefix.split())
972
+ size = item["tamanho_fonte_pt"]
973
+ if isinstance(size, bool) or not isinstance(size, (int, float)) or not isfinite(size) or size <= 0:
974
+ raise InputValidationError("layout_documento.paragrafos.tamanho_fonte_pt deve ser número finito positivo")
975
+ if normalized_prefix in seen:
976
+ raise InputValidationError("layout de parágrafo duplicado para o mesmo prefixo")
977
+ seen.add(normalized_prefix)
978
+ profiles.append((normalized_prefix, float(size)))
979
+ return profiles
980
+
981
+
982
+ def validate_report_layout(layout: Any) -> None:
983
+ """Valida a declaração de layout antes de iniciar a renderização."""
984
+ _report_table_layouts(layout)
985
+ _report_paragraph_layouts(layout)
986
+
987
+
988
+ def apply_report_layout(document: Any, layout: Any) -> None:
989
+ """Aplica perfis de tabela e parágrafo ao DOCX já composto."""
990
+ table_layouts = _report_table_layouts(layout)
991
+ paragraph_layouts = _report_paragraph_layouts(layout)
992
+ _apply_report_table_layouts(document, table_layouts, _report_default_table_look(layout))
993
+ _apply_report_paragraph_layouts(document, paragraph_layouts)
994
+
995
+
996
+ def _apply_report_paragraph_layouts(document: Any, profiles: list[tuple[str, float]]) -> None:
997
+ if not profiles:
998
+ return
999
+ from docx.oxml import OxmlElement
1000
+ from docx.oxml.ns import qn
1001
+ from docx.shared import Pt
1002
+
1003
+ paragraphs = list(document.paragraphs)
1004
+
1005
+ def collect_table_paragraphs(table: Any) -> None:
1006
+ for row in table.rows:
1007
+ for cell in row.cells:
1008
+ paragraphs.extend(cell.paragraphs)
1009
+ for nested in cell.tables:
1010
+ collect_table_paragraphs(nested)
1011
+
1012
+ for table in document.tables:
1013
+ collect_table_paragraphs(table)
1014
+ for paragraph in paragraphs:
1015
+ text = " ".join(paragraph.text.split())
1016
+ profile = next(((prefix, size) for prefix, size in profiles if text.startswith(prefix)), None)
1017
+ if profile is None:
1018
+ continue
1019
+ _, size = profile
1020
+ for run in paragraph.runs:
1021
+ if run.text:
1022
+ run.font.size = Pt(size)
1023
+ properties = paragraph._p.get_or_add_pPr()
1024
+ run_properties = properties.find(qn("w:rPr"))
1025
+ if run_properties is None:
1026
+ run_properties = OxmlElement("w:rPr")
1027
+ properties.append(run_properties)
1028
+ for name in ("w:sz", "w:szCs"):
1029
+ element = run_properties.find(qn(name))
1030
+ if element is None:
1031
+ element = OxmlElement(name)
1032
+ run_properties.append(element)
1033
+ element.set(qn("w:val"), str(round(size * 2)))
1034
+
1035
+
1036
+ def _apply_report_table_layouts(
1037
+ document: Any,
1038
+ profiles: list[Any],
1039
+ default_look: Mapping[str, bool] | None = None,
1040
+ ) -> None:
1041
+ from fractions import Fraction
1042
+ from docx.oxml import OxmlElement
1043
+ from docx.oxml.ns import qn
1044
+ from docx.shared import Twips
1045
+ from docx.enum.table import WD_TABLE_ALIGNMENT
1046
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
1047
+ from docx.text.paragraph import Paragraph
1048
+
1049
+ default_look = dict(default_look or {})
1050
+ if default_look:
1051
+ for table in document.tables:
1052
+ _apply_report_table_look(table, default_look)
1053
+
1054
+ for names, _, options in profiles:
1055
+ if not options.get("obrigatorio"):
1056
+ continue
1057
+ matches = [
1058
+ table for table in document.tables
1059
+ if table.rows and _table_header_pattern_matches(
1060
+ names,
1061
+ tuple(" ".join(cell.text.split()) for cell in table.rows[0].cells),
1062
+ )
1063
+ ]
1064
+ if len(matches) != 1:
1065
+ raise InputValidationError(
1066
+ "layout de tabela obrigatório requer exatamente uma tabela correspondente ao padrão "
1067
+ f"de cabeçalho {list(names)!r} (encontrado: {len(matches)})"
1068
+ )
1069
+
1070
+ for table in document.tables:
1071
+ if not table.rows:
1072
+ continue
1073
+ headers = tuple(" ".join(cell.text.split()) for cell in table.rows[0].cells)
1074
+ matching_profiles = [
1075
+ (widths, options, names)
1076
+ for names, widths, options in profiles
1077
+ if _table_header_pattern_matches(names, headers)
1078
+ ]
1079
+ if len(matching_profiles) > 1:
1080
+ patterns = [list(names) for _, _, names in matching_profiles]
1081
+ raise InputValidationError(
1082
+ f"mais de um perfil de layout corresponde aos cabeçalhos {list(headers)!r}: {patterns!r}"
1083
+ )
1084
+ if not matching_profiles:
1085
+ continue
1086
+ percentages, options, _ = matching_profiles[0]
1087
+ section = document.sections[0]
1088
+ available = int((section.page_width - section.left_margin - section.right_margin) / 635)
1089
+ indent = options.get("recuo_esquerdo_twips", 0)
1090
+ automatic = options.get("ajuste_automatico", False)
1091
+ explicit_width = "largura_total_twips" in options
1092
+ total = options.get("largura_total_twips", available - indent)
1093
+ if (automatic and not 0 <= indent < available) or (not automatic and (total <= 0 or indent + total > available)):
1094
+ raise InputValidationError("largura/recuo da tabela excedem a área útil")
1095
+ grid_widths = options.get("larguras_grade_twips")
1096
+ if grid_widths is not None:
1097
+ widths = list(grid_widths)
1098
+ else:
1099
+ ideals = [Fraction(value) * total / 100 for value in percentages]
1100
+ widths = [value.numerator // value.denominator for value in ideals]
1101
+ # Equal fractional remainders are awarded from the right, matching
1102
+ # the reference DOCX width distribution for otherwise equal columns.
1103
+ order = sorted(range(len(widths)), key=lambda i: (-(ideals[i] - widths[i]), -i))
1104
+ for i in order[:total - sum(widths)]:
1105
+ widths[i] += 1
1106
+ if any(value <= 0 for value in widths):
1107
+ raise InputValidationError("largura de coluna resulta em zero twip")
1108
+ table.autofit = automatic
1109
+ alignment = options.get("alinhamento", "esquerda" if indent else "centro")
1110
+ table.alignment = {"esquerda": WD_TABLE_ALIGNMENT.LEFT, "centro": WD_TABLE_ALIGNMENT.CENTER,
1111
+ "direita": WD_TABLE_ALIGNMENT.RIGHT}[alignment]
1112
+ indentation = table._tbl.tblPr.find(qn("w:tblInd"))
1113
+ if indent:
1114
+ if indentation is None:
1115
+ indentation = OxmlElement("w:tblInd")
1116
+ table._tbl.tblPr.append(indentation)
1117
+ indentation.set(qn("w:w"), str(indent))
1118
+ indentation.set(qn("w:type"), "dxa")
1119
+ elif indentation is not None:
1120
+ table._tbl.tblPr.remove(indentation)
1121
+ table_width = table._tbl.tblPr.find(qn("w:tblW"))
1122
+ if automatic and options.get("largura_automatica", "area_texto") == "conteudo":
1123
+ table_width.set(qn("w:type"), "auto")
1124
+ table_width.set(qn("w:w"), "0")
1125
+ elif automatic or (not explicit_width and indent == 0):
1126
+ # Keep an unqualified full-width table responsive when its DOCX
1127
+ # body is composed into a publication model with different
1128
+ # margins. Fixed twip widths retain the narrower source area.
1129
+ table_width.set(qn("w:type"), "pct")
1130
+ table_width.set(qn("w:w"), "5000")
1131
+ else:
1132
+ table_width.set(qn("w:type"), "dxa")
1133
+ table_width.set(qn("w:w"), str(total))
1134
+ for column, width in zip(table.columns, widths, strict=True):
1135
+ column.width = Twips(width)
1136
+ if automatic:
1137
+ for cell_width in table._tbl.xpath(".//w:tcPr/w:tcW"):
1138
+ cell_width.getparent().remove(cell_width)
1139
+ else:
1140
+ for row in table.rows:
1141
+ offset = 0
1142
+ for cell in row._tr.tc_lst:
1143
+ properties = cell.get_or_add_tcPr()
1144
+ span = properties.find(qn("w:gridSpan"))
1145
+ count = int(span.get(qn("w:val"))) if span is not None else 1
1146
+ element = properties.find(qn("w:tcW"))
1147
+ if element is None:
1148
+ element = OxmlElement("w:tcW")
1149
+ properties.append(element)
1150
+ element.set(qn("w:type"), "dxa")
1151
+ element.set(qn("w:w"), str(sum(widths[offset:offset + count])))
1152
+ offset += count
1153
+ if "impedir_quebra_linhas" in options:
1154
+ for row in table.rows:
1155
+ row_properties = row._tr.get_or_add_trPr()
1156
+ markers = row_properties.xpath("w:cantSplit")
1157
+ if options["impedir_quebra_linhas"]:
1158
+ if not markers:
1159
+ row_properties.append(OxmlElement("w:cantSplit"))
1160
+ else:
1161
+ for marker in markers:
1162
+ row_properties.remove(marker)
1163
+ if "tbl_look" in options:
1164
+ _apply_report_table_look(table, default_look | options["tbl_look"])
1165
+ if options.get("alinhar_legenda_fonte"):
1166
+ for element in (table._tbl.getprevious(), table._tbl.getnext()):
1167
+ if element is None or element.tag != qn("w:p"):
1168
+ continue
1169
+ paragraph = Paragraph(element, document._body)
1170
+ name = _normalize_style_name(str(paragraph.style.name or ""))
1171
+ if "caption" in name or "fonteimagem" in name or paragraph.text.startswith(("Tabela ", "(Fonte:")):
1172
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
1173
+ paragraph.paragraph_format.left_indent = Twips(indent)
1174
+ paragraph.paragraph_format.right_indent = Twips(0)
1175
+
1176
+
1177
+ def _apply_report_table_style(document: Any, table: Any) -> None:
1178
+ from docx.enum.style import WD_STYLE_TYPE
1179
+
1180
+ for name in ("Table", "Table Grid"):
1181
+ style = _find_style(document, name)
1182
+ if style is not None and style.type == WD_STYLE_TYPE.TABLE:
1183
+ table.style = style
1184
+ break
1185
+
1186
+ # Preserve the Pandoc/reference table look by default. Specific profiles
1187
+ # may override these flags after layout selection.
1188
+ _apply_report_table_look(table, {
1189
+ "firstRow": True,
1190
+ "lastRow": False,
1191
+ "firstColumn": False,
1192
+ "lastColumn": False,
1193
+ "noHBand": False,
1194
+ "noVBand": False,
1195
+ })
1196
+
1197
+
1198
+ def _apply_report_table_look(table: Any, overrides: Mapping[str, bool]) -> None:
1199
+ from docx.oxml import OxmlElement
1200
+ from docx.oxml.ns import qn
1201
+
1202
+ properties = table._tbl.tblPr
1203
+ look = properties.find(qn("w:tblLook"))
1204
+ if look is None:
1205
+ look = OxmlElement("w:tblLook")
1206
+ properties.append(look)
1207
+ defaults = {
1208
+ "firstRow": True,
1209
+ "lastRow": False,
1210
+ "firstColumn": False,
1211
+ "lastColumn": False,
1212
+ "noHBand": False,
1213
+ "noVBand": False,
1214
+ }
1215
+ bits = {"firstRow": 0x20, "lastRow": 0x40, "firstColumn": 0x80,
1216
+ "lastColumn": 0x100, "noHBand": 0x200, "noVBand": 0x400}
1217
+ values = {
1218
+ name: look.get(qn(f"w:{name}"), "1" if default else "0") == "1"
1219
+ for name, default in defaults.items()
1220
+ }
1221
+ values.update(overrides)
1222
+ for name, value in values.items():
1223
+ look.set(qn(f"w:{name}"), "1" if value else "0")
1224
+ value = sum(bit for name, bit in bits.items() if values[name])
1225
+ look.set(qn("w:val"), f"{value:04X}")
1226
+
1227
+
1228
+ def _optimize_document_pagination(document: Any) -> None:
1229
+ """Aplica agrupamento básico de títulos, figuras, fontes e linhas de tabela."""
1230
+ from docx.enum.table import WD_TABLE_ALIGNMENT
1231
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
1232
+ from docx.oxml import OxmlElement
1233
+ from docx.oxml.ns import qn
1234
+ from docx.shared import Cm, Pt
1235
+ from docx.text.paragraph import Paragraph
1236
+
1237
+ # A standalone note immediately after a figure belongs to its caption,
1238
+ # rather than a separate line that can drift to another page.
1239
+ for paragraph in list(document.paragraphs):
1240
+ if paragraph.text.strip() or not paragraph._p.xpath(".//w:footnoteReference"):
1241
+ continue
1242
+ previous = paragraph._p.getprevious()
1243
+ if previous is not None and previous.xpath(".//w:drawing"):
1244
+ previous = previous.getprevious()
1245
+ if previous is None or previous.tag != qn("w:p"):
1246
+ continue
1247
+ caption = Paragraph(previous, document._body)
1248
+ if not caption.text.strip().startswith("Figura "):
1249
+ continue
1250
+ for child in list(paragraph._p):
1251
+ if child.tag != qn("w:pPr"):
1252
+ caption._p.append(child)
1253
+ paragraph._p.getparent().remove(paragraph._p)
1254
+
1255
+ for paragraph in list(document.paragraphs):
1256
+ style_name = str(paragraph.style.name or "")
1257
+ normalized_style = _normalize_style_name(style_name)
1258
+ is_heading = (
1259
+ normalized_style.startswith(("heading", "titulo", "title", "subtitle", "subtitulo"))
1260
+ or bool(paragraph._element.xpath("./w:pPr/w:outlineLvl"))
1261
+ )
1262
+ if is_heading:
1263
+ paragraph.paragraph_format.keep_with_next = True
1264
+ else:
1265
+ paragraph.paragraph_format.widow_control = True
1266
+
1267
+ paragraphs = list(document.paragraphs)
1268
+ for index, paragraph in enumerate(paragraphs):
1269
+ if not paragraph._element.xpath(".//w:drawing | .//w:graphic"):
1270
+ continue
1271
+ previous = paragraphs[index - 1] if index else None
1272
+ following = paragraphs[index + 1] if index + 1 < len(paragraphs) else None
1273
+ previous_style = _normalize_style_name(str(previous.style.name or "")) if previous else ""
1274
+ following_style = _normalize_style_name(str(following.style.name or "")) if following else ""
1275
+ previous_text = previous.text.strip() if previous else ""
1276
+ following_text = following.text.strip() if following else ""
1277
+ if previous and (
1278
+ "caption" in previous_style
1279
+ or "legenda" in previous_style
1280
+ or previous_text.startswith("Figura ")
1281
+ ):
1282
+ previous.paragraph_format.keep_with_next = True
1283
+ if following and (
1284
+ "fonteimagem" in following_style or following_text.startswith("(Fonte:")
1285
+ ):
1286
+ paragraph.paragraph_format.keep_with_next = True
1287
+ following.paragraph_format.keep_with_next = False
1288
+ elif following_text.startswith("Figura "):
1289
+ # Figure captions placed below must remain attached to the image.
1290
+ paragraph.paragraph_format.keep_with_next = True
1291
+ if index + 2 < len(paragraphs):
1292
+ source = paragraphs[index + 2]
1293
+ if "fonteimagem" in _normalize_style_name(str(source.style.name or "")) or source.text.strip().startswith("(Fonte:"):
1294
+ following.paragraph_format.keep_with_next = True
1295
+
1296
+ max_height = Cm(21)
1297
+ for extent in paragraph._element.xpath(".//wp:extent"):
1298
+ height = int(extent.get("cy", 0))
1299
+ if height > max_height:
1300
+ width = int(extent.get("cx", 0))
1301
+ ratio = max_height / height
1302
+ extent.set("cy", str(int(max_height)))
1303
+ extent.set("cx", str(int(width * ratio)))
1304
+
1305
+ for table in document.tables:
1306
+ table.alignment = WD_TABLE_ALIGNMENT.CENTER
1307
+ table.autofit = True
1308
+ _apply_report_table_style(document, table)
1309
+ if not table.rows:
1310
+ continue
1311
+ for row_index, row in enumerate(table.rows):
1312
+ row_properties = row._tr.get_or_add_trPr()
1313
+ if row_index == 0 and not row_properties.xpath("w:tblHeader"):
1314
+ header = OxmlElement("w:tblHeader")
1315
+ header.set(qn("w:val"), "true")
1316
+ row_properties.append(header)
1317
+ total_chars = sum(len(cell.text.strip()) for cell in row.cells)
1318
+ total_paragraphs = sum(len(cell.paragraphs) for cell in row.cells)
1319
+ can_split = row_index > 0 and (total_chars > 250 or total_paragraphs > 3)
1320
+ if can_split:
1321
+ for marker in row_properties.xpath("w:cantSplit"):
1322
+ row_properties.remove(marker)
1323
+ elif not row_properties.xpath("w:cantSplit"):
1324
+ row_properties.append(OxmlElement("w:cantSplit"))
1325
+ font_size = Pt(10 if row_index == 0 else 9)
1326
+ for cell in row.cells:
1327
+ for paragraph in cell.paragraphs:
1328
+ paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY
1329
+ for run in paragraph.runs:
1330
+ run.font.name = "Calibri"
1331
+ run.font.size = font_size
1332
+
1333
+ following = table._tbl.getnext()
1334
+ if following is not None and following.tag == qn("w:p"):
1335
+ source = Paragraph(following, table._parent)
1336
+ source_style = _normalize_style_name(str(source.style.name or ""))
1337
+ if "fonteimagem" in source_style or source.text.strip().startswith("(Fonte:"):
1338
+ source.paragraph_format.keep_with_next = False
1339
+ last_row_chars = sum(len(cell.text.strip()) for cell in table.rows[-1].cells)
1340
+ if last_row_chars <= 200:
1341
+ for cell in table.rows[-1].cells:
1342
+ for paragraph in cell.paragraphs:
1343
+ paragraph.paragraph_format.keep_with_next = True
1344
+
1345
+ # Um parágrafo que contém apenas a quebra não deve ocupar altura própria.
1346
+ for paragraph in list(document.paragraphs):
1347
+ if paragraph.text.strip() or not paragraph._element.xpath('.//w:br[@w:type="page"]'):
1348
+ continue
1349
+ following = paragraph._p.getnext()
1350
+ if following is None or following.tag != qn("w:p"):
1351
+ continue
1352
+ Paragraph(following, paragraph._parent).paragraph_format.page_break_before = True
1353
+ paragraph._p.getparent().remove(paragraph._p)
1354
+
1355
+
1356
+ def _append_hyperlink(
1357
+ paragraph: Any,
1358
+ text: str,
1359
+ href: str,
1360
+ *,
1361
+ bold: bool = False,
1362
+ italic: bool = False,
1363
+ strike: bool = False,
1364
+ underline: bool = True,
1365
+ ) -> bool:
1366
+ """Acrescenta hyperlink externo seguro; retorna false para esquemas não suportados."""
1367
+ from docx.oxml import OxmlElement
1368
+ from docx.oxml.ns import qn
1369
+ from docx.opc.constants import RELATIONSHIP_TYPE as RT
1370
+
1371
+ scheme = urlparse(href).scheme.casefold()
1372
+ if scheme not in {"http", "https", "mailto"}:
1373
+ return False
1374
+ styles = paragraph.part.styles
1375
+ try:
1376
+ styles["Hyperlink"]
1377
+ except KeyError:
1378
+ from docx.enum.style import WD_STYLE_TYPE
1379
+ from docx.shared import RGBColor
1380
+
1381
+ style = styles.add_style("Hyperlink", WD_STYLE_TYPE.CHARACTER)
1382
+ style.font.color.rgb = RGBColor(0x05, 0x63, 0xC1)
1383
+ style.font.underline = True
1384
+ relationship_id = paragraph.part.relate_to(href, RT.HYPERLINK, is_external=True)
1385
+ hyperlink = OxmlElement("w:hyperlink")
1386
+ hyperlink.set(qn("r:id"), relationship_id)
1387
+ run = OxmlElement("w:r")
1388
+ properties = OxmlElement("w:rPr")
1389
+ hyperlink_style = OxmlElement("w:rStyle")
1390
+ hyperlink_style.set(qn("w:val"), "Hyperlink")
1391
+ properties.append(hyperlink_style)
1392
+ if underline:
1393
+ underline_element = OxmlElement("w:u")
1394
+ underline_element.set(qn("w:val"), "single")
1395
+ properties.append(underline_element)
1396
+ if bold:
1397
+ properties.append(OxmlElement("w:b"))
1398
+ if italic:
1399
+ properties.append(OxmlElement("w:i"))
1400
+ if strike:
1401
+ properties.append(OxmlElement("w:strike"))
1402
+ run.append(properties)
1403
+ text_node = OxmlElement("w:t")
1404
+ text_node.text = text
1405
+ run.append(text_node)
1406
+ hyperlink.append(run)
1407
+ paragraph._p.append(hyperlink)
1408
+ return True
1409
+
1410
+
1411
+ def _render_inline(
1412
+ paragraph: Any,
1413
+ tokens: list[Any] | None,
1414
+ *,
1415
+ add_image: Callable[[Any, Any], None],
1416
+ pending: list[dict[str, str]],
1417
+ source_line: int | None,
1418
+ add_footnote_reference: Callable[[Any, str], None],
1419
+ add_figure_bookmark: Callable[[Any, str], None],
1420
+ default_bold: bool = False,
1421
+ default_italic: bool = False,
1422
+ ) -> None:
1423
+ if not tokens:
1424
+ return
1425
+ from docx.shared import Pt
1426
+
1427
+ state = {"bold": default_bold, "italic": default_italic, "strike": False, "underline": False, "link": None}
1428
+ previous_states: list[dict[str, Any]] = []
1429
+ opens = {
1430
+ "strong_open": ("bold", True),
1431
+ "em_open": ("italic", True),
1432
+ "s_open": ("strike", True),
1433
+ "link_open": ("link", "href"),
1434
+ }
1435
+ closes = {"strong_close", "em_close", "s_close", "link_close"}
1436
+
1437
+ for token in tokens:
1438
+ if token.type in opens:
1439
+ previous_states.append(dict(state))
1440
+ name, value = opens[token.type]
1441
+ state[name] = token.attrGet(value) if value == "href" else value
1442
+ continue
1443
+ if token.type in closes:
1444
+ if previous_states:
1445
+ state = previous_states.pop()
1446
+ continue
1447
+ if token.type == "image":
1448
+ add_image(paragraph, token)
1449
+ continue
1450
+ if token.type in {"softbreak", "hardbreak"}:
1451
+ if token.type == "softbreak":
1452
+ paragraph.add_run(" ")
1453
+ else:
1454
+ paragraph.add_run().add_break()
1455
+ continue
1456
+ if token.type in {"html_inline", "html_block"}:
1457
+ html_token = token.content.strip().casefold()
1458
+ figure_bookmark = _FIGURE_BOOKMARK_COMMENT.fullmatch(token.content.strip())
1459
+ if figure_bookmark:
1460
+ add_figure_bookmark(paragraph, figure_bookmark.group(1))
1461
+ continue
1462
+ if html_token == "<u>":
1463
+ previous_states.append(dict(state))
1464
+ state["underline"] = True
1465
+ continue
1466
+ if html_token == "</u>":
1467
+ if previous_states:
1468
+ state = previous_states.pop()
1469
+ continue
1470
+ if html_token in {"<br>", "<br/>", "<br />"}:
1471
+ paragraph.add_run().add_break()
1472
+ continue
1473
+ pending.append(
1474
+ {
1475
+ "type": "unsupported_markdown",
1476
+ "feature": "html_inline",
1477
+ "line": str(source_line or ""),
1478
+ }
1479
+ )
1480
+ paragraph.add_run("[HTML não renderizado]")
1481
+ continue
1482
+
1483
+ text = token.content
1484
+ if token.type == "text":
1485
+ # Match the reference DOCX pipeline's nonbreaking spaces after
1486
+ # compact abbreviations, enumeration labels, and "Sr." while
1487
+ # preserving ordinary spaces elsewhere.
1488
+ text = _COMPACT_ABBREVIATION_SPACE.sub(
1489
+ lambda match: match.group("abbreviation") + ".\u00a0", text
1490
+ )
1491
+ text = _ENUMERATION_SENTENCE_SPACE.sub(
1492
+ lambda match: match.group("item") + ".\u00a0", text
1493
+ )
1494
+ text = _HONORIFIC_NAME_SPACE.sub(
1495
+ lambda match: match.group("title") + ".\u00a0", text
1496
+ )
1497
+ text = re.sub(r"[ \t]+", " ", text)
1498
+ if not text:
1499
+ continue
1500
+ href = state.get("link")
1501
+
1502
+ def add_text(value: str, *, superscript: bool = False) -> None:
1503
+ if not value:
1504
+ return
1505
+ if href and not superscript:
1506
+ if _append_hyperlink(
1507
+ paragraph,
1508
+ value,
1509
+ str(href),
1510
+ bold=bool(state["bold"]),
1511
+ italic=bool(state["italic"]),
1512
+ strike=bool(state["strike"]),
1513
+ underline=bool(state["underline"]),
1514
+ ):
1515
+ return
1516
+ pending.append(
1517
+ {
1518
+ "type": "unsupported_markdown",
1519
+ "feature": "hyperlink_scheme",
1520
+ "target": str(href),
1521
+ "line": str(source_line or ""),
1522
+ }
1523
+ )
1524
+ run = paragraph.add_run(value)
1525
+ run.bold = True if state["bold"] else None
1526
+ run.italic = True if state["italic"] else None
1527
+ run.underline = True if state["underline"] else None
1528
+ run.font.strike = True if state["strike"] else None
1529
+ run.font.superscript = True if superscript else None
1530
+ if token.type == "code_inline":
1531
+ run.font.name = "Consolas"
1532
+ run.font.size = Pt(9)
1533
+
1534
+ cursor = 0
1535
+ for marker in _FOOTNOTE_MARKER.finditer(text):
1536
+ add_text(text[cursor:marker.start()])
1537
+ add_footnote_reference(paragraph, marker.group("number"))
1538
+ cursor = marker.end()
1539
+ add_text(text[cursor:])
1540
+
1541
+
1542
+ def render_markdown_docx(
1543
+ markdown: str,
1544
+ *,
1545
+ document_label: str | None = None,
1546
+ reference: Path | None = None,
1547
+ resource_root: Path | None = None,
1548
+ resolve_path: Callable[[Path], Path] | None = None,
1549
+ resource_overrides: Mapping[str, Path] | None = None,
1550
+ resolved_resources: dict[str, Path] | None = None,
1551
+ layout: Mapping[str, Any] | None = None,
1552
+ ) -> tuple[bytes, tuple[dict[str, str], ...]]:
1553
+ """Renderiza o subconjunto declarado de Markdown/Pandoc para bytes DOCX.
1554
+
1555
+ Recursos não suportados são sinalizados como pendências materiais. As notas
1556
+ de rodapé são gravadas como partes OOXML nativas do pacote DOCX.
1557
+ """
1558
+ try:
1559
+ from docx import Document
1560
+ from docx.enum.text import WD_ALIGN_PARAGRAPH
1561
+ from docx.shared import Inches, Pt
1562
+ from docx.image.exceptions import UnrecognizedImageError
1563
+ from markdown_it import MarkdownIt
1564
+ except ImportError as exc: # pragma: no cover - dependências opcionais
1565
+ raise InputValidationError(
1566
+ "a geração Markdown/DOCX requer python-docx e markdown-it-py; instale argos-cli[reports]"
1567
+ ) from exc
1568
+
1569
+ table_layouts = _report_table_layouts(layout)
1570
+ paragraph_layouts = _report_paragraph_layouts(layout)
1571
+ if reference is not None and not reference.is_file():
1572
+ raise InputValidationError(f"modelo DOCX não encontrado: {reference}")
1573
+ document = Document(str(reference)) if reference else Document()
1574
+ prepared_markdown, metadata, image_widths, footnotes, note_numbers, preparation_pending = _prepare_markdown(markdown)
1575
+ prepared_markdown = _encode_markdown_image_destinations(prepared_markdown)
1576
+ prepared_markdown = _normalize_multiline_pipe_tables(prepared_markdown, document_label=document_label)
1577
+ pending: list[dict[str, str]] = list(preparation_pending)
1578
+ if reference is not None:
1579
+ from docx.oxml.ns import qn
1580
+
1581
+ body = document._element.body
1582
+ section_properties = [child for child in body if child.tag == qn("w:sectPr")]
1583
+ all_section_properties = body.xpath(".//w:sectPr")
1584
+ if len(all_section_properties) > 1:
1585
+ pending.append(
1586
+ {
1587
+ "type": "unsupported_reference_layout",
1588
+ "reason": "modelos DOCX com múltiplas seções não são normalizados pelo renderer",
1589
+ }
1590
+ )
1591
+ retained_section = section_properties[-1] if section_properties else None
1592
+ for child in list(body):
1593
+ if child is not retained_section:
1594
+ body.remove(child)
1595
+ footnote_reference_style = _find_style(
1596
+ document,
1597
+ "Footnote Reference",
1598
+ "FootnoteReference",
1599
+ "Referência de nota de rodapé",
1600
+ )
1601
+ footnote_text_style = _find_style(
1602
+ document,
1603
+ "Footnote Text",
1604
+ "FootnoteText",
1605
+ "Texto de nota de rodapé",
1606
+ )
1607
+ footnote_reference_style_id = (
1608
+ str(footnote_reference_style.style_id)
1609
+ if footnote_reference_style is not None
1610
+ else "FootnoteReference"
1611
+ )
1612
+ footnote_text_style_id = (
1613
+ str(footnote_text_style.style_id)
1614
+ if footnote_text_style is not None
1615
+ else "FootnoteText"
1616
+ )
1617
+
1618
+ note_occurrences: list[tuple[str, int]] = []
1619
+
1620
+ def add_footnote_reference(paragraph: Any, number: str) -> None:
1621
+ occurrence = len(note_occurrences) + 1
1622
+ note_occurrences.append((number, occurrence))
1623
+ _append_footnote_reference(paragraph, str(occurrence), footnote_reference_style_id)
1624
+
1625
+ bookmark_sequence = 0
1626
+
1627
+ def add_figure_bookmark(paragraph: Any, figure_id: str) -> None:
1628
+ nonlocal bookmark_sequence
1629
+ from docx.oxml import OxmlElement
1630
+ from docx.oxml.ns import qn
1631
+
1632
+ existing_ids = []
1633
+ for element in document._element.body.iter():
1634
+ if element.tag == qn("w:bookmarkStart"):
1635
+ try:
1636
+ existing_ids.append(int(element.get(qn("w:id"), "-1")))
1637
+ except ValueError:
1638
+ continue
1639
+ bookmark_sequence = max(bookmark_sequence, max(existing_ids, default=0) + 1)
1640
+ bookmark_name = "argos_fig_" + sha256(figure_id.encode("utf-8")).hexdigest()[:30]
1641
+ start = OxmlElement("w:bookmarkStart")
1642
+ start.set(qn("w:id"), str(bookmark_sequence))
1643
+ start.set(qn("w:name"), bookmark_name)
1644
+ properties = paragraph._p.pPr
1645
+ paragraph._p.insert(1 if properties is not None else 0, start)
1646
+ end = OxmlElement("w:bookmarkEnd")
1647
+ end.set(qn("w:id"), str(bookmark_sequence))
1648
+ paragraph._p.append(end)
1649
+ bookmark_sequence += 1
1650
+
1651
+ parser = MarkdownIt("commonmark", {
1652
+ "typographer": metadata.get("smartquotes", "true").casefold() not in {"false", "no", "0"},
1653
+ }).enable("table").enable("smartquotes")
1654
+ tokens = parser.parse(prepared_markdown)
1655
+ list_tightness = _markdown_list_tightness(tokens, prepared_markdown)
1656
+
1657
+ title = metadata.get("title", "").strip()
1658
+ subtitle = metadata.get("subtitle", "").strip()
1659
+ if title:
1660
+ title_paragraph = document.add_paragraph(title)
1661
+ if not _apply_paragraph_style(title_paragraph, document, "Title", "Título"):
1662
+ pending.append({"type": "unsupported_document_style", "style": "Title"})
1663
+ document.core_properties.title = title
1664
+ if subtitle:
1665
+ subtitle_paragraph = document.add_paragraph(subtitle)
1666
+ if not _apply_paragraph_style(subtitle_paragraph, document, "Subtitle", "Subtítulo"):
1667
+ pending.append({"type": "unsupported_document_style", "style": "Subtitle"})
1668
+
1669
+ def resolve_image(source: str) -> Path | None:
1670
+ parsed = urlparse(source)
1671
+ resource_path = unquote(parsed.path)
1672
+ for reference_key in (source, unquote(source), resource_path, Path(resource_path).as_posix()):
1673
+ staged = (resource_overrides or {}).get(reference_key)
1674
+ if staged is not None:
1675
+ return Path(staged).resolve()
1676
+ candidate = Path(source).expanduser()
1677
+ if candidate.is_absolute():
1678
+ return candidate.resolve()
1679
+ if parsed.scheme or source.startswith(("//", "data:")):
1680
+ return None
1681
+ candidate = Path(resource_path).expanduser()
1682
+ candidates = []
1683
+ if resource_root is not None:
1684
+ candidates.append((resource_root / candidate).resolve())
1685
+ if resolve_path is not None:
1686
+ candidates.append(resolve_path(candidate).resolve())
1687
+ candidates = list(dict.fromkeys(candidates or [candidate.resolve()]))
1688
+ existing = [path for path in candidates if path.is_file()]
1689
+ if len(existing) > 1:
1690
+ from ..contracts import sha256_file
1691
+
1692
+ if len({sha256_file(path) for path in existing}) > 1:
1693
+ raise InputValidationError(
1694
+ f"recurso documental ambíguo {source}: " + "; ".join(map(str, existing))
1695
+ + ". Declare o caminho ou um alias explícito em recursos."
1696
+ )
1697
+ return existing[0] if existing else candidates[0]
1698
+
1699
+ image_occurrences: dict[tuple[str, str], int] = {}
1700
+
1701
+ def image_width(source: str, alt: str) -> str | None:
1702
+ key = (unquote(urlparse(source).path), alt)
1703
+ widths = image_widths.get(key, [])
1704
+ if not widths:
1705
+ return None
1706
+ occurrence = image_occurrences.get(key, 0)
1707
+ image_occurrences[key] = occurrence + 1
1708
+ return widths[min(occurrence, len(widths) - 1)]
1709
+
1710
+ def available_image_width() -> Any:
1711
+ section = document.sections[0]
1712
+ available = section.page_width - section.left_margin - section.right_margin
1713
+ # Pandoc stores the content width at whole-point precision. Use the same
1714
+ # base for implicit widths and percentages so equivalent Markdown has
1715
+ # stable figure geometry across the two renderers.
1716
+ return Pt(int(available / _EMU_PER_POINT))
1717
+
1718
+ def parse_width(value: str | None, source: str) -> Any:
1719
+ if value is None:
1720
+ return None
1721
+ from docx.shared import Cm, Inches, Mm, Pt
1722
+
1723
+ match = re.fullmatch(r"(?P<number>\d+(?:\.\d+)?)(?P<unit>%|in|cm|mm|pt|px)", value.strip(), re.IGNORECASE)
1724
+ if not match or float(match.group("number")) <= 0:
1725
+ pending.append({"type": "unsupported_document_attribute", "attribute": f"width={value}", "resource": source})
1726
+ return None
1727
+ number = float(match.group("number"))
1728
+ unit = match.group("unit").casefold()
1729
+ if unit == "%":
1730
+ available = available_image_width()
1731
+ return available * number / 100
1732
+ if unit == "in":
1733
+ return Inches(number)
1734
+ if unit == "cm":
1735
+ return Cm(number)
1736
+ if unit == "mm":
1737
+ return Mm(number)
1738
+ if unit == "pt":
1739
+ return Pt(number)
1740
+ return Inches(number / 96)
1741
+
1742
+ def add_image(paragraph: Any, token: Any) -> None:
1743
+ source = str(token.attrGet("src") or "")
1744
+ alt = str(token.content or "")
1745
+ image_path = resolve_image(source)
1746
+ if image_path is None:
1747
+ paragraph.add_run(f"[Imagem não incorporada: {source}]")
1748
+ pending.append(
1749
+ {
1750
+ "type": "unsupported_document_resource",
1751
+ "resource": source,
1752
+ "reason": "somente imagens locais são incorporadas",
1753
+ }
1754
+ )
1755
+ return
1756
+ if not image_path.is_file():
1757
+ paragraph.add_run(f"[Imagem ausente: {source}]")
1758
+ pending.append(
1759
+ {
1760
+ "type": "missing_document_resource",
1761
+ "resource": source,
1762
+ "resolved_path": str(image_path),
1763
+ }
1764
+ )
1765
+ return
1766
+ try:
1767
+ width = parse_width(image_width(source, alt), source)
1768
+ if width is None:
1769
+ width = available_image_width()
1770
+ inline = paragraph.add_run().add_picture(str(image_path), width=width)
1771
+ except (OSError, ValueError, UnrecognizedImageError) as exc:
1772
+ paragraph.add_run(f"[Imagem inválida: {source}]")
1773
+ pending.append(
1774
+ {
1775
+ "type": "invalid_document_resource",
1776
+ "resource": source,
1777
+ "resolved_path": str(image_path),
1778
+ "reason": str(exc),
1779
+ }
1780
+ )
1781
+ return
1782
+ if not paragraph.text.strip():
1783
+ _apply_paragraph_style(paragraph, document, "CaptionedFigure", "Captioned Figure")
1784
+ if resolved_resources is not None:
1785
+ resolved_resources[source] = image_path
1786
+ if metadata.get("figure-caption-position", "above").casefold() == "below":
1787
+ paragraph.paragraph_format.keep_with_next = True
1788
+ if alt:
1789
+ inline._inline.docPr.set("descr", alt)
1790
+
1791
+ def set_caption_style(paragraph: Any, content: str) -> None:
1792
+ caption_match = re.match(r"^(Figura|Tabela)\s+\d+\s+-\s+", content)
1793
+ if not caption_match:
1794
+ return
1795
+ names = ("TableCaption", "Table Caption") if caption_match.group(1) == "Tabela" else ("ImageCaption", "Image Caption")
1796
+ if not _apply_paragraph_style(paragraph, document, *names, "Caption", "Legenda"):
1797
+ pending.append({"type": "unsupported_document_style", "style": "Caption"})
1798
+ if caption_match.group(1) == "Tabela" and paragraph._p.pPr is not None:
1799
+ # A table caption inside a Markdown list is a semantic caption, not
1800
+ # an indented continuation paragraph. Pandoc keeps its caption
1801
+ # style and indent while placing the Symbol continuation marker on
1802
+ # the source paragraph that follows the table.
1803
+ number_properties = paragraph._p.pPr.numPr
1804
+ if number_properties is not None:
1805
+ paragraph._p.pPr.remove(number_properties)
1806
+ paragraph.paragraph_format.keep_with_next = (
1807
+ caption_match.group(1) == "Tabela"
1808
+ or metadata.get("figure-caption-position", "above").casefold() != "below"
1809
+ )
1810
+
1811
+ def add_page_break() -> None:
1812
+ from docx.enum.text import WD_BREAK
1813
+
1814
+ document.add_paragraph().add_run().add_break(WD_BREAK.PAGE)
1815
+
1816
+ def add_toc(depth: str, toc_title: str) -> None:
1817
+ from docx.oxml import OxmlElement
1818
+ from docx.oxml.ns import qn
1819
+
1820
+ heading_paragraph = document.add_paragraph(toc_title)
1821
+ if not _apply_paragraph_style(
1822
+ heading_paragraph,
1823
+ document,
1824
+ "TOC Heading",
1825
+ "TOCHeading",
1826
+ "Cabeçalho do Sumário",
1827
+ ):
1828
+ if not _apply_paragraph_style(heading_paragraph, document, "Heading 1", "Título 1"):
1829
+ pending.append({"type": "unsupported_document_style", "style": "TOC Heading"})
1830
+ paragraph = document.add_paragraph()
1831
+ field = OxmlElement("w:fldSimple")
1832
+ field.set(qn("w:instr"), f'TOC \\o "1-{depth}" \\h \\z \\u')
1833
+ run = OxmlElement("w:r")
1834
+ text = OxmlElement("w:t")
1835
+ text.text = "Atualize o sumário no Word para preencher os títulos."
1836
+ run.append(text)
1837
+ field.append(run)
1838
+ paragraph._p.append(field)
1839
+ settings = document.settings._element
1840
+ update_fields = settings.find(qn("w:updateFields"))
1841
+ if update_fields is None:
1842
+ update_fields = OxmlElement("w:updateFields")
1843
+ settings.append(update_fields)
1844
+ update_fields.set(qn("w:val"), "true")
1845
+
1846
+ from docx.oxml import OxmlElement
1847
+ from docx.oxml.ns import qn
1848
+ from docx.text.paragraph import Paragraph
1849
+
1850
+ footnote_definitions: list[Any] = []
1851
+
1852
+ def make_footnote(number: int) -> Any:
1853
+ note = OxmlElement("w:footnote")
1854
+ note.set(qn("w:id"), str(number))
1855
+ footnote_definitions.append(note)
1856
+ paragraph_element = OxmlElement("w:p")
1857
+ paragraph_properties = OxmlElement("w:pPr")
1858
+ paragraph_style = OxmlElement("w:pStyle")
1859
+ paragraph_style.set(qn("w:val"), footnote_text_style_id)
1860
+ paragraph_properties.append(paragraph_style)
1861
+ paragraph_element.append(paragraph_properties)
1862
+ note.append(paragraph_element)
1863
+ paragraph = Paragraph(paragraph_element, document._body)
1864
+
1865
+ run = OxmlElement("w:r")
1866
+ run_properties = OxmlElement("w:rPr")
1867
+ run_style = OxmlElement("w:rStyle")
1868
+ run_style.set(qn("w:val"), footnote_reference_style_id)
1869
+ run_properties.append(run_style)
1870
+ run.append(run_properties)
1871
+ run.append(OxmlElement("w:footnoteRef"))
1872
+ paragraph._p.append(run)
1873
+ paragraph.add_run(" ")
1874
+ return paragraph
1875
+
1876
+ def render_html_block(content: str, line: str) -> bool:
1877
+ html = _HTMLText()
1878
+ try:
1879
+ html.feed(content)
1880
+ except Exception: # noqa: BLE001 - HTML bruto nunca deve interromper a preservação do texto
1881
+ return False
1882
+ element = html.elements[0] if html.elements else ("", {})
1883
+ tag, attributes = element
1884
+ if tag == "argos-page-break":
1885
+ add_page_break()
1886
+ return True
1887
+ if tag == "argos-toc":
1888
+ add_toc(str(attributes.get("depth") or "3"), str(attributes.get("title") or "SUMÁRIO"))
1889
+ return True
1890
+ if tag == "div" and attributes.get("custom-style"):
1891
+ text = "".join(html.parts).strip()
1892
+ paragraph = document.add_paragraph(text)
1893
+ style = str(attributes["custom-style"])
1894
+ if not _apply_paragraph_style(paragraph, document, style):
1895
+ _apply_paragraph_style(paragraph, document, "Caption", "Legenda")
1896
+ pending.append({"type": "unsupported_document_style", "style": style, "line": line})
1897
+ if item_stack:
1898
+ # Custom-style blocks inside a list item are continuation
1899
+ # paragraphs too. Keep the native Symbol marker on this source
1900
+ # paragraph instead of letting it leak onto the table caption.
1901
+ continuation = numbering.new_list(
1902
+ ordered=False,
1903
+ start=1,
1904
+ level=0,
1905
+ delimiter=".",
1906
+ bullet_style=("\uf020", "Symbol"),
1907
+ )
1908
+ numbering.apply(paragraph, continuation, 0)
1909
+ item_stack[-1]["paragraphs"] += 1
1910
+ return True
1911
+ return False
1912
+
1913
+ first_body_paragraph = True
1914
+ numbering = _DocxListNumbering(document)
1915
+
1916
+ def new_paragraph(
1917
+ *, heading: int | None = None, list_marker: tuple[int, int] | None = None,
1918
+ list_depth: int = 0, quote_depth: int = 0, compact: bool = False,
1919
+ ):
1920
+ nonlocal first_body_paragraph
1921
+ if heading is not None:
1922
+ paragraph = document.add_heading("", level=heading)
1923
+ else:
1924
+ paragraph = document.add_paragraph()
1925
+ if list_depth:
1926
+ if compact:
1927
+ _apply_paragraph_style(paragraph, document, "Compact")
1928
+ elif first_body_paragraph:
1929
+ _apply_paragraph_style(paragraph, document, "FirstParagraph", "First Paragraph", "BodyText", "Body Text")
1930
+ else:
1931
+ _apply_paragraph_style(paragraph, document, "BodyText", "Body Text")
1932
+ first_body_paragraph = False
1933
+ if list_marker is not None:
1934
+ numbering.apply(paragraph, *list_marker)
1935
+ elif list_depth:
1936
+ paragraph.paragraph_format.left_indent = Inches(list_depth * 0.5)
1937
+ if quote_depth:
1938
+ paragraph.paragraph_format.left_indent = Inches(quote_depth * 0.3 + list_depth * 0.5)
1939
+ paragraph.paragraph_format.right_indent = Inches(0.2)
1940
+ return paragraph
1941
+
1942
+ def render_table(start: int) -> int:
1943
+ rows: list[list[dict[str, Any]]] = []
1944
+ row: list[dict[str, Any]] | None = None
1945
+ cell: dict[str, Any] | None = None
1946
+ cursor = start + 1
1947
+ while cursor < len(tokens) and tokens[cursor].type != "table_close":
1948
+ token = tokens[cursor]
1949
+ if token.type == "tr_open":
1950
+ row = []
1951
+ elif token.type in {"th_open", "td_open"}:
1952
+ style = token.attrGet("style") or ""
1953
+ alignment = style.partition(":")[2].strip().casefold()
1954
+ cell = {"tokens": [], "header": token.type == "th_open", "alignment": alignment}
1955
+ elif token.type == "inline" and cell is not None:
1956
+ cell["tokens"] = token.children or []
1957
+ elif token.type in {"th_close", "td_close"} and row is not None and cell is not None:
1958
+ row.append(cell)
1959
+ cell = None
1960
+ elif token.type == "tr_close" and row is not None:
1961
+ rows.append(row)
1962
+ row = None
1963
+ cursor += 1
1964
+ if rows and all(item["header"] and not any(
1965
+ token.type == "image" or token.content.strip() for token in item["tokens"]
1966
+ ) for item in rows[0]):
1967
+ rows.pop(0)
1968
+ if not rows:
1969
+ return cursor + 1
1970
+ width = max(len(value) for value in rows)
1971
+ table = document.add_table(rows=len(rows), cols=width)
1972
+ _apply_report_table_style(document, table)
1973
+ from docx.oxml.ns import qn
1974
+
1975
+ table_width = table._tbl.tblPr.find(qn("w:tblW"))
1976
+ table_width.set(qn("w:type"), "pct")
1977
+ table_width.set(qn("w:w"), "5000")
1978
+ for row_index, cells in enumerate(rows):
1979
+ for column, item in enumerate(cells):
1980
+ paragraph = table.cell(row_index, column).paragraphs[0]
1981
+ _apply_paragraph_style(paragraph, document, "Compact")
1982
+ alignment = item["alignment"]
1983
+ if alignment == "center":
1984
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
1985
+ elif alignment == "right":
1986
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
1987
+ _render_inline(
1988
+ paragraph,
1989
+ item["tokens"],
1990
+ add_image=add_image,
1991
+ pending=pending,
1992
+ source_line=None,
1993
+ add_footnote_reference=add_footnote_reference,
1994
+ add_figure_bookmark=add_figure_bookmark,
1995
+ default_bold=bool(item["header"]),
1996
+ )
1997
+ return cursor + 1
1998
+
1999
+ list_stack: list[dict[str, Any]] = []
2000
+ item_stack: list[dict[str, Any]] = []
2001
+ quote_depth = 0
2002
+ paragraph: Any = None
2003
+ paragraph_line: int | None = None
2004
+ heading: int | None = None
2005
+
2006
+ index = 0
2007
+ while index < len(tokens):
2008
+ token = tokens[index]
2009
+ if token.type == "heading_open":
2010
+ heading = int(token.tag[1:])
2011
+ first_body_paragraph = True
2012
+ elif token.type == "heading_close":
2013
+ paragraph = None
2014
+ heading = None
2015
+ paragraph_line = None
2016
+ elif token.type == "paragraph_open":
2017
+ marker = None
2018
+ first_list_paragraph = bool(item_stack and item_stack[-1]["paragraphs"] == 0)
2019
+ if item_stack:
2020
+ if first_list_paragraph:
2021
+ marker = item_stack[-1]["marker"]
2022
+ else:
2023
+ # Pandoc's DOCX writer emits an indented continuation
2024
+ # paragraph as a Symbol bullet. Preserve that native list
2025
+ # semantics instead of leaving only a plain paragraph indent.
2026
+ marker = (
2027
+ numbering.new_list(
2028
+ ordered=False,
2029
+ start=1,
2030
+ level=0,
2031
+ delimiter=".",
2032
+ bullet_style=("\uf020", "Symbol"),
2033
+ ),
2034
+ 0,
2035
+ )
2036
+ item_stack[-1]["paragraphs"] += 1
2037
+ paragraph = new_paragraph(
2038
+ heading=heading,
2039
+ list_marker=marker,
2040
+ list_depth=len(item_stack),
2041
+ quote_depth=quote_depth,
2042
+ compact=bool(token.hidden) or (
2043
+ first_list_paragraph and item_stack[-1]["tight"]
2044
+ ),
2045
+ )
2046
+ if marker is not None and heading is None:
2047
+ item_stack[-1]["first_paragraph"] = paragraph
2048
+ elif token.type == "paragraph_close":
2049
+ paragraph = None
2050
+ paragraph_line = None
2051
+ elif token.type == "inline":
2052
+ if paragraph is None:
2053
+ paragraph = new_paragraph(
2054
+ heading=heading,
2055
+ list_depth=len(item_stack),
2056
+ quote_depth=quote_depth,
2057
+ )
2058
+ if token.map:
2059
+ paragraph_line = token.map[0] + 1
2060
+ set_caption_style(paragraph, token.content)
2061
+ children = token.children
2062
+ if token.content.startswith("| ") and all(line.startswith("| ") for line in token.content.splitlines()):
2063
+ line_block = " \n".join(line[2:] for line in token.content.splitlines())
2064
+ children = parser.parseInline(line_block)[0].children
2065
+ _render_inline(
2066
+ paragraph,
2067
+ children,
2068
+ add_image=add_image,
2069
+ pending=pending,
2070
+ source_line=paragraph_line,
2071
+ add_footnote_reference=add_footnote_reference,
2072
+ add_figure_bookmark=add_figure_bookmark,
2073
+ default_italic=quote_depth > 0,
2074
+ )
2075
+ elif token.type in {"bullet_list_open", "ordered_list_open"}:
2076
+ level = len(list_stack)
2077
+ if level > 8:
2078
+ pending.append({"type": "unsupported_markdown", "feature": "list_depth", "depth": str(level + 1)})
2079
+ level = 8
2080
+ number = numbering.new_list(
2081
+ ordered=token.type == "ordered_list_open", start=int(token.attrGet("start") or 1),
2082
+ level=level, delimiter=token.markup if token.markup in {".", ")"} else ".",
2083
+ )
2084
+ list_stack.append({"number": number, "level": level, "tight": list_tightness.get(index, False)})
2085
+ elif token.type in {"bullet_list_close", "ordered_list_close"}:
2086
+ if list_stack:
2087
+ list_stack.pop()
2088
+ if not list_stack:
2089
+ first_body_paragraph = True
2090
+ elif token.type == "list_item_open":
2091
+ current_list = list_stack[-1]
2092
+ item_stack.append({
2093
+ "marker": (current_list["number"], current_list["level"]),
2094
+ "paragraphs": 0,
2095
+ "tight": current_list["tight"],
2096
+ "first_paragraph": None,
2097
+ })
2098
+ elif token.type == "list_item_close":
2099
+ if item_stack:
2100
+ item_stack.pop()
2101
+ elif token.type == "blockquote_open":
2102
+ quote_depth += 1
2103
+ elif token.type == "blockquote_close":
2104
+ quote_depth = max(0, quote_depth - 1)
2105
+ elif token.type in {"fence", "code_block"}:
2106
+ paragraph = document.add_paragraph()
2107
+ paragraph.paragraph_format.left_indent = Inches(0.25 * quote_depth)
2108
+ for line_number, line in enumerate(token.content.rstrip("\n").split("\n")):
2109
+ if line_number:
2110
+ paragraph.add_run().add_break()
2111
+ run = paragraph.add_run(line)
2112
+ run.font.name = "Consolas"
2113
+ run.font.size = Pt(9)
2114
+ paragraph = None
2115
+ elif token.type == "hr":
2116
+ document.add_paragraph("────────────────────────────────────────")
2117
+ elif token.type == "table_open":
2118
+ index = render_table(index)
2119
+ paragraph = None
2120
+ continue
2121
+ elif token.type == "html_block":
2122
+ line = str((token.map or [0])[0] + 1)
2123
+ if not render_html_block(token.content, line):
2124
+ html = _HTMLText()
2125
+ html.feed(token.content)
2126
+ document.add_paragraph("[Bloco HTML não renderizado] " + "".join(html.parts).strip())
2127
+ pending.append({"type": "unsupported_markdown", "feature": "html_block", "line": line})
2128
+ index += 1
2129
+
2130
+ if note_numbers:
2131
+ identifiers = {str(number): identifier for identifier, number in note_numbers.items()}
2132
+ for original_number, number in note_occurrences:
2133
+ identifier = identifiers[original_number]
2134
+ note_tokens = parser.parse(footnotes[identifier])
2135
+ paragraph = make_footnote(number)
2136
+ note_parent = paragraph._p.getparent()
2137
+ seen_paragraph = False
2138
+ for note_token in note_tokens:
2139
+ if note_token.type == "paragraph_open":
2140
+ if seen_paragraph:
2141
+ element = OxmlElement("w:p")
2142
+ properties = OxmlElement("w:pPr")
2143
+ style = OxmlElement("w:pStyle")
2144
+ style.set(qn("w:val"), footnote_text_style_id)
2145
+ properties.append(style)
2146
+ element.append(properties)
2147
+ note_parent.append(element)
2148
+ paragraph = Paragraph(element, document._body)
2149
+ seen_paragraph = True
2150
+ if note_token.type == "inline":
2151
+ def add_nested_footnote_reference(target: Any, nested_number: str) -> None:
2152
+ run = target.add_run(nested_number)
2153
+ run.font.superscript = True
2154
+
2155
+ _render_inline(
2156
+ paragraph,
2157
+ note_token.children,
2158
+ add_image=add_image,
2159
+ pending=pending,
2160
+ source_line=None,
2161
+ add_footnote_reference=add_nested_footnote_reference,
2162
+ add_figure_bookmark=add_figure_bookmark,
2163
+ )
2164
+ if not paragraph.text.strip():
2165
+ pending.append({"type": "empty_document_note", "reference": identifier})
2166
+
2167
+ _optimize_document_pagination(document)
2168
+ _apply_report_table_layouts(document, table_layouts, _report_default_table_look(layout))
2169
+ _apply_report_paragraph_layouts(document, paragraph_layouts)
2170
+ buffer = io.BytesIO()
2171
+ document.save(buffer)
2172
+ content = buffer.getvalue()
2173
+ if footnote_definitions:
2174
+ content = _attach_footnotes(content, _build_footnotes_xml(footnote_definitions))
2175
+ content = _prune_unreferenced_footnotes(content)
2176
+ return content, tuple(pending)
2177
+
2178
+
2179
+ _IMAGE_INLINE = re.compile(
2180
+ r"!\[(?P<alt>(?:\\.|[^\]])*)\]\("
2181
+ r"(?:<(?P<angle>[^>]+)>|(?P<destination>(?:\\.|[^()]|\((?:\\.|[^()])*\))+?))"
2182
+ r"(?:\s+(?P<title>\"[^\"]*\"|'[^']*'))?\)"
2183
+ )
2184
+ _FIGURE_BOOKMARK_COMMENT = re.compile(r"<!--argos-figure:([^<>]+)-->")
2185
+ _IMAGE_OPEN = re.compile(r"!\[(?:\\.|[^\]])*\]\(")
2186
+ _FENCE_OPEN = re.compile(r"^ {0,3}(?P<marker>`{3,}|~{3,})")
2187
+ _JINJA_IMPORT = re.compile(r"{%[-+]?\s*(?:include|extends|import|from)\s+(['\"])(.*?)\1")
2188
+ _JINJA_DYNAMIC_IMPORT = re.compile(r"{%[-+]?\s*(?:include|extends|import|from)\s+(?!['\"])[^%]+%}")
2189
+
2190
+
2191
+ def _encode_markdown_image_destinations(markdown: str) -> str:
2192
+ """Encode whitespace in bare image paths so CommonMark parsers recognize them."""
2193
+
2194
+ def encode(line: str) -> str:
2195
+ def replace(match: re.Match[str]) -> str:
2196
+ destination = match.group("destination")
2197
+ if destination is None or not re.search(r"\s", destination):
2198
+ return match.group(0)
2199
+ destination = destination.replace(r"\ ", " ")
2200
+ encoded = quote(destination, safe="/:@-._~%")
2201
+ start, end = match.span("destination")
2202
+ before = match.string[match.start() : start]
2203
+ after = match.string[end : match.end()]
2204
+ return before + "<" + encoded + ">" + after
2205
+
2206
+ return _IMAGE_INLINE.sub(replace, line)
2207
+
2208
+ return _map_unfenced_lines(markdown, encode)
2209
+
2210
+
2211
+ def _pipe_table_cells(line: str) -> list[str] | None:
2212
+ """Split a pipe-table row while ignoring escaped pipes and code spans."""
2213
+ _, _, body = _container_prefix(line.rstrip("\r\n"))
2214
+ body = body.strip()
2215
+ if "|" not in body:
2216
+ return None
2217
+ cells: list[str] = []
2218
+ start = 0
2219
+ code_ticks = 0
2220
+ template_end: str | None = None
2221
+ template_quote: str | None = None
2222
+ template_escape = False
2223
+ index = 0
2224
+ while index < len(body):
2225
+ if template_end is not None:
2226
+ char = body[index]
2227
+ if template_quote is not None:
2228
+ if template_escape:
2229
+ template_escape = False
2230
+ elif char == "\\":
2231
+ template_escape = True
2232
+ elif char == template_quote:
2233
+ template_quote = None
2234
+ elif char in {"'", '"'}:
2235
+ template_quote = char
2236
+ elif body.startswith(template_end, index):
2237
+ template_end = None
2238
+ template_quote = None
2239
+ index += 2
2240
+ continue
2241
+ index += 1
2242
+ continue
2243
+ char = body[index]
2244
+ if code_ticks == 0:
2245
+ template_openers = {"{{": "}}", "{%": "%}", "{#": "#}"}
2246
+ opener = body[index:index + 2]
2247
+ if opener in template_openers:
2248
+ template_end = template_openers[opener]
2249
+ index += 2
2250
+ continue
2251
+ if char == "\\":
2252
+ index += 2
2253
+ continue
2254
+ if char == "`":
2255
+ end = index
2256
+ while end < len(body) and body[end] == "`":
2257
+ end += 1
2258
+ run = end - index
2259
+ if code_ticks == 0:
2260
+ code_ticks = run
2261
+ elif code_ticks == run:
2262
+ code_ticks = 0
2263
+ index = end
2264
+ continue
2265
+ if char == "|" and code_ticks == 0:
2266
+ cells.append(body[start:index].strip())
2267
+ start = index + 1
2268
+ index += 1
2269
+ cells.append(body[start:].strip())
2270
+ if body.startswith("|"):
2271
+ cells.pop(0)
2272
+ if body.endswith("|") and not body.endswith(r"\|"):
2273
+ cells.pop()
2274
+ return cells
2275
+
2276
+
2277
+ def _normalize_multiline_pipe_tables(markdown: str, *, document_label: str | None = None) -> str:
2278
+ """Keep wrapped cell text in its logical row, as Pandoc does for pipe tables."""
2279
+ lines = markdown.splitlines(keepends=True)
2280
+ code_lines = _markdown_code_lines(markdown)
2281
+ output: list[str] = []
2282
+ diagnostics: list[str] = []
2283
+ index = 0
2284
+ table_number = 0
2285
+
2286
+ def newline_of(line: str) -> str:
2287
+ if line.endswith("\r\n"):
2288
+ return "\r\n"
2289
+ return "\n" if line.endswith("\n") else ""
2290
+
2291
+ while index < len(lines):
2292
+ header = _pipe_table_cells(lines[index]) if index not in code_lines else None
2293
+ separator = (
2294
+ _pipe_table_cells(lines[index + 1])
2295
+ if index + 1 < len(lines) and index + 1 not in code_lines
2296
+ else None
2297
+ )
2298
+ if not header or not separator or len(header) != len(separator) or not all(
2299
+ re.fullmatch(r":?-+:?", cell) for cell in separator
2300
+ ):
2301
+ output.append(lines[index])
2302
+ index += 1
2303
+ continue
2304
+
2305
+ table_number += 1
2306
+ columns = len(separator)
2307
+ output.extend((lines[index], lines[index + 1]))
2308
+ index += 2
2309
+ pending_body: str | None = None
2310
+ pending_prefix = ""
2311
+ while index < len(lines):
2312
+ raw_line = lines[index]
2313
+ content = raw_line.rstrip("\r\n")
2314
+ if not content.strip() or index in code_lines:
2315
+ if not content.strip() and pending_body is not None:
2316
+ pending_body += " <br> <br> "
2317
+ index += 1
2318
+ continue
2319
+ if pending_body is not None:
2320
+ output.append(pending_prefix + pending_body + newline_of(raw_line))
2321
+ pending_body = None
2322
+ output.append(raw_line)
2323
+ index += 1
2324
+ break
2325
+
2326
+ prefix, _, body = _container_prefix(content)
2327
+ body = body.strip()
2328
+ if pending_body is None:
2329
+ if _pipe_table_cells(body) is None:
2330
+ break
2331
+ pending_prefix = prefix
2332
+ pending_body = body
2333
+ else:
2334
+ pending_body += " <br> " + body
2335
+
2336
+ cells = _pipe_table_cells(pending_body)
2337
+ if cells is not None and len(cells) > columns:
2338
+ table_header = " | ".join(header)
2339
+ candidate_columns = ", ".join(
2340
+ f"{position} ({label!r})" for position, label in enumerate(header, start=1)
2341
+ )
2342
+ context = f"{document_label}: " if document_label else ""
2343
+ diagnostics.append(
2344
+ f"{context}linha {index + 1}: tabela Markdown {table_number} "
2345
+ f"(cabeçalho: {table_header!r}) tem {len(cells)} células, mas define {columns} colunas; "
2346
+ f"delimitadores ambíguos nas colunas candidatas {candidate_columns}. "
2347
+ "Escape barras verticais literais como \\| ou reestruture o conteúdo da célula."
2348
+ )
2349
+ pending_body = None
2350
+ index += 1
2351
+ continue
2352
+ if cells is not None and len(cells) == columns:
2353
+ output.append(pending_prefix + pending_body + newline_of(raw_line))
2354
+ pending_body = None
2355
+ index += 1
2356
+
2357
+ if pending_body is not None:
2358
+ ending = newline_of(lines[index - 1]) if index else ""
2359
+ output.append(pending_prefix + pending_body + ending)
2360
+
2361
+ if diagnostics:
2362
+ raise InputValidationError(
2363
+ "estruturas ambíguas em tabelas Markdown:\n - " + "\n - ".join(diagnostics)
2364
+ )
2365
+ return "".join(output)
2366
+
2367
+
2368
+ def validate_markdown_pipe_tables(markdown: str, *, document_label: str | None = None) -> None:
2369
+ """Valida a contagem das células sem modificar ou renderizar o documento."""
2370
+ _normalize_multiline_pipe_tables(markdown, document_label=document_label)
2371
+
2372
+
2373
+ def parse_image_reference(line: str) -> tuple[str, str] | None:
2374
+ """Extrai a primeira imagem Markdown de uma linha, inclusive inline."""
2375
+ match = _IMAGE_INLINE.search(line)
2376
+ if not match:
2377
+ return None
2378
+ return match.group("alt"), match.group("angle") or match.group("destination")
2379
+
2380
+
2381
+ def document_resources(markdown: str) -> tuple[tuple[str, ...], bool]:
2382
+ """Retorna recursos estáticos e se há includes/imagens Jinja dinâmicos."""
2383
+ references: list[str] = []
2384
+ dynamic = False
2385
+ code_lines = _markdown_code_lines(markdown)
2386
+ for number, line in enumerate(markdown.splitlines()):
2387
+ if number in code_lines:
2388
+ continue
2389
+ images = tuple(_IMAGE_INLINE.finditer(line))
2390
+ if len(images) < len(tuple(_IMAGE_OPEN.finditer(line))):
2391
+ # Unparsed image syntax may still be a valid CommonMark destination
2392
+ # (for example, a path with nested parentheses). Snapshot the
2393
+ # template directory conservatively instead of missing its bytes.
2394
+ dynamic = True
2395
+ for image in images:
2396
+ reference = image.group("angle") or image.group("destination")
2397
+ if "{{" in reference or "{%" in reference:
2398
+ dynamic = True
2399
+ elif not urlparse(reference).scheme or re.match(r"^[A-Za-z]:[\\/]", reference):
2400
+ references.append(unquote(urlparse(reference).path).replace("\\ ", " "))
2401
+ references.extend(match.group(2) for match in _JINJA_IMPORT.finditer(line))
2402
+ dynamic = dynamic or bool(_JINJA_DYNAMIC_IMPORT.search(line))
2403
+ return tuple(dict.fromkeys(references)), dynamic
2404
+
2405
+
2406
+ # --- Conversão DOCX → PDF ---------------------------------------------------
2407
+
2408
+ WINDOWS_WORD_CANDIDATES = (
2409
+ r"C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE",
2410
+ r"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE",
2411
+ )
2412
+
2413
+ LIBREOFFICE_CANDIDATES = (
2414
+ "soffice",
2415
+ "soffice.exe",
2416
+ "libreoffice",
2417
+ "/usr/bin/soffice",
2418
+ "/usr/bin/libreoffice",
2419
+ "/Applications/LibreOffice.app/Contents/MacOS/soffice",
2420
+ )
2421
+
2422
+
2423
+ def pdf_path_for(docx_path: Path) -> Path:
2424
+ """Caminho padrão do PDF: mesmo nome do DOCX, extensão ``.pdf``."""
2425
+ return Path(docx_path).with_suffix(".pdf")
2426
+
2427
+
2428
+ def _word_executable() -> str | None:
2429
+ if os.name != "nt":
2430
+ return None
2431
+ for candidate in WINDOWS_WORD_CANDIDATES:
2432
+ if Path(candidate).is_file():
2433
+ return candidate
2434
+ return shutil.which("WINWORD.EXE") or shutil.which("winword")
2435
+
2436
+
2437
+ def _soffice_executable() -> str | None:
2438
+ for candidate in LIBREOFFICE_CANDIDATES:
2439
+ if os.path.isabs(candidate):
2440
+ if Path(candidate).is_file():
2441
+ return candidate
2442
+ continue
2443
+ found = shutil.which(candidate)
2444
+ if found:
2445
+ return found
2446
+ return None
2447
+
2448
+
2449
+ def _wrapper_text(path: Path) -> str:
2450
+ """Lê um lançador em script sem consumir binários grandes."""
2451
+ try:
2452
+ if not path.is_file() or path.stat().st_size > 65536:
2453
+ return ""
2454
+ return path.read_text(encoding="utf-8", errors="ignore")
2455
+ except OSError:
2456
+ return ""
2457
+
2458
+
2459
+ def _appdir_from_wrapper(path: Path) -> Path | None:
2460
+ """Descobre o AppDir de um wrapper que executa ``AppRun`` (AppImage extraída)."""
2461
+ for line in _wrapper_text(path).splitlines():
2462
+ marker = line.find("AppRun")
2463
+ if marker < 0:
2464
+ continue
2465
+ prefix = line[:marker].strip().strip("'\"")
2466
+ tokens = prefix.split()
2467
+ if not tokens:
2468
+ continue
2469
+ candidate = Path(tokens[-1])
2470
+ if candidate.name == "AppRun":
2471
+ candidate = candidate.parent
2472
+ if candidate.is_dir():
2473
+ return candidate
2474
+ resolved = path.resolve()
2475
+ if resolved.name == "AppRun":
2476
+ return resolved.parent
2477
+ return None
2478
+
2479
+
2480
+ def _libreoffice_launchers(executable: str | Path) -> list[str]:
2481
+ """Resolve wrappers AppImage/AppRun para o lançador real do LibreOffice.
2482
+
2483
+ O ``AppRun`` de algumas instalações AppImage executa ``soffice.bin`` direto,
2484
+ que não inicializa um perfil novo e falha com código 81; o script
2485
+ ``soffice``/``oosplash`` ao lado faz a inicialização e converte. O wrapper
2486
+ permanece como primeira tentativa para não alterar ambientes em que ele
2487
+ funciona.
2488
+ """
2489
+ path = Path(executable).expanduser()
2490
+ launchers = [str(executable)]
2491
+ appdir = _appdir_from_wrapper(path)
2492
+ if appdir is not None:
2493
+ for program in sorted(appdir.glob("opt/*/program")):
2494
+ for name in ("oosplash", "soffice"):
2495
+ candidate = program / name
2496
+ if candidate.is_file() and os.access(candidate, os.X_OK):
2497
+ launchers.append(str(candidate))
2498
+ return launchers
2499
+
2500
+
2501
+ def available_converters() -> tuple[str, ...]:
2502
+ """Conversores disponíveis no ambiente atual, em ordem de preferência."""
2503
+ converters: list[str] = []
2504
+ if _word_executable():
2505
+ converters.append("word")
2506
+ if _soffice_executable():
2507
+ converters.append("libreoffice")
2508
+ return tuple(converters)
2509
+
2510
+
2511
+ def _convert_with_word(source: Path, destination: Path) -> Path:
2512
+ try:
2513
+ import win32com.client # type: ignore[import-not-found]
2514
+ except ImportError as exc: # pragma: no cover - dependência opcional do Windows
2515
+ raise InputValidationError(
2516
+ "conversão via Microsoft Word requer pywin32; instale argos-cli[windows]"
2517
+ ) from exc
2518
+ word = win32com.client.Dispatch("Word.Application")
2519
+ word.Visible = False
2520
+ try:
2521
+ document = word.Documents.Open(str(source), ReadOnly=True)
2522
+ try:
2523
+ document.ExportAsFixedFormat(str(destination), 17) # wdExportFormatPDF
2524
+ finally:
2525
+ document.Close(False)
2526
+ finally:
2527
+ word.Quit()
2528
+ return destination
2529
+
2530
+
2531
+ def _convert_with_libreoffice(source: Path, destination: Path, *, target: str = "pdf") -> Path:
2532
+ executable = _soffice_executable()
2533
+ if executable is None:
2534
+ raise InputValidationError(
2535
+ "LibreOffice (soffice) não encontrado; instale o LibreOffice para gerar PDF"
2536
+ )
2537
+ with tempfile.TemporaryDirectory(prefix="argos-pdf-") as temporary:
2538
+ profile = Path(temporary) / "profile"
2539
+ completed = None
2540
+ # Wrappers AppImage podem executar soffice.bin sem o oosplash que
2541
+ # inicializa o perfil; os lançadores reais do AppDir são tentados em
2542
+ # seguida. O perfil isolado evita colisão com a sessão do usuário e o
2543
+ # fallback sem ele preserva instalações que o recusam.
2544
+ for launcher in _libreoffice_launchers(executable):
2545
+ base = [
2546
+ launcher,
2547
+ "--headless",
2548
+ "--norestore",
2549
+ "--convert-to",
2550
+ target,
2551
+ "--outdir",
2552
+ str(destination.parent),
2553
+ str(source),
2554
+ ]
2555
+ attempts = (
2556
+ [*base[:3], f"-env:UserInstallation={profile.as_uri()}", *base[3:]],
2557
+ base,
2558
+ )
2559
+ for command in attempts:
2560
+ completed = subprocess.run( # noqa: S603 - binário resolvido localmente e sem shell
2561
+ command,
2562
+ check=False,
2563
+ capture_output=True,
2564
+ text=True,
2565
+ timeout=300,
2566
+ )
2567
+ if completed.returncode == 0:
2568
+ break
2569
+ if completed is not None and completed.returncode == 0:
2570
+ break
2571
+ if completed is None or completed.returncode != 0:
2572
+ detail = ((completed.stderr or completed.stdout) if completed else "").strip()
2573
+ raise InputValidationError(
2574
+ f"LibreOffice falhou ao converter {source.name}: {detail or 'erro desconhecido'}"
2575
+ )
2576
+ if not destination.is_file():
2577
+ # O LibreOffice nomeia a saída a partir do arquivo de origem.
2578
+ produced = destination.parent / f"{source.stem}.{target}"
2579
+ if produced.is_file() and produced != destination:
2580
+ shutil.move(str(produced), str(destination))
2581
+ return destination
2582
+
2583
+
2584
+ def convert_docx_to_pdf(source: str | Path, destination: str | Path | None = None) -> Path:
2585
+ """Converte um DOCX em PDF e devolve o caminho do PDF.
2586
+
2587
+ ``destination`` padrão é o mesmo caminho do DOCX com extensão ``.pdf``.
2588
+ Word COM é tentado primeiro no Windows; qualquer falha dele recorre ao
2589
+ LibreOffice headless. O arquivo de saída precisa existir e ser não vazio.
2590
+ """
2591
+ source_path = Path(source).expanduser().resolve()
2592
+ if not source_path.is_file():
2593
+ raise InputValidationError(f"DOCX de entrada ausente: {source_path}")
2594
+ if source_path.suffix.casefold() != ".docx":
2595
+ raise InputValidationError(f"conversão para PDF exige arquivo .docx: {source_path}")
2596
+ destination_path = (
2597
+ Path(destination).expanduser().resolve()
2598
+ if destination is not None
2599
+ else pdf_path_for(source_path)
2600
+ )
2601
+ destination_path.parent.mkdir(parents=True, exist_ok=True)
2602
+
2603
+ errors: list[str] = []
2604
+ if _word_executable() or os.name == "nt":
2605
+ try:
2606
+ _convert_with_word(source_path, destination_path)
2607
+ if destination_path.is_file() and destination_path.stat().st_size > 0:
2608
+ return destination_path
2609
+ except Exception as exc: # noqa: BLE001 - fallback explícito para LibreOffice
2610
+ errors.append(f"Word: {exc}")
2611
+ if _soffice_executable():
2612
+ try:
2613
+ _convert_with_libreoffice(source_path, destination_path)
2614
+ if destination_path.is_file() and destination_path.stat().st_size > 0:
2615
+ return destination_path
2616
+ except Exception as exc: # noqa: BLE001 - erro agregado abaixo
2617
+ errors.append(f"LibreOffice: {exc}")
2618
+ if not errors:
2619
+ raise InputValidationError(
2620
+ "nenhum conversor DOCX→PDF disponível; instale o Microsoft Word ou o LibreOffice"
2621
+ )
2622
+ raise InputValidationError("conversão DOCX→PDF falhou: " + "; ".join(errors))
2623
+
2624
+
2625
+ def docx_bytes_to_pdf(
2626
+ docx_bytes: bytes,
2627
+ *,
2628
+ workdir: Path,
2629
+ stem: str = "documento",
2630
+ ) -> Path:
2631
+ """Converte bytes DOCX em um PDF dentro de ``workdir`` (staging)."""
2632
+ if not isinstance(docx_bytes, (bytes, bytearray)) or not docx_bytes:
2633
+ raise InputValidationError("conversão DOCX→PDF exige bytes do documento")
2634
+ workdir.mkdir(parents=True, exist_ok=True)
2635
+ staged_docx = workdir / f"{stem}.docx"
2636
+ staged_docx.write_bytes(bytes(docx_bytes))
2637
+ return convert_docx_to_pdf(staged_docx, workdir / f"{stem}.pdf")
2638
+
2639
+
2640
+ def _inspect_toc(docx_bytes: bytes) -> dict[str, Any]:
2641
+ from lxml import etree
2642
+
2643
+ namespace = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
2644
+ try:
2645
+ with zipfile.ZipFile(io.BytesIO(docx_bytes), "r") as package:
2646
+ document = etree.fromstring(package.read("word/document.xml"))
2647
+ except (KeyError, OSError, zipfile.BadZipFile, etree.XMLSyntaxError) as exc:
2648
+ raise InputValidationError("DOCX inválido durante a atualização do sumário") from exc
2649
+ instructions = [
2650
+ str(field.get(f"{{{namespace['w']}}}instr") or "")
2651
+ for field in document.xpath(".//w:fldSimple", namespaces=namespace)
2652
+ ]
2653
+ instructions.extend(
2654
+ str(instruction)
2655
+ for instruction in document.xpath(".//w:instrText/text()", namespaces=namespace)
2656
+ )
2657
+ toc_fields = sum("TOC" in instruction.upper() for instruction in instructions)
2658
+ placeholders = []
2659
+ known_placeholders = (
2660
+ "atualize o sumário no word para preencher os títulos.",
2661
+ "o sumário será atualizado ao abrir o documento no word.",
2662
+ )
2663
+ for text in document.xpath(".//w:t/text()", namespaces=namespace):
2664
+ if any(placeholder in str(text).casefold() for placeholder in known_placeholders):
2665
+ placeholders.append(str(text))
2666
+
2667
+ toc_entries = 0
2668
+ for paragraph in document.xpath(".//w:p", namespaces=namespace):
2669
+ styles = paragraph.xpath("./w:pPr/w:pStyle/@w:val", namespaces=namespace)
2670
+ text = "".join(paragraph.xpath(".//w:t/text()", namespaces=namespace)).strip()
2671
+ style = str(styles[0]).casefold() if styles else ""
2672
+ is_toc_entry = (
2673
+ (style.startswith("toc") and style not in {"toc", "tocheading"})
2674
+ or re.match(r"^(?:contents|indice|índice|tableofcontents)\s*\d+$", style) is not None
2675
+ )
2676
+ if is_toc_entry and text:
2677
+ toc_entries += 1
2678
+ for control in document.xpath(
2679
+ ".//w:sdt[w:sdtPr/w:docPartObj/w:docPartGallery[contains(@w:val, 'Table of Contents')]]",
2680
+ namespaces=namespace,
2681
+ ):
2682
+ toc_entries = max(
2683
+ toc_entries,
2684
+ sum(
2685
+ bool("".join(paragraph.xpath(".//w:t/text()", namespaces=namespace)).strip())
2686
+ for paragraph in control.xpath(".//w:p", namespaces=namespace)
2687
+ ),
2688
+ )
2689
+
2690
+ bookmark_names = {
2691
+ str(name)
2692
+ for name in document.xpath(".//w:bookmarkStart/@w:name", namespaces=namespace)
2693
+ }
2694
+ internal_anchors = [
2695
+ str(anchor)
2696
+ for anchor in document.xpath(".//w:hyperlink/@w:anchor", namespaces=namespace)
2697
+ ]
2698
+ broken_anchors = sorted(set(internal_anchors) - bookmark_names)
2699
+ return {
2700
+ "toc_fields": toc_fields,
2701
+ "toc_entries": toc_entries,
2702
+ "placeholders": placeholders,
2703
+ "internal_links": len(internal_anchors),
2704
+ "broken_anchors": broken_anchors,
2705
+ }
2706
+
2707
+
2708
+ def _libreoffice_program_dirs(executable: str) -> list[Path]:
2709
+ candidates: list[Path] = []
2710
+ configured = os.environ.get("LIBREOFFICE_PROGRAM_DIR")
2711
+ if configured:
2712
+ candidates.append(Path(configured).expanduser())
2713
+ executable_path = Path(executable).expanduser()
2714
+ if executable_path.parent.name == "program":
2715
+ candidates.append(executable_path.parent)
2716
+ appdir = _appdir_from_wrapper(executable_path)
2717
+ if appdir is not None:
2718
+ candidates.extend(sorted(appdir.glob("opt/*/program")))
2719
+ candidates.extend((Path("/usr/lib/libreoffice/program"), Path("/usr/lib64/libreoffice/program")))
2720
+ candidates.extend(sorted((Path.home() / ".local/lib/libreoffice/opt").glob("libreoffice*/program")))
2721
+ candidates.extend(sorted(Path("/opt").glob("libreoffice*/program")))
2722
+ return list(dict.fromkeys(path.resolve() for path in candidates if path.is_dir()))
2723
+
2724
+
2725
+ def _find_libreoffice_uno_python(executable: str) -> tuple[str, dict[str, str]]:
2726
+ program_dirs = _libreoffice_program_dirs(executable)
2727
+ candidates: list[Path] = []
2728
+ for program_dir in program_dirs:
2729
+ candidates.extend(program_dir / name for name in ("python", "python3", "python.bin"))
2730
+ candidates.extend(Path(item) for item in (shutil.which("python3"), sys.executable) if item)
2731
+ environment = os.environ.copy()
2732
+ extra_paths = [str(path) for path in program_dirs]
2733
+ if extra_paths:
2734
+ current = environment.get("PYTHONPATH")
2735
+ if current:
2736
+ extra_paths.append(current)
2737
+ environment["PYTHONPATH"] = os.pathsep.join(extra_paths)
2738
+ errors = []
2739
+ for candidate in dict.fromkeys(candidates):
2740
+ if not candidate.is_file() or not os.access(candidate, os.X_OK):
2741
+ continue
2742
+ try:
2743
+ probe = subprocess.run(
2744
+ [str(candidate), "-c", "import uno"],
2745
+ check=False,
2746
+ capture_output=True,
2747
+ text=True,
2748
+ timeout=10,
2749
+ env=environment,
2750
+ )
2751
+ except (OSError, subprocess.TimeoutExpired) as exc:
2752
+ errors.append(str(exc))
2753
+ continue
2754
+ if probe.returncode == 0:
2755
+ return str(candidate), environment
2756
+ if probe.stderr:
2757
+ errors.append(probe.stderr.strip())
2758
+ detail = f": {errors[-1]}" if errors else ""
2759
+ raise InputValidationError(
2760
+ "LibreOffice foi localizado, mas a API Python UNO compatível não está disponível" + detail
2761
+ )
2762
+
2763
+
2764
+ def _free_local_port() -> int:
2765
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
2766
+ server.bind(("127.0.0.1", 0))
2767
+ return int(server.getsockname()[1])
2768
+
2769
+
2770
+ def _run_libreoffice_worker(
2771
+ document_path: Path,
2772
+ executable: str,
2773
+ python_executable: str,
2774
+ environment: Mapping[str, str],
2775
+ *,
2776
+ timeout: float,
2777
+ runner=None,
2778
+ ) -> dict[str, Any]:
2779
+ run = runner or subprocess.run
2780
+ worker = Path(__file__).with_name("_libreoffice_worker.py")
2781
+ with tempfile.TemporaryDirectory(prefix="argos-docx-fields-") as temporary:
2782
+ profile = Path(temporary) / "profile"
2783
+ profile.mkdir()
2784
+ command = [
2785
+ python_executable,
2786
+ str(worker),
2787
+ executable,
2788
+ str(document_path),
2789
+ profile.as_uri(),
2790
+ str(_free_local_port()),
2791
+ str(timeout),
2792
+ ]
2793
+ try:
2794
+ completed = run(
2795
+ command,
2796
+ check=False,
2797
+ capture_output=True,
2798
+ text=True,
2799
+ timeout=timeout + 15,
2800
+ env=dict(environment),
2801
+ )
2802
+ except (OSError, subprocess.TimeoutExpired) as exc:
2803
+ raise InputValidationError(f"não foi possível executar o LibreOffice UNO: {exc}") from exc
2804
+ if completed.returncode != 0:
2805
+ detail = (completed.stderr or completed.stdout or "erro desconhecido").strip()
2806
+ raise InputValidationError(f"LibreOffice falhou ao atualizar os campos: {detail}")
2807
+ try:
2808
+ result = json.loads(completed.stdout)
2809
+ except (TypeError, ValueError) as exc:
2810
+ raise InputValidationError("LibreOffice não confirmou a atualização dos campos") from exc
2811
+ if not isinstance(result, Mapping) or result.get("ok") is not True:
2812
+ raise InputValidationError("LibreOffice não confirmou a atualização dos campos")
2813
+ return dict(result)
2814
+
2815
+
2816
+ def _materialize_with_libreoffice(
2817
+ document_path: Path,
2818
+ *,
2819
+ timeout: float = 120,
2820
+ runner=None,
2821
+ ) -> dict[str, Any]:
2822
+ executable = _soffice_executable()
2823
+ if executable is None:
2824
+ raise InputValidationError("LibreOffice (soffice) não encontrado para atualizar o sumário")
2825
+ python_executable, environment = _find_libreoffice_uno_python(executable)
2826
+ errors = []
2827
+ for launcher in _libreoffice_launchers(executable):
2828
+ try:
2829
+ result = _run_libreoffice_worker(
2830
+ document_path,
2831
+ launcher,
2832
+ python_executable,
2833
+ environment,
2834
+ timeout=timeout,
2835
+ runner=runner,
2836
+ )
2837
+ except InputValidationError as exc:
2838
+ errors.append(str(exc))
2839
+ continue
2840
+ return {"backend": "libreoffice", "indexes": int(result.get("indexes", 0))}
2841
+ raise InputValidationError("LibreOffice não conseguiu atualizar o sumário: " + "; ".join(errors))
2842
+
2843
+
2844
+ def _materialize_with_word(document_path: Path) -> dict[str, Any]:
2845
+ try:
2846
+ import win32com.client # type: ignore[import-not-found]
2847
+ except ImportError as exc: # pragma: no cover - dependência opcional do Windows
2848
+ raise InputValidationError("atualização via Word requer pywin32; instale argos-cli[windows]") from exc
2849
+ word = win32com.client.DispatchEx("Word.Application")
2850
+ word.Visible = False
2851
+ word.DisplayAlerts = 0
2852
+ document = None
2853
+ try:
2854
+ document = word.Documents.Open(str(document_path), ReadOnly=False, AddToRecentFiles=False)
2855
+ for story in document.StoryRanges:
2856
+ current = story
2857
+ while current is not None:
2858
+ current.Fields.Update()
2859
+ current = current.NextStoryRange
2860
+ count = document.TablesOfContents.Count
2861
+ if count < 1:
2862
+ raise InputValidationError("Microsoft Word não reconheceu nenhum campo de sumário no DOCX")
2863
+ for index in range(1, count + 1):
2864
+ document.TablesOfContents.Item(index).Update()
2865
+ document.Fields.Update()
2866
+ document.Save()
2867
+ return {"backend": "word", "indexes": count}
2868
+ except InputValidationError:
2869
+ raise
2870
+ except Exception as exc: # noqa: BLE001 - exceção COM depende da versão do Word
2871
+ raise InputValidationError(f"Microsoft Word falhou ao atualizar os campos: {exc}") from exc
2872
+ finally:
2873
+ if document is not None:
2874
+ document.Close(False)
2875
+ word.Quit()
2876
+
2877
+
2878
+ def materialize_docx_toc(
2879
+ docx_bytes: bytes,
2880
+ *,
2881
+ timeout: float = 120,
2882
+ runner=None,
2883
+ require_entries: bool = True,
2884
+ ) -> tuple[bytes, dict[str, Any]]:
2885
+ """Atualiza sumários/campos pela automação nativa do Word ou do LibreOffice.
2886
+
2887
+ A entrada é uma cópia em staging; os bytes publicados só são devolvidos
2888
+ quando o sumário está materializado e seus vínculos internos continuam válidos.
2889
+ """
2890
+ if not isinstance(docx_bytes, (bytes, bytearray)) or not docx_bytes:
2891
+ raise InputValidationError("atualização do sumário exige bytes DOCX não vazios")
2892
+ before = _inspect_toc(bytes(docx_bytes))
2893
+ if before["toc_fields"] < 1:
2894
+ raise InputValidationError("sumario.atualizar exige um campo TOC no documento")
2895
+ with tempfile.TemporaryDirectory(prefix="argos-docx-toc-") as temporary:
2896
+ staged = Path(temporary) / "relatorio.docx"
2897
+ staged.write_bytes(bytes(docx_bytes))
2898
+ errors = []
2899
+ result = None
2900
+ if _word_executable() or os.name == "nt":
2901
+ try:
2902
+ result = _materialize_with_word(staged)
2903
+ except InputValidationError as exc:
2904
+ errors.append(str(exc))
2905
+ if result is None and _soffice_executable():
2906
+ try:
2907
+ result = _materialize_with_libreoffice(staged, timeout=timeout, runner=runner)
2908
+ except InputValidationError as exc:
2909
+ errors.append(str(exc))
2910
+ if result is None:
2911
+ if not errors:
2912
+ errors.append("nenhum editor compatível (Microsoft Word ou LibreOffice) está disponível")
2913
+ raise InputValidationError("não foi possível materializar o sumário: " + "; ".join(errors))
2914
+ finalized = staged.read_bytes()
2915
+ after = _inspect_toc(finalized)
2916
+ if after["toc_fields"] < 1 or (require_entries and after["toc_entries"] < 1) or after["placeholders"]:
2917
+ raise InputValidationError("o editor não materializou as entradas e páginas do sumário")
2918
+ if after["broken_anchors"]:
2919
+ raise InputValidationError(
2920
+ "o sumário atualizado contém links internos sem destino: " + ", ".join(after["broken_anchors"])
2921
+ )
2922
+ return finalized, {
2923
+ "backend": result["backend"],
2924
+ "indexes": result["indexes"],
2925
+ "toc_fields": after["toc_fields"],
2926
+ "toc_entries": after["toc_entries"],
2927
+ "internal_links": after["internal_links"],
2928
+ }
2929
+
2930
+
2931
+ def finalize_docx_toc(
2932
+ docx_bytes: bytes,
2933
+ *,
2934
+ update: bool | None = None,
2935
+ timeout: float = 120,
2936
+ runner=None,
2937
+ ) -> tuple[bytes, dict[str, Any]]:
2938
+ """Atualiza TOC explícito; ``None`` atualiza quando o DOCX contém um campo TOC."""
2939
+ state = _inspect_toc(docx_bytes)
2940
+ if update is False or (update is None and state["toc_fields"] == 0):
2941
+ return bytes(docx_bytes), {
2942
+ "atualizar": False,
2943
+ "materializado": False,
2944
+ "toc_fields": state["toc_fields"],
2945
+ "toc_entries": state["toc_entries"],
2946
+ }
2947
+ finalized, result = materialize_docx_toc(
2948
+ docx_bytes,
2949
+ timeout=timeout,
2950
+ runner=runner,
2951
+ require_entries=update is True,
2952
+ )
2953
+ return finalized, {"atualizar": True, "materializado": True, **result}