mirror of
https://github.com/Ladebeze66/projetcbaollm.git
synced 2025-12-15 20:06:53 +01:00
50 lines
1.8 KiB
Python
50 lines
1.8 KiB
Python
import json
|
|
import os
|
|
from datetime import datetime
|
|
|
|
# 📂 Dossier où seront stockées les conversations
|
|
HISTORY_DIR = "conversations"
|
|
os.makedirs(HISTORY_DIR, exist_ok=True)
|
|
|
|
def get_history_file(user):
|
|
"""Renvoie le chemin du fichier JSON de l'utilisateur."""
|
|
return os.path.join(HISTORY_DIR, f"{user}.json")
|
|
|
|
def save_conversation(user, user_prompt, bot_response):
|
|
"""Sauvegarde une conversation utilisateur dans son fichier JSON."""
|
|
history_file = get_history_file(user)
|
|
|
|
# 📅 Ajout de l'horodatage (date et heure actuelles)
|
|
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
# 📌 Charger l'historique existant (s'il existe)
|
|
history = []
|
|
if os.path.exists(history_file):
|
|
with open(history_file, "r", encoding="utf-8") as f:
|
|
try:
|
|
history = json.load(f)
|
|
except json.JSONDecodeError:
|
|
pass # On garde une liste vide en cas d'erreur de lecture
|
|
|
|
# 📌 Ajouter le nouveau message avec horodatage
|
|
history.append({
|
|
"timestamp": timestamp,
|
|
"user": user_prompt,
|
|
"bot": bot_response
|
|
})
|
|
|
|
# 📌 Sauvegarder l'historique mis à jour
|
|
with open(history_file, "w", encoding="utf-8") as f:
|
|
json.dump(history, f, indent=4, ensure_ascii=False)
|
|
|
|
def load_conversation(user):
|
|
"""Charge l'historique des conversations d'un utilisateur."""
|
|
history_file = get_history_file(user)
|
|
if os.path.exists(history_file):
|
|
with open(history_file, "r", encoding="utf-8") as f:
|
|
try:
|
|
return json.dumps(json.load(f), indent=4, ensure_ascii=False)
|
|
except json.JSONDecodeError:
|
|
return "❌ Erreur lors de la lecture de l'historique."
|
|
return "⚠️ Aucun historique trouvé pour cet utilisateur."
|