Spaces:
Sleeping
Sleeping
Update Historial/historial_chat.py
Browse files- Historial/historial_chat.py +16 -46
Historial/historial_chat.py
CHANGED
|
@@ -1,51 +1,21 @@
|
|
| 1 |
-
|
| 2 |
-
import os
|
| 3 |
-
import time
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
"""
|
| 10 |
-
ruta_historial = os.path.join("Historial", "chat_history.json") # Ruta completa del archivo
|
| 11 |
-
try:
|
| 12 |
-
with open(ruta_historial, "r") as f:
|
| 13 |
-
historial = json.load(f)
|
| 14 |
-
|
| 15 |
-
# Verificar si el historial es una lista
|
| 16 |
-
if not isinstance(historial, list):
|
| 17 |
-
raise json.JSONDecodeError("El historial no es una lista válida", "", 0)
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
return historial
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
json.dump([], f)
|
| 24 |
-
return []
|
| 25 |
-
except json.JSONDecodeError:
|
| 26 |
-
st.warning("El historial de chat está dañado o vacío. Se creará un nuevo historial.")
|
| 27 |
-
with open(ruta_historial, "w") as f:
|
| 28 |
-
json.dump([], f)
|
| 29 |
-
return []
|
| 30 |
-
|
| 31 |
-
def guardar_historial(historial, max_mensajes=100):
|
| 32 |
-
"""Guarda el historial de chat en un archivo JSON, limitando el número de mensajes.
|
| 33 |
-
|
| 34 |
-
Args:
|
| 35 |
-
historial: Lista de diccionarios que representan los mensajes del chat.
|
| 36 |
-
max_mensajes: Número máximo de mensajes a mantener en el historial.
|
| 37 |
-
"""
|
| 38 |
-
ruta_historial = os.path.join("Historial", "chat_history.json")
|
| 39 |
-
try:
|
| 40 |
-
# Limitar el historial
|
| 41 |
-
historial = historial[-max_mensajes:]
|
| 42 |
-
|
| 43 |
-
# Agregar marcas de tiempo si no existen
|
| 44 |
-
for mensaje in historial:
|
| 45 |
-
if "timestamp" not in mensaje:
|
| 46 |
-
mensaje["timestamp"] = time.time()
|
| 47 |
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
print(f"Error al guardar el historial: {e}") # Imprimir el error en la consola
|
|
|
|
| 1 |
+
# Historial/historial_chat.py
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
import os
|
| 4 |
+
import json
|
| 5 |
+
import streamlit as st # Asegúrate de importar Streamlit aquí
|
| 6 |
|
| 7 |
+
HISTORIAL_PATH = "Historial/historial.json"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
+
def cargar_historial():
|
| 10 |
+
if os.path.exists(HISTORIAL_PATH):
|
| 11 |
+
try:
|
| 12 |
+
with open(HISTORIAL_PATH, "r") as f:
|
| 13 |
+
historial = json.load(f)
|
| 14 |
return historial
|
| 15 |
+
except (json.JSONDecodeError, IOError):
|
| 16 |
+
st.warning("El historial de chat está dañado o vacío. Se creará un nuevo historial.")
|
| 17 |
+
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
def guardar_historial(mensajes):
|
| 20 |
+
with open(HISTORIAL_PATH, "w") as f:
|
| 21 |
+
json.dump(mensajes, f, indent=4)
|
|
|