Spaces:
Runtime error
Runtime error
import csv | |
from datetime import datetime | |
import os | |
class ChatLogger: | |
def __init__(self, csv_file='chats.csv'): | |
self.csv_file = csv_file | |
self.current_chat_id = None | |
self.check_csv_file() | |
def check_csv_file(self): | |
"""Crear archivo CSV si no existe""" | |
if not os.path.exists(self.csv_file): | |
with open(self.csv_file, 'w', newline='', encoding='utf-8') as f: | |
writer = csv.writer(f) | |
writer.writerow(['ChatID', 'Timestamp', 'Modo', 'Modelo_IA', 'Rol', 'Mensaje']) | |
def start_new_chat(self, mode, ai_model): | |
"""Iniciar nueva conversación""" | |
self.current_chat_id = datetime.now().strftime("%Y%m%d_%H%M%S") | |
return self.current_chat_id | |
def log_message(self, message, is_user=False, mode=None, ai_model=None): | |
"""Registrar mensaje en CSV""" | |
if not self.current_chat_id: | |
self.current_chat_id = self.start_new_chat(mode, ai_model) | |
try: | |
with open(self.csv_file, 'a', newline='', encoding='utf-8') as f: | |
writer = csv.writer(f) | |
writer.writerow([ | |
self.current_chat_id, | |
datetime.now().strftime("%Y-%m-%d %H:%M:%S"), | |
mode, | |
ai_model, | |
'Usuario' if is_user else 'Asistente', | |
message.replace('\n', ' ') | |
]) | |
except Exception as e: | |
print(f"Error guardando mensaje en log: {e}") | |
def end_chat(self): | |
"""Finalizar chat actual""" | |
self.current_chat_id = None |