Josedcape commited on
Commit
2f82086
·
verified ·
1 Parent(s): cdb9ff5

Update Historial/historial_chat.py

Browse files
Files changed (1) hide show
  1. Historial/historial_chat.py +16 -46
Historial/historial_chat.py CHANGED
@@ -1,51 +1,21 @@
1
- import json
2
- import os
3
- import time
4
 
5
- def cargar_historial():
6
- """Carga el historial de chat desde un archivo JSON.
 
7
 
8
- Si el archivo no existe, se crea uno vacío. Si el archivo está dañado, se muestra una advertencia y se crea uno nuevo.
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
- except FileNotFoundError:
21
- # Crear el archivo si no existe
22
- with open(ruta_historial, "w") as f:
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
- with open(ruta_historial, "w") as f:
49
- json.dump(historial, f, indent=4) # Indentación para mejor legibilidad
50
- except Exception as e:
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)