DawnC commited on
Commit
74e8943
1 Parent(s): 2421522

Update history_manager.py

Browse files
Files changed (1) hide show
  1. history_manager.py +75 -34
history_manager.py CHANGED
@@ -11,22 +11,22 @@ class UserHistoryManager:
11
  print(f"Initializing UserHistoryManager with file: {os.path.abspath(self.history_file)}")
12
  self._init_file()
13
 
14
- def _init_file(self):
15
- """初始化JSON檔案"""
16
- try:
17
- if not os.path.exists(self.history_file):
18
- print(f"Creating new history file: {self.history_file}")
19
- with open(self.history_file, 'w', encoding='utf-8') as f:
20
- json.dump([], f)
21
- else:
22
- print(f"History file exists: {self.history_file}")
23
- # 驗證檔案內容
24
- with open(self.history_file, 'r', encoding='utf-8') as f:
25
- data = json.load(f)
26
- print(f"Current history entries: {len(data)}")
27
- except Exception as e:
28
- print(f"Error in _init_file: {str(e)}")
29
- print(traceback.format_exc())
30
 
31
 
32
  # def save_history(self, user_preferences: dict = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool:
@@ -77,40 +77,81 @@ class UserHistoryManager:
77
  # print(f"Error saving history: {str(e)}")
78
  # return False
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  def save_history(self, user_preferences: dict = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool:
 
 
 
 
 
 
 
 
 
 
 
 
81
  try:
82
- # 確保 results 格式正確
83
- if results:
84
- for result in results:
85
- if not all(k in result for k in ('breed', 'overall_score')):
86
- print(f"Invalid result entry detected: {result}")
87
- raise ValueError("Each result must include 'breed' and 'overall_score'.")
88
-
89
- # 原始保存邏輯保持不變
90
  taipei_tz = pytz.timezone('Asia/Taipei')
91
  current_time = datetime.now(taipei_tz)
92
-
 
93
  history_entry = {
94
  "timestamp": current_time.strftime("%Y-%m-%d %H:%M:%S"),
95
- "search_type": search_type,
96
- "results": results
97
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  if user_preferences:
99
  history_entry["preferences"] = user_preferences
100
-
 
101
  with open(self.history_file, 'r', encoding='utf-8') as f:
102
  history = json.load(f)
103
-
 
104
  history.append(history_entry)
105
- if len(history) > 20: # 保留最近 20
106
  history = history[-20:]
107
-
 
108
  with open(self.history_file, 'w', encoding='utf-8') as f:
109
  json.dump(history, f, ensure_ascii=False, indent=2)
110
-
111
- print("History saved successfully:", history_entry)
112
  return True
113
-
114
  except Exception as e:
115
  print(f"Error saving history: {str(e)}")
116
  print(traceback.format_exc())
 
11
  print(f"Initializing UserHistoryManager with file: {os.path.abspath(self.history_file)}")
12
  self._init_file()
13
 
14
+ # def _init_file(self):
15
+ # """初始化JSON檔案"""
16
+ # try:
17
+ # if not os.path.exists(self.history_file):
18
+ # print(f"Creating new history file: {self.history_file}")
19
+ # with open(self.history_file, 'w', encoding='utf-8') as f:
20
+ # json.dump([], f)
21
+ # else:
22
+ # print(f"History file exists: {self.history_file}")
23
+ # # 驗證檔案內容
24
+ # with open(self.history_file, 'r', encoding='utf-8') as f:
25
+ # data = json.load(f)
26
+ # print(f"Current history entries: {len(data)}")
27
+ # except Exception as e:
28
+ # print(f"Error in _init_file: {str(e)}")
29
+ # print(traceback.format_exc())
30
 
31
 
32
  # def save_history(self, user_preferences: dict = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool:
 
77
  # print(f"Error saving history: {str(e)}")
78
  # return False
79
 
80
+
81
+ def _init_file(self):
82
+ """初始化JSON檔案"""
83
+ try:
84
+ if not os.path.exists(self.history_file):
85
+ print(f"Creating new history file: {self.history_file}")
86
+ with open(self.history_file, 'w', encoding='utf-8') as f:
87
+ json.dump([], f)
88
+ else:
89
+ print(f"History file exists: {self.history_file}")
90
+ with open(self.history_file, 'r', encoding='utf-8') as f:
91
+ data = json.load(f)
92
+ print(f"Current history entries: {len(data)}")
93
+ except Exception as e:
94
+ print(f"Error in _init_file: {str(e)}")
95
+ print(traceback.format_exc())
96
+
97
  def save_history(self, user_preferences: dict = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool:
98
+ """
99
+ 保存搜尋歷史,確保結果資料被完整保存
100
+
101
+ Args:
102
+ user_preferences: 使用者的搜尋偏好設定
103
+ results: 品種推薦結果列表
104
+ search_type: 搜尋類型
105
+ description: 搜尋描述
106
+
107
+ Returns:
108
+ bool: 保存是否成功
109
+ """
110
  try:
111
+ # 初始化時區和當前時間
 
 
 
 
 
 
 
112
  taipei_tz = pytz.timezone('Asia/Taipei')
113
  current_time = datetime.now(taipei_tz)
114
+
115
+ # 創建歷史紀錄項目並包含時間戳記
116
  history_entry = {
117
  "timestamp": current_time.strftime("%Y-%m-%d %H:%M:%S"),
118
+ "search_type": search_type
 
119
  }
120
+
121
+ # 確保結果資料的完整性
122
+ if results and isinstance(results, list):
123
+ processed_results = []
124
+ for result in results:
125
+ # 確保每個結果都包含必要的欄位
126
+ if isinstance(result, dict):
127
+ processed_result = {
128
+ 'breed': result.get('breed', 'Unknown'),
129
+ 'overall_score': result.get('overall_score', result.get('final_score', 0)),
130
+ 'rank': result.get('rank', 0)
131
+ }
132
+ processed_results.append(processed_result)
133
+ history_entry["results"] = processed_results
134
+
135
+ # 加入使用者偏好設定(如果有的話)
136
  if user_preferences:
137
  history_entry["preferences"] = user_preferences
138
+
139
+ # 讀��現有歷史
140
  with open(self.history_file, 'r', encoding='utf-8') as f:
141
  history = json.load(f)
142
+
143
+ # 加入新紀錄並保持歷史限制
144
  history.append(history_entry)
145
+ if len(history) > 20: # 保留最近 20
146
  history = history[-20:]
147
+
148
+ # 儲存更新後的歷史
149
  with open(self.history_file, 'w', encoding='utf-8') as f:
150
  json.dump(history, f, ensure_ascii=False, indent=2)
151
+
152
+ print(f"Successfully saved history entry: {history_entry}")
153
  return True
154
+
155
  except Exception as e:
156
  print(f"Error saving history: {str(e)}")
157
  print(traceback.format_exc())