import gradio as gr import traceback from typing import Optional, Dict, List from history_manager import UserHistoryManager class SearchHistoryComponent: def __init__(self): """初始化搜索歷史組件""" self.history_manager = UserHistoryManager() def format_history_html(self, history_data: Optional[List[Dict]] = None) -> str: try: if history_data is None: history_data = self.history_manager.get_history() if not history_data: return """

No search history yet. Try making some breed recommendations!

""" html = "
" for entry in reversed(history_data): timestamp = entry.get('timestamp', 'Unknown time') search_type = entry.get('search_type', 'criteria') results = entry.get('results', []) # 根據搜尋類型使用不同的標題樣式 type_label = "Criteria History" if search_type == "criteria" else "Description History" type_color = "#4299e1" if search_type == "criteria" else "#48bb78" # 藍色vs綠色 html += f"""
🕒 {timestamp} {type_label}
""" if search_type == "criteria": prefs = entry.get('preferences', {}) html += f"""

Search Parameters:

  • Living Space: {prefs.get('living_space', 'N/A')}
  • Exercise Time: {prefs.get('exercise_time', 'N/A')} minutes
  • Grooming: {prefs.get('grooming_commitment', 'N/A')}
  • Experience: {prefs.get('experience_level', 'N/A')}
  • Children at Home: {"Yes" if prefs.get('has_children') else "No"}
  • Noise Tolerance: {prefs.get('noise_tolerance', 'N/A')}
""" else: # Description 搜尋的顯示邏輯 description = entry.get('description', 'No description provided') html += f"""

Search Description:

{description}

""" # 共用的結果顯示邏輯 html += """

Top 10 Breed Matches:

""" if results: for i, result in enumerate(results[:10], 1): breed_name = result.get('breed', 'Unknown breed').replace('_', ' ') score = result.get('overall_score', result.get('final_score', 0)) html += f"""
#{i} {breed_name} {score*100:.1f}%
""" html += """
""" html += "
" return html except Exception as e: print(f"Error formatting history: {str(e)}") print(traceback.format_exc()) return f"""
Error formatting history. Please try refreshing the page.
Error details: {str(e)}
""" def clear_history(self) -> str: """清除所有搜尋歷史""" try: success = self.history_manager.clear_all_history() print(f"Clear history result: {success}") return self.format_history_html() except Exception as e: print(f"Error in clear_history: {str(e)}") print(traceback.format_exc()) return "Error clearing history" def refresh_history(self) -> str: """刷新歷史記錄顯示""" try: return self.format_history_html() except Exception as e: print(f"Error in refresh_history: {str(e)}") return "Error refreshing history" def save_search(self, user_preferences: Optional[dict] = None, results: list = None, search_type: str = "criteria", description: str = None) -> bool: """保存搜索結果 Args: user_preferences: 使用者偏好設定 (僅用於criteria搜尋) results: 推薦結果列表 search_type: 搜尋類型 ("criteria" 或 "description") description: 使用者輸入的描述 (僅用於description搜尋) """ return self.history_manager.save_history( user_preferences=user_preferences, results=results, search_type=search_type, description=description ) def create_history_component(): """只創建實例""" return SearchHistoryComponent() def create_history_tab(history_component: SearchHistoryComponent): """創建歷史紀錄的頁面 Args: history_component: """ with gr.TabItem("Recommendation Search History"): gr.HTML("""

Search History

View your previous breed recommendations and search preferences

""") with gr.Row(): with gr.Column(scale=4): history_display = gr.HTML() with gr.Row(): with gr.Column(scale=1): clear_history_btn = gr.Button( "🗑️ Clear History", variant="secondary", size="sm" ) with gr.Column(scale=1): refresh_btn = gr.Button( "🔄 Refresh", variant="secondary", size="sm" ) history_display.value = history_component.format_history_html() clear_history_btn.click( fn=history_component.clear_history, outputs=[history_display], api_name="clear_history" ) refresh_btn.click( fn=history_component.refresh_history, outputs=[history_display], api_name="refresh_history" )