| """ |
| Conversão otimizada de PDF → Markdown para grandes volumes de Doutrinas. |
| |
| Dois modos: |
| rapido (padrão) - Extração direta via engine C do PyMuPDF, ~5-10x mais rápido |
| completo - Via pymupdf4llm, melhor para tabelas complexas |
| |
| Usa ProcessPoolExecutor para paralelismo real (bypass GIL). |
| """ |
|
|
| import os |
| import sys |
| import argparse |
| import warnings |
| import time |
| from pathlib import Path |
| from typing import List, Dict, Optional, Tuple |
| from collections import Counter |
| from concurrent.futures import ProcessPoolExecutor, as_completed |
|
|
| from tqdm import tqdm |
|
|
| warnings.filterwarnings("ignore") |
|
|
| try: |
| import pymupdf |
| except ImportError: |
| print("ERRO: PyMuPDF não encontrado.") |
| print(" pip install pymupdf pymupdf4llm") |
| sys.exit(1) |
|
|
| |
| |
| |
|
|
| BASE_DOUTRINAS_PATH = Path("data/Doutrinas") |
| OUTPUT_DIR = Path("data/pymupdf_output") |
|
|
|
|
| |
| |
| |
|
|
| def _detectar_corpo(pages_data: list) -> float: |
| """Descobre tamanho de fonte do corpo (mais frequente por nº de caracteres).""" |
| size_chars: Counter = Counter() |
| for data in pages_data: |
| for block in data["blocks"]: |
| if block["type"] != 0: |
| continue |
| for line in block["lines"]: |
| for span in line["spans"]: |
| t = span["text"].strip() |
| if t: |
| size_chars[round(span["size"], 1)] += len(t) |
| return size_chars.most_common(1)[0][0] if size_chars else 12.0 |
|
|
|
|
| def _formatar_span(span: dict) -> str: |
| """Aplica bold/itálico a um span.""" |
| texto = span["text"] |
| t = texto.strip() |
| if not t: |
| return texto |
|
|
| flags = span["flags"] |
| is_bold = bool(flags & 16) |
| is_italic = bool(flags & 2) |
|
|
| if is_bold and is_italic: |
| return f"***{t}*** " |
| elif is_bold: |
| return f"**{t}** " |
| elif is_italic: |
| return f"*{t}* " |
| return texto |
|
|
|
|
| def _formatar_bloco(block: dict, body_size: float) -> Optional[str]: |
| """Converte um bloco de texto em parágrafo markdown.""" |
| if block["type"] != 0: |
| return None |
|
|
| linhas_formatadas = [] |
|
|
| for line in block["lines"]: |
| |
| partes = [_formatar_span(s) for s in line["spans"]] |
| linha = "".join(partes).strip() |
| if not linha: |
| continue |
|
|
| |
| sizes = [round(s["size"], 1) for s in line["spans"] if s["text"].strip()] |
| if sizes: |
| ratio = max(sizes) / body_size if body_size > 0 else 1 |
| if ratio > 1.5: |
| linha = f"# {linha}" |
| elif ratio > 1.3: |
| linha = f"## {linha}" |
| elif ratio > 1.15: |
| linha = f"### {linha}" |
|
|
| linhas_formatadas.append(linha) |
|
|
| if not linhas_formatadas: |
| return None |
|
|
| |
| if len(linhas_formatadas) == 1 and linhas_formatadas[0].startswith("#"): |
| return linhas_formatadas[0] |
|
|
| |
| resultado = linhas_formatadas[0] |
| for proxima in linhas_formatadas[1:]: |
| |
| if resultado.endswith("") or resultado.endswith("-"): |
| |
| if not resultado.endswith(" -"): |
| resultado = resultado[:-1] + proxima |
| continue |
| resultado = resultado + " " + proxima |
|
|
| return resultado |
|
|
|
|
| def _extrair_rapido(caminho_str: str) -> Tuple[str, int]: |
| """ |
| Extração rápida via engine C do PyMuPDF. |
| Usa get_text("dict") que roda em C e faz formatação leve em Python. |
| """ |
| doc = pymupdf.open(caminho_str) |
| num_pages = len(doc) |
|
|
| if num_pages == 0: |
| doc.close() |
| return "", 0 |
|
|
| |
| pages_data = [page.get_text("dict") for page in doc] |
| doc.close() |
|
|
| |
| body_size = _detectar_corpo(pages_data) |
|
|
| |
| page_parts = [] |
|
|
| for data in pages_data: |
| blocos = [] |
| for block in data["blocks"]: |
| formatado = _formatar_bloco(block, body_size) |
| if formatado: |
| blocos.append(formatado) |
|
|
| if blocos: |
| page_parts.append("\n\n".join(blocos)) |
|
|
| return "\n\n---\n\n".join(page_parts), num_pages |
|
|
|
|
| |
| |
| |
|
|
| def _extrair_completo(caminho_str: str) -> Tuple[str, int]: |
| """Extração via pymupdf4llm (Python pesado, melhor qualidade em tabelas).""" |
| import pymupdf4llm as p4l |
|
|
| doc = pymupdf.open(caminho_str) |
| num_pages = len(doc) |
| conteudo = p4l.to_markdown(doc, write_images=False) |
| doc.close() |
| return conteudo, num_pages |
|
|
|
|
| |
| |
| |
|
|
| def _worker(args: Tuple[str, str, str]) -> Dict: |
| """Worker genérico para ProcessPoolExecutor.""" |
| caminho_str, base_str, modo = args |
| caminho = Path(caminho_str) |
|
|
| try: |
| pasta_rel = str(caminho.parent.relative_to(base_str)) |
| except ValueError: |
| pasta_rel = caminho.parent.name |
|
|
| resultado = { |
| "nome": caminho.name, |
| "pasta_relativa": pasta_rel, |
| "sucesso": False, |
| "erro": None, |
| "num_paginas": 0, |
| "conteudo": None, |
| "tempo": 0, |
| } |
|
|
| t0 = time.perf_counter() |
| try: |
| if modo == "rapido": |
| conteudo, npages = _extrair_rapido(caminho_str) |
| else: |
| conteudo, npages = _extrair_completo(caminho_str) |
|
|
| resultado["conteudo"] = conteudo |
| resultado["num_paginas"] = npages |
| resultado["sucesso"] = True |
| except Exception as e: |
| resultado["erro"] = f"{type(e).__name__}: {str(e)[:200]}" |
|
|
| resultado["tempo"] = time.perf_counter() - t0 |
| return resultado |
|
|
|
|
| |
| |
| |
|
|
| def listar_pdfs(pasta_base: Path, pasta_especifica: Optional[str] = None) -> List[Path]: |
| if pasta_especifica: |
| pasta_alvo = pasta_base / pasta_especifica |
| if not pasta_alvo.exists(): |
| return [] |
| pasta_base = pasta_alvo |
| return sorted(p for p in pasta_base.rglob("*") if p.suffix.lower() == ".pdf") |
|
|
|
|
| def salvar_resultado(resultado: Dict, output_dir: Path): |
| if not resultado["sucesso"] or not resultado.get("conteudo"): |
| return |
| pasta_saida = output_dir / resultado["pasta_relativa"] |
| pasta_saida.mkdir(parents=True, exist_ok=True) |
| arquivo = pasta_saida / f"{Path(resultado['nome']).stem}.md" |
| arquivo.write_text(resultado["conteudo"], encoding="utf-8") |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Conversão PDF → Markdown (otimizada para grandes volumes)" |
| ) |
| parser.add_argument("--limite", "-l", type=int, default=None) |
| parser.add_argument("--pasta", "-p", type=str, default=None) |
| parser.add_argument("--salvar", "-s", action="store_true") |
| parser.add_argument( |
| "--workers", "-w", type=int, |
| default=max(1, os.cpu_count() or 4), |
| help="Processos paralelos (padrão: todos os CPUs)", |
| ) |
| parser.add_argument( |
| "--modo", "-m", choices=["rapido", "completo"], default="rapido", |
| help="rapido = PyMuPDF direto (~5-10x mais rápido) | completo = pymupdf4llm", |
| ) |
| args = parser.parse_args() |
|
|
| if not BASE_DOUTRINAS_PATH.exists(): |
| print(f"[ERRO] {BASE_DOUTRINAS_PATH} não existe.") |
| sys.exit(1) |
|
|
| pdfs = listar_pdfs(BASE_DOUTRINAS_PATH, args.pasta) |
| if args.limite: |
| pdfs = pdfs[:args.limite] |
|
|
| if not pdfs: |
| print("[!] Nenhum PDF encontrado.") |
| sys.exit(0) |
|
|
| if args.salvar: |
| OUTPUT_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| modo_label = ( |
| "RÁPIDO (PyMuPDF C-engine direto)" |
| if args.modo == "rapido" |
| else "COMPLETO (pymupdf4llm)" |
| ) |
|
|
| print(f"[*] Modo: {modo_label}") |
| print(f"[*] PDFs: {len(pdfs)} | Workers: {args.workers}") |
| print() |
| sys.stdout.flush() |
|
|
| base_str = str(BASE_DOUTRINAS_PATH) |
| worker_args = [(str(pdf), base_str, args.modo) for pdf in pdfs] |
|
|
| sucessos = 0 |
| falhas = [] |
| t_inicio = time.perf_counter() |
|
|
| with ProcessPoolExecutor(max_workers=args.workers) as executor: |
| futures = {executor.submit(_worker, a): a for a in worker_args} |
|
|
| with tqdm(total=len(pdfs), desc="Convertendo", unit="pdf") as pbar: |
| for future in as_completed(futures): |
| res = future.result() |
|
|
| if res["sucesso"]: |
| sucessos += 1 |
| if args.salvar: |
| salvar_resultado(res, OUTPUT_DIR) |
| else: |
| falhas.append({"nome": res["nome"], "erro": res.get("erro")}) |
|
|
| res.pop("conteudo", None) |
| pbar.update(1) |
|
|
| t_total = time.perf_counter() - t_inicio |
| total = len(pdfs) |
|
|
| print(f"\n{'='*50}") |
| print(f" Modo: {modo_label}") |
| print(f" Tempo: {t_total:.1f}s") |
| print(f" OK: {sucessos}/{total}") |
| print(f" Falhas: {len(falhas)}/{total}") |
| print(f" Média: {t_total/max(total,1):.2f}s/PDF") |
| print(f" Veloc.: {total/max(t_total,0.01):.1f} PDFs/s") |
| print(f"{'='*50}") |
|
|
| if falhas: |
| erros = Counter() |
| for f in falhas: |
| tipo = (f["erro"] or "").split(":")[0] or "?" |
| erros[tipo] += 1 |
|
|
| print(f"\nErros ({len(falhas)}):") |
| for tipo, n in erros.most_common(): |
| print(f" {tipo}: {n}x") |
|
|
| print() |
| for f in falhas[:5]: |
| print(f" {f['nome']} → {f['erro']}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|