File size: 8,919 Bytes
780413d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
"""
Formatador de saída Markdown.

Este módulo contém funções e classes para formatar documentos
processados em formato Markdown.
"""

from datetime import datetime
from pathlib import Path
from typing import Any, Optional

from utils.logger import get_logger

# Logger para este módulo
logger = get_logger(__name__)


def format_to_markdown(
    processed_data: dict[str, Any],
    include_metadata_header: bool = True,
    include_tables: bool = True
) -> str:
    """
    Formata dados processados em Markdown.

    Args:
        processed_data: Dados retornados pelo DoclingProcessor.
        include_metadata_header: Se deve incluir cabeçalho com metadados.
        include_tables: Se deve incluir tabelas formatadas.

    Returns:
        String Markdown formatada.
    """
    document = processed_data.get("document")
    metadata = processed_data.get("metadata", {})
    tables = processed_data.get("tables", [])
    language = processed_data.get("language", "desconhecido")

    sections = []

    # Cabeçalho com metadados
    if include_metadata_header:
        header = _format_metadata_header(metadata, language)
        if header:
            sections.append(header)

    # Conteúdo principal do documento
    if document:
        try:
            if hasattr(document, "export_to_markdown"):
                content = document.export_to_markdown()
                if content:
                    sections.append(content)
        except Exception as e:
            logger.warning(f"Erro ao exportar Markdown: {e}")
            sections.append(f"> ⚠️ Erro ao exportar conteúdo: {e}")

    # Tabelas (se não foram incluídas no export padrão)
    if include_tables and tables:
        tables_section = _format_tables_section(tables)
        if tables_section:
            sections.append(tables_section)

    return "\n\n---\n\n".join(sections)


def _format_metadata_header(
    metadata: dict[str, Any],
    language: str
) -> str:
    """
    Formata cabeçalho com metadados.

    Args:
        metadata: Dicionário de metadados.
        language: Código do idioma.

    Returns:
        String Markdown com metadados.
    """
    lines = []

    # Título
    titulo = metadata.get("titulo", metadata.get("nome_arquivo", "Documento"))
    lines.append(f"# {titulo}")
    lines.append("")

    # Metadados como lista
    meta_items = []

    if metadata.get("autor"):
        meta_items.append(f"**Autor:** {metadata['autor']}")

    if metadata.get("data_criacao"):
        meta_items.append(f"**Data de criação:** {metadata['data_criacao']}")

    if language and language not in ("desconhecido", "erro", "nao_detectado"):
        lang_names = {
            "pt": "Português",
            "en": "Inglês",
            "es": "Espanhol",
            "fr": "Francês",
            "de": "Alemão",
            "it": "Italiano",
        }
        lang_name = lang_names.get(language, language.upper())
        meta_items.append(f"**Idioma:** {lang_name}")

    if metadata.get("num_paginas"):
        meta_items.append(f"**Páginas:** {metadata['num_paginas']}")

    if metadata.get("num_tabelas"):
        meta_items.append(f"**Tabelas:** {metadata['num_tabelas']}")

    if metadata.get("num_imagens"):
        meta_items.append(f"**Imagens:** {metadata['num_imagens']}")

    if meta_items:
        lines.extend(meta_items)
        lines.append("")

    return "\n".join(lines)


def _format_tables_section(tables: list[dict[str, Any]]) -> str:
    """
    Formata seção de tabelas.

    Args:
        tables: Lista de tabelas extraídas.

    Returns:
        String Markdown com tabelas.
    """
    if not tables:
        return ""

    lines = ["## Tabelas Extraídas", ""]

    for table in tables:
        index = table.get("indice", 0)
        lines.append(f"### Tabela {index}")
        lines.append("")

        # Se tem dados como dict/list, formata como tabela MD
        if table.get("dados"):
            md_table = _dict_to_markdown_table(table["dados"])
            lines.append(md_table)
        elif table.get("markdown"):
            lines.append(table["markdown"])
        elif table.get("texto"):
            lines.append(f"```\n{table['texto']}\n```")
        else:
            lines.append("*Dados da tabela não disponíveis*")

        lines.append("")

    return "\n".join(lines)


