File size: 6,401 Bytes
0852a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

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:
        """將歷史記錄格式化為HTML"""
        try:
            if history_data is None:
                history_data = self.history_manager.get_history()

            if not history_data:
                return """
                <div style='text-align: center; padding: 20px; color: #666;'>
                    No search history yet. Try making some breed recommendations!
                </div>
                """

            html = "<div class='history-container'>"

            for entry in reversed(history_data):
                timestamp = entry.get('timestamp', 'Unknown time')
                prefs = entry.get('preferences', {})
                results = entry.get('results', [])

                html += f"""
                <div class="history-entry">
                    <div class="history-header">
                        <span class="timestamp">🕒 {timestamp}</span>
                    </div>

                    <div class="params-list">
                        <h4>Search Parameters:</h4>
                        <ul>
                            <li><span class="param-label">Living Space:</span> {prefs.get('living_space', 'N/A')}</li>
                            <li><span class="param-label">Exercise Time:</span> {prefs.get('exercise_time', 'N/A')} minutes</li>
                            <li><span class="param-label">Grooming:</span> {prefs.get('grooming_commitment', 'N/A')}</li>
                            <li><span class="param-label">Experience:</span> {prefs.get('experience_level', 'N/A')}</li>
                            <li><span class="param-label">Children at Home:</span> {"Yes" if prefs.get('has_children') else "No"}</li>
                            <li><span class="param-label">Noise Tolerance:</span> {prefs.get('noise_tolerance', 'N/A')}</li>
                        </ul>
                    </div>

                    <div class="results-list">
                        <h4>Top 10 Breed Matches:</h4>
                        <div class="breed-list">
                """

                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"""
                            <div class="breed-item">
                                <div class="breed-info">
                                    <span class="breed-rank">#{i}</span>
                                    <span class="breed-name">{breed_name}</span>
                                    <span class="breed-score">{score*100:.1f}%</span>
                                </div>
                            </div>
                        """

                html += """
                        </div>
                    </div>
                </div>
                """

            html += "</div>"
            return html

        except Exception as e:
            print(f"Error formatting history: {str(e)}")
            print(traceback.format_exc())
            return f"""
            <div style='text-align: center; padding: 20px; color: #dc2626;'>
                Error formatting history. Please try refreshing the page.
                <br>Error details: {str(e)}
            </div>
            """

    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: dict, results: list) -> bool:
        """保存搜索結果"""
        return self.history_manager.save_history(user_preferences, results)

def create_history_component():
    """只创建历史组件实例,不创建UI"""
    return SearchHistoryComponent()

def create_history_tab(history_component: SearchHistoryComponent):
    """创建历史记录标签页

    Args:
        history_component: 已创建的历史组件实例
    """
    with gr.TabItem("Recommendation Search History"):
        gr.HTML("""
        <div style='text-align: center; padding: 20px;'>
            <h3 style='color: #2D3748; margin-bottom: 10px;'>Search History</h3>
            <p style='color: #4A5568;'>View your previous breed recommendations and search preferences</p>
        </div>
        """)

        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"
                )