Create utils.py
Browse files
utils.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# utils.py
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import re
|
| 5 |
+
import os
|
| 6 |
+
import requests
|
| 7 |
+
import matplotlib.font_manager as fm
|
| 8 |
+
from pydantic import BaseModel, Field, ConfigDict
|
| 9 |
+
from typing import List, Tuple, Optional
|
| 10 |
+
from fpdf import FPDF
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
# --- MODELOS PYDANTIC ---
|
| 14 |
+
class Historico(BaseModel):
|
| 15 |
+
entradas: List[Tuple[str, str]] = []
|
| 16 |
+
|
| 17 |
+
def adicionar(self, pergunta: str, resposta: str):
|
| 18 |
+
if pergunta and resposta:
|
| 19 |
+
self.entradas.append((pergunta, resposta))
|
| 20 |
+
|
| 21 |
+
# --- FUNÇÕES DE PROCESSAMENTO DE TEXTO E DADOS ---
|
| 22 |
+
def descricao_colunas(df: pd.DataFrame) -> str:
|
| 23 |
+
descricao = "\n".join([f"`{col}`: {str(df[col].dtype)}" for col in df.columns])
|
| 24 |
+
return "Colunas do DataFrame:\n" + descricao
|
| 25 |
+
|
| 26 |
+
def limpar_codigo_pandas(codigo: str) -> str:
|
| 27 |
+
codigo = re.sub(r'```(?:python)?\n?', '', codigo)
|
| 28 |
+
codigo = re.sub(r'```', '', codigo)
|
| 29 |
+
linhas = [linha.strip() for linha in codigo.split('\n') if linha.strip()]
|
| 30 |
+
codigo_filtrado = [l for l in linhas if not (l.startswith('#') or 'resposta:' in l.lower())]
|
| 31 |
+
return codigo_filtrado[-1] if codigo_filtrado else ""
|
| 32 |
+
|
| 33 |
+
# --- LÓGICA DE PREPARAÇÃO DE FONTES ---
|
| 34 |
+
FONT_PATH = ""
|
| 35 |
+
def setup_font():
|
| 36 |
+
global FONT_PATH
|
| 37 |
+
FONT_NAME_TO_FIND = "DejaVu Sans"
|
| 38 |
+
try:
|
| 39 |
+
FONT_PATH = fm.findfont(FONT_NAME_TO_FIND, fallback_to_default=True)
|
| 40 |
+
if not os.path.exists(FONT_PATH): raise FileNotFoundError
|
| 41 |
+
print(f"✅ Fonte encontrada localmente: {FONT_PATH}")
|
| 42 |
+
except Exception:
|
| 43 |
+
print(f"⚠️ Fonte '{FONT_NAME_TO_FIND}' não encontrada. Baixando alternativa (Roboto)...")
|
| 44 |
+
FONT_FILE_NAME = "Roboto-Regular.ttf"
|
| 45 |
+
FONT_URL = "https://github.com/google/fonts/raw/main/ofl/roboto/Roboto-Regular.ttf"
|
| 46 |
+
if not os.path.exists(FONT_FILE_NAME):
|
| 47 |
+
try:
|
| 48 |
+
response = requests.get(FONT_URL)
|
| 49 |
+
response.raise_for_status()
|
| 50 |
+
with open(FONT_FILE_NAME, "wb") as f: f.write(response.content)
|
| 51 |
+
FONT_PATH = FONT_FILE_NAME
|
| 52 |
+
print(f"✅ Fonte alternativa baixada!")
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"❌ FALHA CRÍTICA ao baixar fonte: {e}")
|
| 55 |
+
FONT_PATH = ""
|
| 56 |
+
else:
|
| 57 |
+
FONT_PATH = FONT_FILE_NAME
|
| 58 |
+
print(f"✅ Fonte alternativa já existe.")
|
| 59 |
+
return FONT_PATH
|
| 60 |
+
|
| 61 |
+
# --- GERAÇÃO DE PDF ---
|
| 62 |
+
def gerar_pdf_report(historico: Historico, font_path: str):
|
| 63 |
+
if not historico or not historico.entradas:
|
| 64 |
+
print("⚠️ Tentativa de gerar PDF com histórico vazio.")
|
| 65 |
+
return None
|
| 66 |
+
if not font_path or not os.path.exists(font_path):
|
| 67 |
+
print(f"❌ Erro ao gerar PDF: Arquivo da fonte não encontrado em '{font_path}'.")
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 72 |
+
caminho_pdf = f"relatorio_consultas_{timestamp}.pdf"
|
| 73 |
+
pdf = FPDF()
|
| 74 |
+
pdf.add_page()
|
| 75 |
+
pdf.add_font('CustomFont', '', font_path, uni=True)
|
| 76 |
+
pdf.set_font('CustomFont', '', 16)
|
| 77 |
+
pdf.cell(0, 10, "Relatório de Consultas ao CSV", ln=True, align="C")
|
| 78 |
+
pdf.ln(10)
|
| 79 |
+
|
| 80 |
+
for i, (pergunta, resposta) in enumerate(historico.entradas, 1):
|
| 81 |
+
pdf.set_font('CustomFont', '', 12)
|
| 82 |
+
pdf.multi_cell(0, 8, f"Pergunta {i}: {pergunta}")
|
| 83 |
+
pdf.ln(2)
|
| 84 |
+
pdf.set_font('CustomFont', '', 10)
|
| 85 |
+
pdf.multi_cell(0, 6, f"Resposta: {resposta}")
|
| 86 |
+
pdf.ln(8)
|
| 87 |
+
pdf.cell(0, 0, '', 'T'); pdf.ln(8)
|
| 88 |
+
|
| 89 |
+
pdf.output(caminho_pdf)
|
| 90 |
+
print(f"✅ PDF gerado: {caminho_pdf}")
|
| 91 |
+
return caminho_pdf
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"❌ Erro crítico ao gerar PDF: {e}")
|
| 94 |
+
return None
|