DawnC commited on
Commit
450e465
·
1 Parent(s): 5493f62

Delete breed_recommendation.py

Browse files
Files changed (1) hide show
  1. breed_recommendation.py +0 -256
breed_recommendation.py DELETED
@@ -1,256 +0,0 @@
1
- import sqlite3
2
- import gradio as gr
3
- from dog_database import get_dog_description, dog_data
4
- from breed_health_info import breed_health_info
5
- from breed_noise_info import breed_noise_info
6
- from scoring_calculation_system import UserPreferences, calculate_compatibility_score
7
- from recommendation_html_format import format_recommendation_html, get_breed_recommendations
8
- from smart_breed_matcher import SmartBreedMatcher
9
- from description_search_ui import create_description_search_tab
10
-
11
- def create_recommendation_tab(UserPreferences, get_breed_recommendations, format_recommendation_html, history_component):
12
-
13
- with gr.TabItem("Breed Recommendation"):
14
- with gr.Tabs():
15
- with gr.Tab("Find by Criteria"):
16
- gr.HTML("<p style='text-align: center;'>Tell us about your lifestyle, and we'll recommend the perfect dog breeds for you!</p>")
17
-
18
- with gr.Row():
19
- with gr.Column():
20
- living_space = gr.Radio(
21
- choices=["apartment", "house_small", "house_large"],
22
- label="What type of living space do you have?",
23
- info="Choose your current living situation",
24
- value="apartment"
25
- )
26
-
27
- exercise_time = gr.Slider(
28
- minimum=0,
29
- maximum=180,
30
- value=60,
31
- label="Daily exercise time (minutes)",
32
- info="Consider walks, play time, and training"
33
- )
34
-
35
- grooming_commitment = gr.Radio(
36
- choices=["low", "medium", "high"],
37
- label="Grooming commitment level",
38
- info="Low: monthly, Medium: weekly, High: daily",
39
- value="medium"
40
- )
41
-
42
- with gr.Column():
43
- experience_level = gr.Radio(
44
- choices=["beginner", "intermediate", "advanced"],
45
- label="Dog ownership experience",
46
- info="Be honest - this helps find the right match",
47
- value="beginner"
48
- )
49
-
50
- has_children = gr.Checkbox(
51
- label="Have children at home",
52
- info="Helps recommend child-friendly breeds"
53
- )
54
-
55
- noise_tolerance = gr.Radio(
56
- choices=["low", "medium", "high"],
57
- label="Noise tolerance level",
58
- info="Some breeds are more vocal than others",
59
- value="medium"
60
- )
61
-
62
- get_recommendations_btn = gr.Button("Find My Perfect Match! 🔍", variant="primary")
63
- recommendation_output = gr.HTML(label="Breed Recommendations")
64
-
65
- with gr.Tab("Find by Description"):
66
- description_input, description_search_btn, description_output, loading_msg = create_description_search_tab()
67
-
68
-
69
- def on_find_match_click(*args):
70
- try:
71
- user_prefs = UserPreferences(
72
- living_space=args[0],
73
- exercise_time=args[1],
74
- grooming_commitment=args[2],
75
- experience_level=args[3],
76
- has_children=args[4],
77
- noise_tolerance=args[5],
78
- space_for_play=True if args[0] != "apartment" else False,
79
- other_pets=False,
80
- climate="moderate",
81
- health_sensitivity="medium", # 新增: 默認中等敏感度
82
- barking_acceptance=args[5] # 使用 noise_tolerance 作為 barking_acceptance
83
- )
84
-
85
- recommendations = get_breed_recommendations(user_prefs, top_n=10)
86
-
87
- history_results = [{
88
- 'breed': rec['breed'],
89
- 'rank': rec['rank'],
90
- 'overall_score': rec['final_score'],
91
- 'base_score': rec['base_score'],
92
- 'bonus_score': rec['bonus_score'],
93
- 'scores': rec['scores']
94
- } for rec in recommendations]
95
-
96
- # 保存到歷史記錄,也需要更新保存的偏好設定
97
- history_component.save_search(
98
- user_preferences={
99
- 'living_space': args[0],
100
- 'exercise_time': args[1],
101
- 'grooming_commitment': args[2],
102
- 'experience_level': args[3],
103
- 'has_children': args[4],
104
- 'noise_tolerance': args[5],
105
- 'health_sensitivity': "medium",
106
- 'barking_acceptance': args[5]
107
- },
108
- results=history_results
109
- )
110
-
111
- return format_recommendation_html(recommendations)
112
-
113
- except Exception as e:
114
- print(f"Error in find match: {str(e)}")
115
- import traceback
116
- print(traceback.format_exc())
117
- return "Error getting recommendations"
118
-
119
- def on_description_search(description: str):
120
- try:
121
- matcher = SmartBreedMatcher(dog_data)
122
- breed_recommendations = matcher.match_user_preference(description, top_n=10)
123
-
124
- print("Creating user preferences...")
125
- user_prefs = UserPreferences(
126
- living_space="apartment" if "apartment" in description.lower() else "house_small",
127
- exercise_time=60,
128
- grooming_commitment="medium",
129
- experience_level="intermediate",
130
- has_children="children" in description.lower() or "kids" in description.lower(),
131
- noise_tolerance="medium",
132
- space_for_play=True if "yard" in description.lower() or "garden" in description.lower() else False,
133
- other_pets=False,
134
- climate="moderate",
135
- health_sensitivity="medium",
136
- barking_acceptance=None
137
- )
138
-
139
- final_recommendations = []
140
-
141
- for smart_rec in breed_recommendations:
142
- breed_name = smart_rec['breed']
143
- breed_info = get_dog_description(breed_name)
144
- if not isinstance(breed_info, dict):
145
- continue
146
-
147
- # 計算基礎相容性分數
148
- compatibility_scores = calculate_compatibility_score(breed_info, user_prefs)
149
-
150
- bonus_reasons = []
151
- bonus_score = 0
152
- is_preferred = smart_rec.get('is_preferred', False)
153
- similarity = smart_rec.get('similarity', 0)
154
-
155
- # 用戶直接提到的品種
156
- if is_preferred:
157
- bonus_score = 0.15 # 15% bonus
158
- bonus_reasons.append("Directly mentioned breed (+15%)")
159
- # 高相似度品種
160
- elif similarity > 0.8:
161
- bonus_score = 0.10 # 10% bonus
162
- bonus_reasons.append("Very similar to preferred breed (+10%)")
163
- # 中等相似度品種
164
- elif similarity > 0.6:
165
- bonus_score = 0.05 # 5% bonus
166
- bonus_reasons.append("Similar to preferred breed (+5%)")
167
-
168
- # 基於品種特性的額外加分
169
- temperament = breed_info.get('Temperament', '').lower()
170
- if any(trait in temperament for trait in ['friendly', 'gentle', 'affectionate']):
171
- bonus_score += 0.02 # 2% bonus
172
- bonus_reasons.append("Positive temperament traits (+2%)")
173
-
174
- if breed_info.get('Good with Children') == 'Yes' and user_prefs.has_children:
175
- bonus_score += 0.03 # 3% bonus
176
- bonus_reasons.append("Excellent with children (+3%)")
177
-
178
- # 基礎分數和最終分數計算
179
- base_score = compatibility_scores.get('overall', 0.7)
180
- final_score = min(0.95, base_score + bonus_score) # 確保不超過95%
181
-
182
- final_recommendations.append({
183
- 'rank': 0,
184
- 'breed': breed_name,
185
- 'base_score': round(base_score, 4),
186
- 'bonus_score': round(bonus_score, 4),
187
- 'final_score': round(final_score, 4),
188
- 'scores': compatibility_scores,
189
- 'match_reason': ' • '.join(bonus_reasons) if bonus_reasons else "Standard match",
190
- 'info': breed_info,
191
- 'noise_info': breed_noise_info.get(breed_name, {}),
192
- 'health_info': breed_health_info.get(breed_name, {})
193
- })
194
-
195
- # 根據最終分數排序
196
- final_recommendations.sort(key=lambda x: (-x['final_score'], x['breed']))
197
-
198
- # 更新排名
199
- for i, rec in enumerate(final_recommendations, 1):
200
- rec['rank'] = i
201
-
202
- # 驗證排序
203
- print("\nFinal Rankings:")
204
- for rec in final_recommendations:
205
- print(f"#{rec['rank']} {rec['breed']}")
206
- print(f"Base Score: {rec['base_score']:.4f}")
207
- print(f"Bonus Score: {rec['bonus_score']:.4f}")
208
- print(f"Final Score: {rec['final_score']:.4f}")
209
- print(f"Reason: {rec['match_reason']}\n")
210
-
211
- result = format_recommendation_html(final_recommendations)
212
- return [gr.update(value=result), gr.update(visible=False)]
213
-
214
- except Exception as e:
215
- error_msg = f"Error processing your description. Details: {str(e)}"
216
- return [gr.update(value=error_msg), gr.update(visible=False)]
217
-
218
- def show_loading():
219
- return [gr.update(value=""), gr.update(visible=True)]
220
-
221
-
222
- get_recommendations_btn.click(
223
- fn=on_find_match_click,
224
- inputs=[
225
- living_space,
226
- exercise_time,
227
- grooming_commitment,
228
- experience_level,
229
- has_children,
230
- noise_tolerance
231
- ],
232
- outputs=recommendation_output
233
- )
234
-
235
- description_search_btn.click(
236
- fn=show_loading, # 先顯示加載消息
237
- outputs=[description_output, loading_msg]
238
- ).then( # 然後執行搜索
239
- fn=on_description_search,
240
- inputs=[description_input],
241
- outputs=[description_output, loading_msg]
242
- )
243
-
244
- return {
245
- 'living_space': living_space,
246
- 'exercise_time': exercise_time,
247
- 'grooming_commitment': grooming_commitment,
248
- 'experience_level': experience_level,
249
- 'has_children': has_children,
250
- 'noise_tolerance': noise_tolerance,
251
- 'get_recommendations_btn': get_recommendations_btn,
252
- 'recommendation_output': recommendation_output,
253
- 'description_input': description_input,
254
- 'description_search_btn': description_search_btn,
255
- 'description_output': description_output
256
- }