Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,7 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.responses import HTMLResponse
|
|
|
|
|
|
|
| 3 |
import requests
|
| 4 |
import xml.etree.ElementTree as ET
|
| 5 |
import google.generativeai as genai
|
|
@@ -10,59 +12,123 @@ import time
|
|
| 10 |
from bs4 import BeautifulSoup
|
| 11 |
|
| 12 |
app = FastAPI()
|
| 13 |
-
resend.api_key = os.getenv("RESEND_API_KEY")
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
try:
|
| 18 |
-
headers = {
|
|
|
|
|
|
|
| 19 |
resposta = requests.get(url, headers=headers, timeout=15)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
except Exception as e:
|
| 26 |
-
print(f"Erro ao raspar
|
| 27 |
return ""
|
| 28 |
|
|
|
|
| 29 |
def executar_agente_diario():
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
hoje = datetime.now()
|
| 32 |
data_fim = hoje.strftime("%d/%m/%Y")
|
| 33 |
data_inicio = (hoje - timedelta(days=7)).strftime("%d/%m/%Y")
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
url_rss =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
try:
|
| 39 |
-
headers = {
|
| 40 |
resposta_rss = requests.get(url_rss, headers=headers, timeout=20)
|
| 41 |
-
|
| 42 |
-
return f"❌ ERRO RSS: Código de status {resposta_rss.status_code}."
|
| 43 |
|
| 44 |
root = ET.fromstring(resposta_rss.content)
|
| 45 |
-
itens = root.findall(
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
if not itens:
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
#
|
| 53 |
lista_final = []
|
| 54 |
for item in itens:
|
| 55 |
-
|
| 56 |
-
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
bloco_dados = ""
|
| 68 |
for i, a in enumerate(lista_final):
|
|
@@ -70,11 +136,13 @@ def executar_agente_diario():
|
|
| 70 |
|
| 71 |
prompt = f"""
|
| 72 |
Você é um Auditor Analítico da SEPAF Navegantes. Recebemos {len(lista_final)} atos oficiais do Diário.
|
|
|
|
| 73 |
SUA MISSÃO DE AUDITORIA:
|
| 74 |
Crie um relatório com o Título Original e um resumo executivo direto para cada ato.
|
| 75 |
- O Resumo DEVE conter Nomes Próprios, CNPJs, Valores (R$) e a decisão/verbo exato encontrados no 'TEXTO EXTRAÍDO'.
|
| 76 |
- Liste todos individualmente.
|
| 77 |
- Devolva APENAS o código HTML puro (tabela profissional), sem marcadores Markdown como ```html.
|
|
|
|
| 78 |
|
| 79 |
DADOS PARA ANÁLISE:
|
| 80 |
{bloco_dados}
|
|
@@ -84,39 +152,93 @@ def executar_agente_diario():
|
|
| 84 |
response = model.generate_content(prompt)
|
| 85 |
resumo_html = response.text.replace("```html", "").replace("```", "").strip()
|
| 86 |
except Exception as e:
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
# 4. Disparo Resend
|
| 90 |
params = {
|
| 91 |
-
"from":
|
| 92 |
-
"to":
|
| 93 |
"subject": f"🏛️ SEPAF Inteligência: Diário de Navegantes ({data_inicio} a {data_fim})",
|
| 94 |
"html": resumo_html,
|
| 95 |
}
|
| 96 |
|
| 97 |
try:
|
| 98 |
resend.Emails.send(params)
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
except Exception as e:
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
#
|
| 104 |
@app.get("/", response_class=HTMLResponse)
|
| 105 |
def home():
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
<html>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
<body style="font-family: Arial, sans-serif; text-align: center; background-color: #f4f7f6; padding: 50px;">
|
| 109 |
<div style="background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); max-width: 600px; margin: auto;">
|
| 110 |
<h2 style="color: #004a80; margin-bottom: 10px;">🏛️ Painel SEPAF - Agente Diário Oficial</h2>
|
| 111 |
-
<p style="color: #555; margin-bottom:
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
</a>
|
| 115 |
</div>
|
| 116 |
</body>
|
| 117 |
</html>
|
| 118 |
"""
|
| 119 |
|
|
|
|
| 120 |
@app.get("/disparar-robo-secreto-sepaf", response_class=HTMLResponse)
|
| 121 |
def disparar_robo():
|
| 122 |
resultado = executar_agente_diario()
|
|
@@ -125,7 +247,7 @@ def disparar_robo():
|
|
| 125 |
<body style="font-family: Arial, sans-serif; text-align: center; background-color: #f4f7f6; padding: 50px;">
|
| 126 |
<div style="background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); max-width: 700px; margin: auto; text-align: left;">
|
| 127 |
<h2 style="color: #004a80; text-align: center; margin-bottom: 30px;">🔎 Resultado da Execução</h2>
|
| 128 |
-
<div style="padding: 20px; border: 1px solid #ccc; border-radius: 5px; font-size: 16px; font-weight: bold;">
|
| 129 |
{resultado}
|
| 130 |
</div>
|
| 131 |
<div style="text-align: center; margin-top: 30px;">
|
|
@@ -134,4 +256,16 @@ def disparar_robo():
|
|
| 134 |
</div>
|
| 135 |
</body>
|
| 136 |
</html>
|
| 137 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.responses import HTMLResponse
|
| 3 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 4 |
+
from apscheduler.triggers.cron import CronTrigger
|
| 5 |
import requests
|
| 6 |
import xml.etree.ElementTree as ET
|
| 7 |
import google.generativeai as genai
|
|
|
|
| 12 |
from bs4 import BeautifulSoup
|
| 13 |
|
| 14 |
app = FastAPI()
|
|
|
|
| 15 |
|
| 16 |
+
# ─── CONFIGURAÇÃO ───────────────────────────────────────────────
|
| 17 |
+
RESEND_API_KEY = os.getenv("RESEND_API_KEY")
|
| 18 |
+
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
|
| 19 |
+
EMAIL_DESTINO = os.getenv("EMAIL_DESTINO", "marioluiz_mello@hotmail.com")
|
| 20 |
+
EMAIL_REMETENTE = os.getenv("EMAIL_REMETENTE", "onboarding@resend.dev")
|
| 21 |
+
|
| 22 |
+
# Validação no startup
|
| 23 |
+
if not RESEND_API_KEY:
|
| 24 |
+
print("⚠️ AVISO: RESEND_API_KEY não configurada! E-mails não serão enviados.")
|
| 25 |
+
if not GEMINI_API_KEY:
|
| 26 |
+
print("⚠️ AVISO: GEMINI_API_KEY não configurada! Resumos não serão gerados.")
|
| 27 |
+
|
| 28 |
+
resend.api_key = RESEND_API_KEY
|
| 29 |
+
|
| 30 |
+
# ─── VARIÁVEL GLOBAL DE ESTADO ──────────────────────────────────
|
| 31 |
+
ultimo_envio = {"status": "Nunca executado", "data": None, "atos": 0}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# ─── FUNÇÕES AUXILIARES ─────────────────────────────────────────
|
| 35 |
+
def extrair_texto_pagina(url: str) -> str:
|
| 36 |
+
"""Entra no link do ato e extrai o texto para o Gemini."""
|
| 37 |
try:
|
| 38 |
+
headers = {
|
| 39 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.0"
|
| 40 |
+
}
|
| 41 |
resposta = requests.get(url, headers=headers, timeout=15)
|
| 42 |
+
resposta.raise_for_status()
|
| 43 |
+
|
| 44 |
+
soup = BeautifulSoup(resposta.text, "html.parser")
|
| 45 |
+
|
| 46 |
+
# Remove scripts e styles para não poluir o texto
|
| 47 |
+
for tag in soup(["script", "style", "nav", "footer", "header"]):
|
| 48 |
+
tag.decompose()
|
| 49 |
+
|
| 50 |
+
texto = soup.get_text(separator=" ", strip=True)
|
| 51 |
+
return texto[:4000] # Aumentado um pouco para mais contexto
|
| 52 |
+
|
| 53 |
except Exception as e:
|
| 54 |
+
print(f"❌ Erro ao raspar {url}: {e}")
|
| 55 |
return ""
|
| 56 |
|
| 57 |
+
|
| 58 |
def executar_agente_diario():
|
| 59 |
+
"""Executa o pipeline completo: RSS → Raspagem → Gemini → E-mail."""
|
| 60 |
+
global ultimo_envio
|
| 61 |
+
|
| 62 |
+
print(f"🚀 Iniciando agente em {datetime.now()}")
|
| 63 |
+
|
| 64 |
+
# 1. Janela de 7 dias
|
| 65 |
hoje = datetime.now()
|
| 66 |
data_fim = hoje.strftime("%d/%m/%Y")
|
| 67 |
data_inicio = (hoje - timedelta(days=7)).strftime("%d/%m/%Y")
|
| 68 |
|
| 69 |
+
# 2. RSS Público (Filtro 173 = Navegantes)
|
| 70 |
+
url_rss = (
|
| 71 |
+
f"https://diariomunicipal.sc.gov.br/?r=site/portal"
|
| 72 |
+
f"&codigoEntidade=173&dataInicial={data_inicio}"
|
| 73 |
+
f"&dataFinal={data_fim}&view=rss"
|
| 74 |
+
)
|
| 75 |
|
| 76 |
try:
|
| 77 |
+
headers = {"User-Agent": "Mozilla/5.0"}
|
| 78 |
resposta_rss = requests.get(url_rss, headers=headers, timeout=20)
|
| 79 |
+
resposta_rss.raise_for_status()
|
|
|
|
| 80 |
|
| 81 |
root = ET.fromstring(resposta_rss.content)
|
| 82 |
+
itens = root.findall(".//item")
|
| 83 |
+
|
| 84 |
+
except requests.exceptions.RequestException as e:
|
| 85 |
+
msg = f"❌ FALHA DE CONEXÃO: {e}"
|
| 86 |
+
print(msg)
|
| 87 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 88 |
+
return msg
|
| 89 |
+
except ET.ParseError as e:
|
| 90 |
+
msg = f"❌ ERRO AO LER XML: {e}"
|
| 91 |
+
print(msg)
|
| 92 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 93 |
+
return msg
|
| 94 |
|
| 95 |
if not itens:
|
| 96 |
+
msg = f"⚠️ VAZIO: Nenhuma publicação entre {data_inicio} e {data_fim}."
|
| 97 |
+
print(msg)
|
| 98 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 99 |
+
return msg
|
| 100 |
|
| 101 |
+
# 3. Raspagem Profunda (com tratamento de None)
|
| 102 |
lista_final = []
|
| 103 |
for item in itens:
|
| 104 |
+
titulo_elem = item.find("title")
|
| 105 |
+
link_elem = item.find("link")
|
| 106 |
|
| 107 |
+
titulo = titulo_elem.text.strip() if titulo_elem is not None and titulo_elem.text else "Título não disponível"
|
| 108 |
+
link_ato = link_elem.text.strip() if link_elem is not None and link_elem.text else ""
|
| 109 |
+
|
| 110 |
+
texto_ato = extrair_texto_pagina(link_ato) if link_ato else ""
|
| 111 |
+
|
| 112 |
+
lista_final.append({
|
| 113 |
+
"titulo": titulo,
|
| 114 |
+
"link": link_ato,
|
| 115 |
+
"texto": texto_ato
|
| 116 |
+
})
|
| 117 |
+
time.sleep(0.5) # Respeitar o servidor
|
| 118 |
+
|
| 119 |
+
if not lista_final:
|
| 120 |
+
msg = "⚠️ Nenhum ato válido encontrado após filtragem."
|
| 121 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 122 |
+
return msg
|
| 123 |
+
|
| 124 |
+
# 4. Inteligência (Gemini)
|
| 125 |
+
if not GEMINI_API_KEY:
|
| 126 |
+
msg = "❌ GEMINI_API_KEY não configurada."
|
| 127 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 128 |
+
return msg
|
| 129 |
+
|
| 130 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 131 |
+
model = genai.GenerativeModel("gemini-2.5-flash")
|
| 132 |
|
| 133 |
bloco_dados = ""
|
| 134 |
for i, a in enumerate(lista_final):
|
|
|
|
| 136 |
|
| 137 |
prompt = f"""
|
| 138 |
Você é um Auditor Analítico da SEPAF Navegantes. Recebemos {len(lista_final)} atos oficiais do Diário.
|
| 139 |
+
|
| 140 |
SUA MISSÃO DE AUDITORIA:
|
| 141 |
Crie um relatório com o Título Original e um resumo executivo direto para cada ato.
|
| 142 |
- O Resumo DEVE conter Nomes Próprios, CNPJs, Valores (R$) e a decisão/verbo exato encontrados no 'TEXTO EXTRAÍDO'.
|
| 143 |
- Liste todos individualmente.
|
| 144 |
- Devolva APENAS o código HTML puro (tabela profissional), sem marcadores Markdown como ```html.
|
| 145 |
+
- Use CSS inline para garantir que o e-mail renderize bem.
|
| 146 |
|
| 147 |
DADOS PARA ANÁLISE:
|
| 148 |
{bloco_dados}
|
|
|
|
| 152 |
response = model.generate_content(prompt)
|
| 153 |
resumo_html = response.text.replace("```html", "").replace("```", "").strip()
|
| 154 |
except Exception as e:
|
| 155 |
+
msg = f"❌ ERRO NO GEMINI: {e}"
|
| 156 |
+
print(msg)
|
| 157 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 158 |
+
return msg
|
| 159 |
+
|
| 160 |
+
# 5. Disparo Resend
|
| 161 |
+
if not RESEND_API_KEY:
|
| 162 |
+
msg = "❌ RESEND_API_KEY não configurada."
|
| 163 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 164 |
+
return msg
|
| 165 |
|
|
|
|
| 166 |
params = {
|
| 167 |
+
"from": EMAIL_REMETENTE,
|
| 168 |
+
"to": EMAIL_DESTINO,
|
| 169 |
"subject": f"🏛️ SEPAF Inteligência: Diário de Navegantes ({data_inicio} a {data_fim})",
|
| 170 |
"html": resumo_html,
|
| 171 |
}
|
| 172 |
|
| 173 |
try:
|
| 174 |
resend.Emails.send(params)
|
| 175 |
+
msg = f"✅ SUCESSO! {len(lista_final)} publicações processadas e enviadas."
|
| 176 |
+
print(msg)
|
| 177 |
+
ultimo_envio = {
|
| 178 |
+
"status": "Sucesso",
|
| 179 |
+
"data": datetime.now().isoformat(),
|
| 180 |
+
"atos": len(lista_final),
|
| 181 |
+
"periodo": f"{data_inicio} a {data_fim}"
|
| 182 |
+
}
|
| 183 |
+
return msg
|
| 184 |
+
|
| 185 |
except Exception as e:
|
| 186 |
+
msg = f"❌ ERRO NO RESEND: {e}"
|
| 187 |
+
print(msg)
|
| 188 |
+
ultimo_envio = {"status": msg, "data": datetime.now().isoformat(), "atos": 0}
|
| 189 |
+
return msg
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# ─── AGENDADOR (AUTOMATIZAÇÃO) ──────────────────────────────────
|
| 193 |
+
scheduler = BackgroundScheduler()
|
| 194 |
+
|
| 195 |
+
# Roda todo dia às 08:00 (ajuste o horário conforme necessário)
|
| 196 |
+
scheduler.add_job(
|
| 197 |
+
executar_agente_diario,
|
| 198 |
+
trigger=CronTrigger(hour=8, minute=0),
|
| 199 |
+
id="agente_diario",
|
| 200 |
+
name="Agente Diário Oficial",
|
| 201 |
+
replace_existing=True,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
scheduler.start()
|
| 205 |
+
|
| 206 |
|
| 207 |
+
# ─── ROTAS FASTAPI ──────────────────────────────────────────────
|
| 208 |
@app.get("/", response_class=HTMLResponse)
|
| 209 |
def home():
|
| 210 |
+
status = ultimo_envio.get("status", "Nunca executado")
|
| 211 |
+
data = ultimo_envio.get("data", "—")
|
| 212 |
+
atos = ultimo_envio.get("atos", 0)
|
| 213 |
+
|
| 214 |
+
return f"""
|
| 215 |
<html>
|
| 216 |
+
<head>
|
| 217 |
+
<meta charset="UTF-8">
|
| 218 |
+
<title>SEPAF - Agente Diário</title>
|
| 219 |
+
</head>
|
| 220 |
<body style="font-family: Arial, sans-serif; text-align: center; background-color: #f4f7f6; padding: 50px;">
|
| 221 |
<div style="background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); max-width: 600px; margin: auto;">
|
| 222 |
<h2 style="color: #004a80; margin-bottom: 10px;">🏛️ Painel SEPAF - Agente Diário Oficial</h2>
|
| 223 |
+
<p style="color: #555; margin-bottom: 20px;">Conectado via RSS Público, Gemini 2.5 Flash e Resend.</p>
|
| 224 |
+
|
| 225 |
+
<div style="background: #e8f4f8; padding: 15px; border-radius: 5px; margin-bottom: 25px; text-align: left; font-size: 14px;">
|
| 226 |
+
<strong>📊 Última Execução:</strong><br>
|
| 227 |
+
Status: {status}<br>
|
| 228 |
+
Data: {data}<br>
|
| 229 |
+
Atos processados: {atos}
|
| 230 |
+
</div>
|
| 231 |
+
|
| 232 |
+
<a href="/disparar-robo-secreto-sepaf"
|
| 233 |
+
style="display: inline-block; padding: 15px 30px; background-color: #004a80; color: white; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 16px;">
|
| 234 |
+
▶️ Executar Agora (Manual)
|
| 235 |
</a>
|
| 236 |
</div>
|
| 237 |
</body>
|
| 238 |
</html>
|
| 239 |
"""
|
| 240 |
|
| 241 |
+
|
| 242 |
@app.get("/disparar-robo-secreto-sepaf", response_class=HTMLResponse)
|
| 243 |
def disparar_robo():
|
| 244 |
resultado = executar_agente_diario()
|
|
|
|
| 247 |
<body style="font-family: Arial, sans-serif; text-align: center; background-color: #f4f7f6; padding: 50px;">
|
| 248 |
<div style="background: white; padding: 40px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); max-width: 700px; margin: auto; text-align: left;">
|
| 249 |
<h2 style="color: #004a80; text-align: center; margin-bottom: 30px;">🔎 Resultado da Execução</h2>
|
| 250 |
+
<div style="padding: 20px; border: 1px solid #ccc; border-radius: 5px; font-size: 16px; font-weight: bold; white-space: pre-wrap;">
|
| 251 |
{resultado}
|
| 252 |
</div>
|
| 253 |
<div style="text-align: center; margin-top: 30px;">
|
|
|
|
| 256 |
</div>
|
| 257 |
</body>
|
| 258 |
</html>
|
| 259 |
+
"""
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@app.get("/status")
|
| 263 |
+
def status():
|
| 264 |
+
"""Endpoint para verificar o estado do agente via API."""
|
| 265 |
+
return ultimo_envio
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ─── SHUTDOWN GRACEFUL ──────────────────────────────────────────
|
| 269 |
+
@app.on_event("shutdown")
|
| 270 |
+
def shutdown_scheduler():
|
| 271 |
+
scheduler.shutdown()
|