def _dict_to_markdown_table(data: list[dict[str, Any]]) -> str:
    """
    Converte lista de dicionários em tabela Markdown.

    Args:
        data: Lista de dicionários (cada dict = uma linha).

    Returns:
        String com tabela em formato Markdown pipe.
    """
    if not data:
        return "*Tabela vazia*"

    # Pega colunas do primeiro item
    headers = list(data[0].keys())

    lines = []

    # Cabeçalho
    header_line = "| " + " | ".join(str(h) for h in headers) + " |"
    lines.append(header_line)

    # Separador
    separator = "| " + " | ".join("---" for _ in headers) + " |"
    lines.append(separator)

    # Dados
    for row in data:
        values = []
        for h in headers:
            value = row.get(h, "")
            # Escapa pipes no conteúdo
            value = str(value).replace("|", "\\|")
            # Remove quebras de linha
            value = value.replace("\n", " ")
            values.append(value)

        row_line = "| " + " | ".join(values) + " |"
        lines.append(row_line)

    return "\n".join(lines)


class MarkdownFormatter:
    """
    Classe para formatação Markdown com configurações personalizadas.

    Permite manter configurações consistentes entre múltiplas formatações.
    """

    def __init__(
        self,
        include_metadata_header: bool = True,
        include_tables: bool = True,
        include_toc: bool = False,
        max_heading_level: int = 6
    ):
        """
        Inicializa o formatador Markdown.

        Args:
            include_metadata_header: Se deve incluir cabeçalho com metadados.
            include_tables: Se deve incluir tabelas extraídas.
            include_toc: Se deve incluir sumário (Table of Contents).
            max_heading_level: Nível máximo de heading a usar.
        """
        self.include_metadata_header = include_metadata_header
        self.include_tables = include_tables
        self.include_toc = include_toc
        self.max_heading_level = max_heading_level

    def format(self, processed_data: dict[str, Any]) -> str:
        """
        Formata dados processados em Markdown.

        Args:
            processed_data: Dados do DoclingProcessor.

        Returns:
            String Markdown formatada.
        """
        content = format_to_markdown(
            processed_data,
            include_metadata_header=self.include_metadata_header,
            include_tables=self.include_tables
        )

        if self.include_toc:
            toc = self._generate_toc(content)
            if toc:
                content = f"{toc}\n\n---\n\n{content}"

        return content

    def _generate_toc(self, content: str) -> str:
        """
        Gera sumário (Table of Contents) do conteúdo.

        Args:
            content: Conteúdo Markdown.

        Returns:
            String com sumário em Markdown.
        """
        import re

        lines = []
        lines.append("## Sumário")
        lines.append("")

        # Encontra headings
        heading_pattern = r"^(#{1,6})\s+(.+)$"

        for line in content.split("\n"):
            match = re.match(heading_pattern, line)
            if match:
                level = len(match.group(1))
                title = match.group(2)

                if level <= self.max_heading_level:
                    # Cria link
                    anchor = self._slugify(title)
                    indent = "  " * (level - 1)
                    lines.append(f"{indent}- [{title}](#{anchor})")

        return "\n".join(lines) if len(lines) > 2 else ""

    def _slugify(self, text: str) -> str:
        """
        Converte texto em slug para anchor.

        Args:
            text: Texto a converter.

        Returns:
            Slug do texto.
        """
        import re

        # Converte para lowercase
        slug = text.lower()

        # Remove caracteres especiais
        slug = re.sub(r"[^\w\s-]", "", slug)

        # Substitui espaços por hífens
        slug = re.sub(r"\s+", "-", slug)

        return slug


def save_markdown(
    content: str,
    output_path: str | Path,
    encoding: str = "utf-8"
) -> Path:
    """
    Salva conteúdo Markdown em arquivo.

    Args:
        content: String Markdown.
        output_path: Caminho do arquivo de saída.
        encoding: Encoding do arquivo.

    Returns:
        Path para o arquivo salvo.
    """
    output_path = Path(output_path)

    output_path.write_text(content, encoding=encoding)
    logger.debug(f"Markdown salvo: {output_path}")

    return output_path