File size: 2,307 Bytes
723e654 ab4139b 22458f1 ab4139b 41a98f2 ab4139b 41a98f2 22458f1 41a98f2 22458f1 41a98f2 ab4139b 41a98f2 ab4139b 723e654 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
"""Conversation tracking for BF chatbot"""
import json
import os
from datetime import datetime
from typing import List, Dict, Any
# Konuşma geçmişini saklamak için
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONVERSATIONS_FILE = os.path.join(BASE_DIR, "conversations.json")
PUBLIC_FILE = os.path.join(BASE_DIR, "public", "conversations.json")
MAX_CONVERSATIONS = 100 # Son 100 konuşmayı sakla
def load_conversations():
"""Load conversation history from file"""
if os.path.exists(CONVERSATIONS_FILE):
try:
with open(CONVERSATIONS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except:
return []
return []
def save_conversations(conversations):
"""Save conversations to file"""
try:
# Keep only last MAX_CONVERSATIONS
if len(conversations) > MAX_CONVERSATIONS:
conversations = conversations[-MAX_CONVERSATIONS:]
# Try to save to file
with open(CONVERSATIONS_FILE, 'w', encoding='utf-8') as f:
json.dump(conversations, f, ensure_ascii=False, indent=2)
print(f"✅ Saved {len(conversations)} conversations to {CONVERSATIONS_FILE}")
# Also save to a backup location that Gradio can access
try:
# Create a directory if it doesn't exist
os.makedirs(os.path.dirname(PUBLIC_FILE), exist_ok=True)
with open(PUBLIC_FILE, 'w', encoding='utf-8') as f:
json.dump(conversations, f, ensure_ascii=False, indent=2)
print(f"✅ Also saved to {PUBLIC_FILE}")
except:
pass
except Exception as e:
print(f"❌ Error saving conversations: {e}")
# If file write fails, at least keep in memory
global _memory_conversations
_memory_conversations = conversations
# Keep a memory backup
_memory_conversations = []
def add_conversation(user_message, bot_response):
"""Add a new conversation to history"""
conversations = load_conversations()
conversation = {
"timestamp": datetime.now().isoformat(),
"user": user_message,
"bot": bot_response
}
conversations.append(conversation)
save_conversations(conversations)
return conversation |