PawMatchAI / history_manager.py
DawnC's picture
Update history_manager.py
f9cdc52 verified
raw
history blame
5.63 kB
from datetime import datetime
import json
import os
import pytz
import traceback
class UserHistoryManager:
def __init__(self):
"""初始化歷史紀錄管理器"""
self.history_file = "user_history.json"
print(f"Initializing UserHistoryManager with file: {os.path.abspath(self.history_file)}")
self._init_file()
def _init_file(self):
"""初始化JSON檔案"""
try:
if not os.path.exists(self.history_file):
print(f"Creating new history file: {self.history_file}")
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump([], f)
else:
print(f"History file exists: {self.history_file}")
# 驗證檔案內容
with open(self.history_file, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"Current history entries: {len(data)}")
except Exception as e:
print(f"Error in _init_file: {str(e)}")
print(traceback.format_exc())
# def save_history(self, user_preferences: dict = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool:
# """
# Save search history with proper timestamp handling.
# Args:
# user_preferences: User's search preferences
# results: List of breed recommendations
# search_type: Type of search performed
# description: Search description if applicable
# Returns:
# bool: Success status of save operation
# """
# try:
# # Initialize timezone and current time
# taipei_tz = pytz.timezone('Asia/Taipei')
# current_time = datetime.now(taipei_tz)
# # Create history entry with timestamp
# history_entry = {
# "timestamp": current_time.strftime("%Y-%m-%d %H:%M:%S"),
# "search_type": search_type,
# "results": results
# }
# # Add preferences to history entry if provided
# if user_preferences:
# history_entry["preferences"] = user_preferences
# # Read existing history
# with open(self.history_file, 'r', encoding='utf-8') as f:
# history = json.load(f)
# # Add new entry and maintain history limit
# history.append(history_entry)
# if len(history) > 20: # Keep last 20 entries
# history = history[-20:]
# # Save updated history
# with open(self.history_file, 'w', encoding='utf-8') as f:
# json.dump(history, f, ensure_ascii=False, indent=2)
# return True
# except Exception as e:
# print(f"Error saving history: {str(e)}")
# return False
def save_history(self, user_preferences: dict = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool:
try:
# 確保 results 格式正確
if results:
for result in results:
if not all(k in result for k in ('breed', 'overall_score')):
print(f"Invalid result entry detected: {result}")
raise ValueError("Each result must include 'breed' and 'overall_score'.")
# 原始保存邏輯保持不變
taipei_tz = pytz.timezone('Asia/Taipei')
current_time = datetime.now(taipei_tz)
history_entry = {
"timestamp": current_time.strftime("%Y-%m-%d %H:%M:%S"),
"search_type": search_type,
"results": results
}
if user_preferences:
history_entry["preferences"] = user_preferences
with open(self.history_file, 'r', encoding='utf-8') as f:
history = json.load(f)
history.append(history_entry)
if len(history) > 20: # 保留最近 20 條
history = history[-20:]
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump(history, f, ensure_ascii=False, indent=2)
print("History saved successfully:", history_entry)
return True
except Exception as e:
print(f"Error saving history: {str(e)}")
print(traceback.format_exc())
return False
def get_history(self) -> list:
"""獲取搜尋歷史"""
try:
print("Attempting to read history") # Debug
with open(self.history_file, 'r', encoding='utf-8') as f:
data = json.load(f)
print(f"Read {len(data)} history entries") # Debug
return data if isinstance(data, list) else []
except Exception as e:
print(f"Error reading history: {str(e)}")
print(traceback.format_exc())
return []
def clear_all_history(self) -> bool:
"""清除所有歷史紀錄"""
try:
print("Attempting to clear all history") # Debug
with open(self.history_file, 'w', encoding='utf-8') as f:
json.dump([], f)
print("History cleared successfully") # Debug
return True
except Exception as e:
print(f"Error clearing history: {str(e)}")
print(traceback.format_exc())
return False