Spaces:
Runtime error
Runtime error
File size: 5,042 Bytes
ff785b4 e7cd4c3 ff785b4 e7cd4c3 ff785b4 e7cd4c3 ff785b4 e7cd4c3 ff785b4 e7cd4c3 | 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 | from fastapi import FastAPI, Depends, BackgroundTasks
from sqlalchemy.orm import Session
from database import get_db, engine, Base
from models import NoticiaAnalizada
from scraper import obtener_ultimas_noticias
from brain import procesar_lote_noticias
from apscheduler.schedulers.background import BackgroundScheduler
from contextlib import asynccontextmanager
from fastapi.middleware.cors import CORSMiddleware
from datetime import datetime, timedelta
# Crea las tablas si no existen
Base.metadata.create_all(bind=engine)
# --- 1. LÓGICA DE LIMPIEZA DE BASE DE DATOS (36 HORAS) ---
def limpiar_base_de_datos():
db = Session(bind=engine)
try:
print("🧹 Iniciando protocolo de limpieza de base de datos...")
limite_tiempo = datetime.utcnow() - timedelta(hours=36)
filas_borradas = db.query(NoticiaAnalizada).filter(NoticiaAnalizada.fecha_creacion < limite_tiempo).delete()
db.commit()
print(f"✨ Limpieza exitosa: {filas_borradas} noticias antiguas eliminadas.")
except Exception as e:
db.rollback()
print(f"⚠️ Error al limpiar la base de datos: {e}")
finally:
db.close()
# --- 2. LÓGICA DE AUTOMATIZACIÓN DE NOTICIAS ---
def tarea_automatizada():
db = Session(bind=engine)
try:
print("🤖 Ejecutando escaneo automático de noticias...")
noticias_web = obtener_ultimas_noticias()
noticias_nuevas = []
for n in noticias_web:
existe_url = db.query(NoticiaAnalizada).filter(NoticiaAnalizada.enlace == n['enlace']).first()
if not existe_url:
noticias_nuevas.append(n)
if not noticias_nuevas:
print("😴 No hay noticias nuevas. Cuota de Gemini ahorrada.")
return
print(f"✨ Se encontraron {len(noticias_nuevas)} noticias nuevas. Procesando...")
resultados = procesar_lote_noticias(noticias_nuevas)
if resultados:
for res in resultados:
# --- FILTRO DE NOTICIAS DESCARTADAS ---
if isinstance(res, dict) and res.get('titular_ia') == "DESCARTAR":
print("🗑️ Noticia internacional descartada (No afecta a Venezuela).")
continue
titular_ia = res.get('titular_ia')
repetida = db.query(NoticiaAnalizada).filter(NoticiaAnalizada.titular == titular_ia).first()
if not repetida:
nueva = NoticiaAnalizada(
titular=titular_ia,
resumen=str(res.get('resumen')),
activos=str(res.get('activos')),
sentimiento=res.get('sentimiento'),
justificacion=res.get('justificacion'),
enlace=res.get('enlace')
)
db.add(nueva)
print(f"✅ Noticia guardada: {titular_ia}")
else:
print(f"⏭️ Omitida (titular ya existe): {titular_ia}")
db.commit()
print("✅ Automatización completada con éxito.")
except Exception as e:
db.rollback()
print(f"⚠️ Error en automatización: {e}")
finally:
db.close()
# --- 3. CONFIGURACIÓN DEL RELOJ (SCHEDULER) ---
scheduler = BackgroundScheduler()
scheduler.add_job(tarea_automatizada, 'interval', hours=4)
scheduler.add_job(limpiar_base_de_datos, 'interval', hours=36) # Se ejecuta cada 36 horas
@asynccontextmanager
async def lifespan(app: FastAPI):
# Cuando el servidor arranca, hace una limpieza inicial por si acaso
limpiar_base_de_datos()
scheduler.start()
yield
scheduler.shutdown()
app = FastAPI(title="Flash Capital API", lifespan=lifespan)
# --- 4. SEGURIDAD ANTI-HACKEO (CORS ESTRICTO) ---
app.add_middleware(
CORSMiddleware,
# ¡SOLO permitimos que tu dominio lea los datos!
allow_origins=["https://flash-capital.web.app"],
allow_methods=["GET"], # Solo lectura, nadie puede borrar datos desde la web
allow_headers=["*"],
)
# --- 5. ENDPOINTS ---
@app.get("/")
def inicio():
return {"mensaje": "Flash Capital operativo, asegurado y automatizado 🚀"}
@app.get("/flash/pildoras")
def obtener_pildoras(db: Session = Depends(get_db)):
return db.query(NoticiaAnalizada).order_by(NoticiaAnalizada.fecha_creacion.desc()).all()
# --- ENDPOINT MANUAL ACTUALIZADO CON TAREAS EN SEGUNDO PLANO ---
@app.get("/flash/analisis")
def forzar_analisis_manual(background_tasks: BackgroundTasks):
background_tasks.add_task(tarea_automatizada)
return {"estado": "🚀 Análisis manual solicitado. El robot está trabajando en segundo plano sin pausar la web."}
# TRAMPA PARA BOTS (Honeypot)
@app.get("/admin/login")
def trampa_bots():
return {"alerta": "Acceso denegado. Intento registrado en el firewall."} |