Spaces:
Running
on
Zero
Running
on
Zero
File size: 7,371 Bytes
ee184bc 10f4c7d ee184bc 9ca8314 f9cdc52 04b305f f9cdc52 04b305f f9cdc52 10f4c7d f9cdc52 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f 10f4c7d 04b305f f9cdc52 04b305f ee184bc f9cdc52 ee184bc |
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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
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 _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:
"""
保存搜尋歷史,確保結果資料被完整保存
Args:
user_preferences: 使用者的搜尋偏好設定
results: 品種推薦結果列表
search_type: 搜尋類型
description: 搜尋描述
Returns:
bool: 保存是否成功
"""
try:
# 初始化時區和當前時間
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
}
# 確保結果資料的完整性
if results and isinstance(results, list):
processed_results = []
for result in results:
# 確保每個結果都包含必要的欄位
if isinstance(result, dict):
processed_result = {
'breed': result.get('breed', 'Unknown'),
'overall_score': result.get('overall_score', result.get('final_score', 0)),
'rank': result.get('rank', 0)
}
processed_results.append(processed_result)
history_entry["results"] = processed_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(f"Successfully saved history entry: {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
|