DawnC commited on
Commit
c58a9f5
1 Parent(s): 3e53bf9

Delete breed_recommendation.py

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