feat: Enhance logging and add chart endpoints

- Updated LoggerDB to remove all active sinks on initialization.
- Added a new PostgresCredencial setup in notas_mmr.py for database connection.
- Replaced print statements with logger calls for better logging in notas_mmr.py.
- Introduced new FastAPI endpoints for various chart types (bar, line, pie, scatter).
- Created Editor_biblioteca.css for styling the rich text editor.
- Implemented Editor_Test.tsx to test the rich text editor functionality.
This commit is contained in:
2025-06-01 00:33:48 +02:00
parent cf6a768f6b
commit 628cddc3ae
18 changed files with 5092 additions and 345 deletions
@@ -0,0 +1,57 @@
from fastapi import APIRouter
router = APIRouter()
@router.get("/bar")
def get_bar_chart():
return {
"xAxis": {"type": "category", "data": ["Ene", "Feb", "Mar", "Abr"]},
"yAxis": {"type": "value"},
"series": [{"data": [5, 20, 36, 10], "type": "bar"}]
}
@router.get("/line")
def get_line_chart():
return {
"xAxis": {"type": "category", "data": ["Semana 1", "Semana 2", "Semana 3", "Semana 4"]},
"yAxis": {"type": "value"},
"series": [{"data": [15, 25, 18, 30], "type": "line"}]
}
@router.get("/pie")
def get_pie_chart():
return {
"tooltip": {"trigger": "item"},
"legend": {"top": "5%", "left": "center"},
"series": [{
"name": "Accesos",
"type": "pie",
"radius": ["40%", "70%"],
"avoidLabelOverlap": False,
"itemStyle": {"borderRadius": 10, "borderColor": "#fff", "borderWidth": 2},
"label": {"show": False, "position": "center"},
"emphasis": {
"label": {"show": True, "fontSize": 16, "fontWeight": "bold"}
},
"labelLine": {"show": False},
"data": [
{"value": 1048, "name": "Search"},
{"value": 735, "name": "Direct"},
{"value": 580, "name": "Email"},
{"value": 484, "name": "Union Ads"},
{"value": 300, "name": "Video Ads"}
]
}]
}
@router.get("/scatter")
def get_scatter_chart():
return {
"xAxis": {},
"yAxis": {},
"series": [{
"symbolSize": 20,
"data": [[10, 8], [20, 20], [30, 10], [40, 30], [50, 15]],
"type": "scatter"
}]
}
@@ -8,6 +8,10 @@ from backend.db.conexion import get_conexion
from backend.services.text_manager_srvc import *
from src.ConexionSql.Postgres_conexion import PostgresConexion
from entrypoint.init_db import db_credencial
from src.Logger.logger_db import LoggerDB, logger
LoggerDB(db_credencial, "logger_textos", created_by="sistema")
router = APIRouter()
+3 -1
View File
@@ -1,8 +1,10 @@
# backend/api/router.py
from fastapi import APIRouter
from backend.api.v1.endpoints import ping, text_manager_endpoint
from backend.api.v1.endpoints import ping, text_manager_endpoint, charts_examples as charts
router = APIRouter()
router.include_router(ping.router, prefix="/api/v1/ping")
router.include_router(text_manager_endpoint.router, prefix="/api/v1/text_manager")
router.include_router(charts.router, prefix="/api/v1/charts")
+21 -24
View File
@@ -8,46 +8,48 @@ from src.TextManager.notas_mmr import generar_tabla_nota_para_biblioteca, NotaRe
from sqlalchemy import MetaData
from backend.schemas.text_manager_schema import NotaInput
from entrypoint.init_db import db_credencial
from src.Logger.logger_db import LoggerDB, logger
LoggerDB(db_credencial, "logger_textos", created_by="sistema")
def crear_biblioteca(nombre_biblioteca: str, conexion: PostgresConexion, descripcion: str = None):
print("[INICIO] Creando biblioteca...")
logger.info("[INICIO] Creando biblioteca...")
try:
print("[Paso 1] Obteniendo credencial...")
logger.info("[Paso 1] Obteniendo credencial...")
cred_repo = OpenAICredencialRepo(conexion)
credencial = cred_repo.get_by_id("OPAK20250513-61b29978b7604031014")
print("[OK] Credencial obtenida:", credencial.titulo if credencial else "❌ None")
logger.debug(f"[OK] Credencial obtenida: {credencial.titulo if credencial else '❌ None'}")
print("[Paso 2] Instanciando embedder...")
logger.info("[Paso 2] Instanciando embedder...")
embedder = OpenAIEmbedder(credencial, model="text-embedding-3-large")
print("[OK] Embedder instanciado")
logger.debug("[OK] Embedder instanciado")
print("[Paso 3] Instanciando biblioteca...")
logger.info("[Paso 3] Instanciando biblioteca...")
biblioteca = Biblioteca(
nombre=nombre_biblioteca,
embedder=embedder,
descripcion=descripcion
)
print(f"[OK] Biblioteca instanciada con ID: {biblioteca.id}")
logger.debug(f"[OK] Biblioteca instanciada con ID: {biblioteca.id}")
print("[Paso 4] Guardando en base de datos...")
logger.info("[Paso 4] Guardando en base de datos...")
repo = BibliotecaRepo(conexion)
repo.add(biblioteca=biblioteca)
print("[OK] Biblioteca guardada")
logger.success("[OK] Biblioteca guardada")
print("[Paso 5] Generando modelo de notas...")
logger.info("[Paso 5] Generando modelo de notas...")
biblioteca.generar_modelo_notas(conexion)
print("[OK] Modelo de notas generado")
logger.success("[OK] Modelo de notas generado")
print("[FIN] Biblioteca creada correctamente")
logger.success("[FIN] Biblioteca creada correctamente")
return {
"mensaje": f"Biblioteca '{nombre_biblioteca}' creada con éxito.",
"id": biblioteca.id
}
except Exception as e:
print("[ERROR] Ocurrió una excepción:", str(e))
logger.exception("[ERROR] Ocurrió una excepción:")
raise
@@ -64,6 +66,7 @@ def listar_bibliotecas(conexion: PostgresConexion) -> list[dict]:
for b in bibliotecas
]
def agregar_nota_a_biblioteca(
conexion: PostgresConexion,
biblioteca_id: str,
@@ -73,25 +76,19 @@ def agregar_nota_a_biblioteca(
conexiones: list[str] = None,
resumen: str = ""
):
# Obtener la biblioteca
repo_biblioteca = BibliotecaRepo(conexion)
biblioteca = repo_biblioteca.get_by_id(biblioteca_id)
if biblioteca is None:
raise ValueError(f"No se encontró la biblioteca con ID {biblioteca_id}")
# Crear objeto Nota
nota = Nota(
titulo=titulo,
texto=texto,
tags=tags or [],
conexiones=conexiones or [],
resumen=resumen or "",
# vector=biblioteca.embedder.embed_text(texto),
# vector_resumen=biblioteca.embedder.embed_text(resumen) if resumen else None
)
# Mostrar atributos seguros
print(
logger.debug(
f"[DEBUG] Nota creada: titulo='{nota.titulo}', "
f"texto_len={len(nota.texto)}, "
f"tags={len(nota.tags)}, "
@@ -99,7 +96,6 @@ def agregar_nota_a_biblioteca(
f"resumen_len={len(nota.resumen)}"
)
# Preparar tabla y modelo de nota
metadata = MetaData()
tabla, ModeloNota = generar_tabla_nota_para_biblioteca(
biblioteca.nombre,
@@ -108,7 +104,6 @@ def agregar_nota_a_biblioteca(
)
metadata.create_all(conexion.get_engine())
# Guardar la nota
repo_nota = NotaRepo(conexion.get_session(), ModeloNota)
nota_id = repo_nota.add(nota)
@@ -117,7 +112,7 @@ def agregar_nota_a_biblioteca(
"nota_id": nota_id
}
print(f"[SUCCESS] {resultado['mensaje']}")
logger.success(f"[SUCCESS] {resultado['mensaje']}")
return resultado
@@ -160,6 +155,7 @@ def eliminar_nota(conexion: PostgresConexion, biblioteca_id: str, nota_id: str)
fue_eliminada = repo_nota.delete_by_id(nota_id)
if fue_eliminada:
logger.success(f"Nota '{nota_id}' eliminada correctamente.")
return {"mensaje": f"Nota '{nota_id}' eliminada correctamente."}
else:
raise ValueError(f"No se encontró la nota con ID: {nota_id}")
@@ -186,6 +182,7 @@ def actualizar_nota(conexion: PostgresConexion, biblioteca_id: str, nota_id: str
fue_actualizada = repo_nota.update(nota_id, nota_actualizada)
if fue_actualizada:
logger.success(f"Nota '{nota_id}' actualizada correctamente.")
return {"mensaje": f"Nota '{nota_id}' actualizada correctamente."}
else:
raise ValueError(f"No se encontró la nota con ID: {nota_id}")