Spaces:
Runtime error
Runtime error
Download main.py from FlashCapital/flash-api: direct link, hf CLI and curl.
- Browser
- Download file 5.04 kB
-
https://huggingface.co/spaces/FlashCapital/flash-api/resolve/main/main.py
- Command line
-
hf download hf://spaces/FlashCapital/flash-api/main.py
-
curl -L -o main.py https://huggingface.co/spaces/FlashCapital/flash-api/resolve/main/main.py
5.04 kB
| 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 | |
| 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 --- | |
| def inicio(): | |
| return {"mensaje": "Flash Capital operativo, asegurado y automatizado 🚀"} | |
| 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 --- | |
| 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) | |
| def trampa_bots(): | |
| return {"alerta": "Acceso denegado. Intento registrado en el firewall."} |