File size: 10,805 Bytes
c82d44a
7eaf3d5
56014c2
984ba7f
7eaf3d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import sqlite3
import gradio as gr
from dog_database import get_dog_description, dog_data
from scoring_calculation_system import UserPreferences, calculate_compatibility_score
from recommendation_html_format import format_recommendation_html, get_breed_recommendations
from smart_breed_matcher import SmartBreedMatcher
from description_search_ui import create_description_search_tab

def create_recommendation_tab(UserPreferences, get_breed_recommendations, format_recommendation_html, history_component):

    with gr.TabItem("Breed Recommendation"):
        with gr.Tabs():
            with gr.Tab("Find by Criteria"):
                gr.HTML("<p style='text-align: center;'>Tell us about your lifestyle, and we'll recommend the perfect dog breeds for you!</p>")

                with gr.Row():
                    with gr.Column():
                        living_space = gr.Radio(
                            choices=["apartment", "house_small", "house_large"],
                            label="What type of living space do you have?",
                            info="Choose your current living situation",
                            value="apartment"
                        )

                        exercise_time = gr.Slider(
                            minimum=0,
                            maximum=180,
                            value=60,
                            label="Daily exercise time (minutes)",
                            info="Consider walks, play time, and training"
                        )

                        grooming_commitment = gr.Radio(
                            choices=["low", "medium", "high"],
                            label="Grooming commitment level",
                            info="Low: monthly, Medium: weekly, High: daily",
                            value="medium"
                        )

                    with gr.Column():
                        experience_level = gr.Radio(
                            choices=["beginner", "intermediate", "advanced"],
                            label="Dog ownership experience",
                            info="Be honest - this helps find the right match",
                            value="beginner"
                        )

                        has_children = gr.Checkbox(
                            label="Have children at home",
                            info="Helps recommend child-friendly breeds"
                        )

                        noise_tolerance = gr.Radio(
                            choices=["low", "medium", "high"],
                            label="Noise tolerance level",
                            info="Some breeds are more vocal than others",
                            value="medium"
                        )

                get_recommendations_btn = gr.Button("Find My Perfect Match! 🔍", variant="primary")
                recommendation_output = gr.HTML(label="Breed Recommendations")

            with gr.Tab("Find by Description"):
                description_input, description_search_btn, description_output = create_description_search_tab()
    
        def on_find_match_click(*args):
            try:
                user_prefs = UserPreferences(
                    living_space=args[0],
                    exercise_time=args[1],
                    grooming_commitment=args[2],
                    experience_level=args[3],
                    has_children=args[4],
                    noise_tolerance=args[5],
                    space_for_play=True if args[0] != "apartment" else False,
                    other_pets=False,
                    climate="moderate",
                    health_sensitivity="medium",  # 新增: 默認中等敏感度
                    barking_acceptance=args[5]    # 使用 noise_tolerance 作為 barking_acceptance
                )

                recommendations = get_breed_recommendations(user_prefs, top_n=10)

                history_results = [{
                    'breed': rec['breed'],
                    'rank': rec['rank'],
                    'overall_score': rec['final_score'],
                    'base_score': rec['base_score'],
                    'bonus_score': rec['bonus_score'],
                    'scores': rec['scores']
                } for rec in recommendations]

                # 保存到歷史記錄,也需要更新保存的偏好設定
                history_component.save_search(
                    user_preferences={
                        'living_space': args[0],
                        'exercise_time': args[1],
                        'grooming_commitment': args[2],
                        'experience_level': args[3],
                        'has_children': args[4],
                        'noise_tolerance': args[5],
                        'health_sensitivity': "medium",
                        'barking_acceptance': args[5]
                    },
                    results=history_results
                )

                return format_recommendation_html(recommendations)

            except Exception as e:
                print(f"Error in find match: {str(e)}")
                import traceback
                print(traceback.format_exc())
                return "Error getting recommendations"

        def on_description_search(description: str):
            try:
                matcher = SmartBreedMatcher(dog_data)
                breed_recommendations = matcher.match_user_preference(description, top_n=10)
                
                # 創建基本的 UserPreferences
                user_prefs = UserPreferences(
                    living_space="apartment" if "apartment" in description.lower() else "house_small",
                    exercise_time=60,
                    grooming_commitment="medium",
                    experience_level="intermediate",
                    has_children="children" in description.lower() or "kids" in description.lower(),
                    noise_tolerance="medium",
                    space_for_play=True if "yard" in description.lower() or "garden" in description.lower() else False,
                    other_pets=False,
                    climate="moderate",
                    health_sensitivity="medium",
                    barking_acceptance=None
                )

                final_recommendations = []
                
                for smart_rec in breed_recommendations:
                    breed_name = smart_rec['breed']
                    breed_info = get_dog_description(breed_name)
                    if not isinstance(breed_info, dict):
                        continue
                        
                    # 計算基礎相容性分數
                    compatibility_scores = calculate_compatibility_score(breed_info, user_prefs)
                    
                    # 最終分數計算
                    is_preferred = smart_rec.get('is_preferred', False)
                    base_score = compatibility_scores.get('overall', 0.7)
                    smart_score = smart_rec['score']
                    
                    # 根據是否為偏好品種調整分數
                    if is_preferred:
                        final_score = 0.95  # 確保最高分
                    else:
                        # 相似品種的分數計算
                        final_score = min(0.90, (base_score * 0.6 + smart_score * 0.4))
                    
                    final_recommendations.append({
                        'rank': 0,  # 稍後更新
                        'breed': breed_name,
                        'base_score': round(base_score, 4),
                        'smart_match_score': round(smart_score, 4),
                        'final_score': round(final_score, 4),
                        'scores': compatibility_scores,
                        'match_reason': smart_rec['reason'],
                        'info': breed_info,
                        'noise_info': breed_noise_info.get(breed_name, {}),
                        'health_info': breed_health_info.get(breed_name, {})
                    })
                
                # 根據final_score重新排序
                final_recommendations.sort(key=lambda x: (-x['final_score'], x['breed']))
                
                # 更新排名
                for i, rec in enumerate(final_recommendations, 1):
                    rec['rank'] = i
                
                # 驗證排序
                print("\nFinal Rankings:")
                for rec in final_recommendations:
                    print(f"#{rec['rank']} {rec['breed']}")
                    print(f"Base Score: {rec['base_score']:.4f}")
                    print(f"Smart Match Score: {rec['smart_match_score']:.4f}")
                    print(f"Final Score: {rec['final_score']:.4f}")
                    print(f"Reason: {rec['match_reason']}\n")
                    
                    # 確保分數按降序排列
                    if rec['rank'] > 1:
                        prev_score = final_recommendations[rec['rank']-2]['final_score']
                        if rec['final_score'] > prev_score:
                            print(f"Warning: Ranking inconsistency detected!")
                            print(f"#{rec['rank']-1} score: {prev_score:.4f}")
                            print(f"#{rec['rank']} score: {rec['final_score']:.4f}")
                
                return format_recommendation_html(final_recommendations)
                
            except Exception as e:
                print(f"Error in description search: {str(e)}")
                import traceback
                print(traceback.format_exc())
                return "Error processing your description"


        get_recommendations_btn.click(
            fn=on_find_match_click,
            inputs=[
                living_space,
                exercise_time,
                grooming_commitment,
                experience_level,
                has_children,
                noise_tolerance
            ],
            outputs=recommendation_output
        )

        description_search_btn.click(
            fn=on_description_search,
            inputs=[description_input],
            outputs=[description_output]
        )

    return {
        'living_space': living_space,
        'exercise_time': exercise_time,
        'grooming_commitment': grooming_commitment,
        'experience_level': experience_level,
        'has_children': has_children,
        'noise_tolerance': noise_tolerance,
        'get_recommendations_btn': get_recommendations_btn,
        'recommendation_output': recommendation_output,
        'description_input': description_input,
        'description_search_btn': description_search_btn,
        'description_output': description_output
    }