Spaces:
Running
on
Zero
Running
on
Zero
Upload 5 files
Browse files- animal_detector.db +0 -0
- breed_recommendation.py +234 -0
- description_search_ui.py +154 -0
- dog_database.py +221 -0
- smart_breed_matcher.py +365 -0
animal_detector.db
ADDED
Binary file (94.2 kB). View file
|
|
breed_recommendation.py
ADDED
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import gradio as gr
|
3 |
+
from recommendation_html_format import format_recommendation_html, get_breed_recommendations
|
4 |
+
from smart_breed_matcher import SmartBreedMatcher
|
5 |
+
from description_search_ui import create_description_search_tab
|
6 |
+
|
7 |
+
def create_recommendation_tab(UserPreferences, get_breed_recommendations, format_recommendation_html, history_component):
|
8 |
+
|
9 |
+
with gr.TabItem("Breed Recommendation"):
|
10 |
+
with gr.Tabs():
|
11 |
+
with gr.Tab("Find by Criteria"):
|
12 |
+
gr.HTML("<p style='text-align: center;'>Tell us about your lifestyle, and we'll recommend the perfect dog breeds for you!</p>")
|
13 |
+
|
14 |
+
with gr.Row():
|
15 |
+
with gr.Column():
|
16 |
+
living_space = gr.Radio(
|
17 |
+
choices=["apartment", "house_small", "house_large"],
|
18 |
+
label="What type of living space do you have?",
|
19 |
+
info="Choose your current living situation",
|
20 |
+
value="apartment"
|
21 |
+
)
|
22 |
+
|
23 |
+
exercise_time = gr.Slider(
|
24 |
+
minimum=0,
|
25 |
+
maximum=180,
|
26 |
+
value=60,
|
27 |
+
label="Daily exercise time (minutes)",
|
28 |
+
info="Consider walks, play time, and training"
|
29 |
+
)
|
30 |
+
|
31 |
+
grooming_commitment = gr.Radio(
|
32 |
+
choices=["low", "medium", "high"],
|
33 |
+
label="Grooming commitment level",
|
34 |
+
info="Low: monthly, Medium: weekly, High: daily",
|
35 |
+
value="medium"
|
36 |
+
)
|
37 |
+
|
38 |
+
with gr.Column():
|
39 |
+
experience_level = gr.Radio(
|
40 |
+
choices=["beginner", "intermediate", "advanced"],
|
41 |
+
label="Dog ownership experience",
|
42 |
+
info="Be honest - this helps find the right match",
|
43 |
+
value="beginner"
|
44 |
+
)
|
45 |
+
|
46 |
+
has_children = gr.Checkbox(
|
47 |
+
label="Have children at home",
|
48 |
+
info="Helps recommend child-friendly breeds"
|
49 |
+
)
|
50 |
+
|
51 |
+
noise_tolerance = gr.Radio(
|
52 |
+
choices=["low", "medium", "high"],
|
53 |
+
label="Noise tolerance level",
|
54 |
+
info="Some breeds are more vocal than others",
|
55 |
+
value="medium"
|
56 |
+
)
|
57 |
+
|
58 |
+
get_recommendations_btn = gr.Button("Find My Perfect Match! 🔍", variant="primary")
|
59 |
+
recommendation_output = gr.HTML(label="Breed Recommendations")
|
60 |
+
|
61 |
+
with gr.Tab("Find by Description"):
|
62 |
+
description_input, description_search_btn, description_output = create_description_search_tab()
|
63 |
+
|
64 |
+
def on_find_match_click(*args):
|
65 |
+
try:
|
66 |
+
user_prefs = UserPreferences(
|
67 |
+
living_space=args[0],
|
68 |
+
exercise_time=args[1],
|
69 |
+
grooming_commitment=args[2],
|
70 |
+
experience_level=args[3],
|
71 |
+
has_children=args[4],
|
72 |
+
noise_tolerance=args[5],
|
73 |
+
space_for_play=True if args[0] != "apartment" else False,
|
74 |
+
other_pets=False,
|
75 |
+
climate="moderate",
|
76 |
+
health_sensitivity="medium", # 新增: 默認中等敏感度
|
77 |
+
barking_acceptance=args[5] # 使用 noise_tolerance 作為 barking_acceptance
|
78 |
+
)
|
79 |
+
|
80 |
+
recommendations = get_breed_recommendations(user_prefs, top_n=10)
|
81 |
+
|
82 |
+
history_results = [{
|
83 |
+
'breed': rec['breed'],
|
84 |
+
'rank': rec['rank'],
|
85 |
+
'overall_score': rec['final_score'],
|
86 |
+
'base_score': rec['base_score'],
|
87 |
+
'bonus_score': rec['bonus_score'],
|
88 |
+
'scores': rec['scores']
|
89 |
+
} for rec in recommendations]
|
90 |
+
|
91 |
+
# 保存到歷史記錄,也需要更新保存的偏好設定
|
92 |
+
history_component.save_search(
|
93 |
+
user_preferences={
|
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 |
+
'health_sensitivity': "medium",
|
101 |
+
'barking_acceptance': args[5]
|
102 |
+
},
|
103 |
+
results=history_results
|
104 |
+
)
|
105 |
+
|
106 |
+
return format_recommendation_html(recommendations)
|
107 |
+
|
108 |
+
except Exception as e:
|
109 |
+
print(f"Error in find match: {str(e)}")
|
110 |
+
import traceback
|
111 |
+
print(traceback.format_exc())
|
112 |
+
return "Error getting recommendations"
|
113 |
+
|
114 |
+
def on_description_search(description: str):
|
115 |
+
try:
|
116 |
+
matcher = SmartBreedMatcher(dog_data)
|
117 |
+
breed_recommendations = matcher.match_user_preference(description, top_n=10)
|
118 |
+
|
119 |
+
# 創建基本的 UserPreferences
|
120 |
+
user_prefs = UserPreferences(
|
121 |
+
living_space="apartment" if "apartment" in description.lower() else "house_small",
|
122 |
+
exercise_time=60,
|
123 |
+
grooming_commitment="medium",
|
124 |
+
experience_level="intermediate",
|
125 |
+
has_children="children" in description.lower() or "kids" in description.lower(),
|
126 |
+
noise_tolerance="medium",
|
127 |
+
space_for_play=True if "yard" in description.lower() or "garden" in description.lower() else False,
|
128 |
+
other_pets=False,
|
129 |
+
climate="moderate",
|
130 |
+
health_sensitivity="medium",
|
131 |
+
barking_acceptance=None
|
132 |
+
)
|
133 |
+
|
134 |
+
final_recommendations = []
|
135 |
+
|
136 |
+
for smart_rec in breed_recommendations:
|
137 |
+
breed_name = smart_rec['breed']
|
138 |
+
breed_info = get_dog_description(breed_name)
|
139 |
+
if not isinstance(breed_info, dict):
|
140 |
+
continue
|
141 |
+
|
142 |
+
# 計算基礎相容性分數
|
143 |
+
compatibility_scores = calculate_compatibility_score(breed_info, user_prefs)
|
144 |
+
|
145 |
+
# 最終分數計算
|
146 |
+
is_preferred = smart_rec.get('is_preferred', False)
|
147 |
+
base_score = compatibility_scores.get('overall', 0.7)
|
148 |
+
smart_score = smart_rec['score']
|
149 |
+
|
150 |
+
# 根據是否為偏好品種調整分數
|
151 |
+
if is_preferred:
|
152 |
+
final_score = 0.95 # 確保最高分
|
153 |
+
else:
|
154 |
+
# 相似品種的分數計算
|
155 |
+
final_score = min(0.90, (base_score * 0.6 + smart_score * 0.4))
|
156 |
+
|
157 |
+
final_recommendations.append({
|
158 |
+
'rank': 0, # 稍後更新
|
159 |
+
'breed': breed_name,
|
160 |
+
'base_score': round(base_score, 4),
|
161 |
+
'smart_match_score': round(smart_score, 4),
|
162 |
+
'final_score': round(final_score, 4),
|
163 |
+
'scores': compatibility_scores,
|
164 |
+
'match_reason': smart_rec['reason'],
|
165 |
+
'info': breed_info,
|
166 |
+
'noise_info': breed_noise_info.get(breed_name, {}),
|
167 |
+
'health_info': breed_health_info.get(breed_name, {})
|
168 |
+
})
|
169 |
+
|
170 |
+
# 根據final_score重新排序
|
171 |
+
final_recommendations.sort(key=lambda x: (-x['final_score'], x['breed']))
|
172 |
+
|
173 |
+
# 更新排名
|
174 |
+
for i, rec in enumerate(final_recommendations, 1):
|
175 |
+
rec['rank'] = i
|
176 |
+
|
177 |
+
# 驗證排序
|
178 |
+
print("\nFinal Rankings:")
|
179 |
+
for rec in final_recommendations:
|
180 |
+
print(f"#{rec['rank']} {rec['breed']}")
|
181 |
+
print(f"Base Score: {rec['base_score']:.4f}")
|
182 |
+
print(f"Smart Match Score: {rec['smart_match_score']:.4f}")
|
183 |
+
print(f"Final Score: {rec['final_score']:.4f}")
|
184 |
+
print(f"Reason: {rec['match_reason']}\n")
|
185 |
+
|
186 |
+
# 確保分數按降序排列
|
187 |
+
if rec['rank'] > 1:
|
188 |
+
prev_score = final_recommendations[rec['rank']-2]['final_score']
|
189 |
+
if rec['final_score'] > prev_score:
|
190 |
+
print(f"Warning: Ranking inconsistency detected!")
|
191 |
+
print(f"#{rec['rank']-1} score: {prev_score:.4f}")
|
192 |
+
print(f"#{rec['rank']} score: {rec['final_score']:.4f}")
|
193 |
+
|
194 |
+
return format_recommendation_html(final_recommendations)
|
195 |
+
|
196 |
+
except Exception as e:
|
197 |
+
print(f"Error in description search: {str(e)}")
|
198 |
+
import traceback
|
199 |
+
print(traceback.format_exc())
|
200 |
+
return "Error processing your description"
|
201 |
+
|
202 |
+
|
203 |
+
get_recommendations_btn.click(
|
204 |
+
fn=on_find_match_click,
|
205 |
+
inputs=[
|
206 |
+
living_space,
|
207 |
+
exercise_time,
|
208 |
+
grooming_commitment,
|
209 |
+
experience_level,
|
210 |
+
has_children,
|
211 |
+
noise_tolerance
|
212 |
+
],
|
213 |
+
outputs=recommendation_output
|
214 |
+
)
|
215 |
+
|
216 |
+
description_search_btn.click(
|
217 |
+
fn=on_description_search,
|
218 |
+
inputs=[description_input],
|
219 |
+
outputs=[description_output]
|
220 |
+
)
|
221 |
+
|
222 |
+
return {
|
223 |
+
'living_space': living_space,
|
224 |
+
'exercise_time': exercise_time,
|
225 |
+
'grooming_commitment': grooming_commitment,
|
226 |
+
'experience_level': experience_level,
|
227 |
+
'has_children': has_children,
|
228 |
+
'noise_tolerance': noise_tolerance,
|
229 |
+
'get_recommendations_btn': get_recommendations_btn,
|
230 |
+
'recommendation_output': recommendation_output,
|
231 |
+
'description_input': description_input,
|
232 |
+
'description_search_btn': description_search_btn,
|
233 |
+
'description_output': description_output
|
234 |
+
}
|
description_search_ui.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import gradio as gr
|
3 |
+
|
4 |
+
def create_description_search_tab() -> gr.Column:
|
5 |
+
"""創建描述搜索頁面的UI組件"""
|
6 |
+
guide_html = """
|
7 |
+
<div class="breed-search-container">
|
8 |
+
<div class="description-guide">
|
9 |
+
<h2 class="guide-title">🐾 Describe Your Ideal Dog</h2>
|
10 |
+
|
11 |
+
<div class="guide-content">
|
12 |
+
<p class="intro-text">Help us find your perfect companion! Please consider including the following details:</p>
|
13 |
+
|
14 |
+
<div class="criteria-grid">
|
15 |
+
<div class="criteria-item">
|
16 |
+
<span class="icon">📏</span>
|
17 |
+
<div class="criteria-content">
|
18 |
+
<h3>Size Preference</h3>
|
19 |
+
<p>Small • Medium • Large</p>
|
20 |
+
</div>
|
21 |
+
</div>
|
22 |
+
|
23 |
+
<div class="criteria-item">
|
24 |
+
<span class="icon">🏃</span>
|
25 |
+
<div class="criteria-content">
|
26 |
+
<h3>Activity Level</h3>
|
27 |
+
<p>Low • Moderate • High • Very Active</p>
|
28 |
+
</div>
|
29 |
+
</div>
|
30 |
+
|
31 |
+
<div class="criteria-item">
|
32 |
+
<span class="icon">🏠</span>
|
33 |
+
<div class="criteria-content">
|
34 |
+
<h3>Living Environment</h3>
|
35 |
+
<p>Apartment • House • Yard Space</p>
|
36 |
+
</div>
|
37 |
+
</div>
|
38 |
+
|
39 |
+
<div class="criteria-item">
|
40 |
+
<span class="icon">👨👩👧👦</span>
|
41 |
+
<div class="criteria-content">
|
42 |
+
<h3>Family Situation</h3>
|
43 |
+
<p>Children • Other Pets • Single Adult</p>
|
44 |
+
</div>
|
45 |
+
</div>
|
46 |
+
|
47 |
+
<div class="criteria-item">
|
48 |
+
<span class="icon">✂️</span>
|
49 |
+
<div class="criteria-content">
|
50 |
+
<h3>Grooming Commitment</h3>
|
51 |
+
<p>Low • Medium • High Maintenance</p>
|
52 |
+
</div>
|
53 |
+
</div>
|
54 |
+
|
55 |
+
<div class="criteria-item">
|
56 |
+
<span class="icon">🎭</span>
|
57 |
+
<div class="criteria-content">
|
58 |
+
<h3>Desired Personality</h3>
|
59 |
+
<p>Friendly • Independent • Intelligent • Calm</p>
|
60 |
+
</div>
|
61 |
+
</div>
|
62 |
+
</div>
|
63 |
+
</div>
|
64 |
+
</div>
|
65 |
+
</div>
|
66 |
+
"""
|
67 |
+
|
68 |
+
# 添加CSS樣式
|
69 |
+
css = """
|
70 |
+
<style>
|
71 |
+
.breed-search-container {
|
72 |
+
background: white;
|
73 |
+
border-radius: 12px;
|
74 |
+
padding: 24px;
|
75 |
+
margin-bottom: 20px;
|
76 |
+
}
|
77 |
+
|
78 |
+
.guide-title {
|
79 |
+
font-size: 1.8rem;
|
80 |
+
color: #2c3e50;
|
81 |
+
margin-bottom: 20px;
|
82 |
+
text-align: center;
|
83 |
+
}
|
84 |
+
|
85 |
+
.intro-text {
|
86 |
+
color: #666;
|
87 |
+
text-align: center;
|
88 |
+
margin-bottom: 24px;
|
89 |
+
font-size: 1.1rem;
|
90 |
+
}
|
91 |
+
|
92 |
+
.criteria-grid {
|
93 |
+
display: grid;
|
94 |
+
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
95 |
+
gap: 20px;
|
96 |
+
margin-bottom: 24px;
|
97 |
+
}
|
98 |
+
|
99 |
+
.criteria-item {
|
100 |
+
display: flex;
|
101 |
+
align-items: flex-start;
|
102 |
+
padding: 16px;
|
103 |
+
background: #f8fafc;
|
104 |
+
border-radius: 8px;
|
105 |
+
transition: all 0.3s ease;
|
106 |
+
}
|
107 |
+
|
108 |
+
.criteria-item:hover {
|
109 |
+
transform: translateY(-2px);
|
110 |
+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
|
111 |
+
}
|
112 |
+
|
113 |
+
.criteria-item .icon {
|
114 |
+
font-size: 24px;
|
115 |
+
margin-right: 12px;
|
116 |
+
margin-top: 3px;
|
117 |
+
}
|
118 |
+
|
119 |
+
.criteria-content h3 {
|
120 |
+
font-size: 1.1rem;
|
121 |
+
color: #2c3e50;
|
122 |
+
margin: 0 0 4px 0;
|
123 |
+
}
|
124 |
+
|
125 |
+
.criteria-content p {
|
126 |
+
color: #666;
|
127 |
+
margin: 0;
|
128 |
+
font-size: 0.95rem;
|
129 |
+
}
|
130 |
+
</style>
|
131 |
+
"""
|
132 |
+
|
133 |
+
with gr.Column():
|
134 |
+
# 顯示指南和樣式
|
135 |
+
gr.HTML(css + guide_html)
|
136 |
+
|
137 |
+
# 描述輸入區
|
138 |
+
description_input = gr.Textbox(
|
139 |
+
label="",
|
140 |
+
placeholder="Example: I'm looking for a medium-sized, friendly dog that's good with kids. I live in an apartment and can provide moderate exercise. Looking for an intelligent breed that's easy to train...",
|
141 |
+
lines=5
|
142 |
+
)
|
143 |
+
|
144 |
+
# 搜索按鈕(使用 Gradio 默認顏色)
|
145 |
+
search_button = gr.Button(
|
146 |
+
"Find My Perfect Match! 🔍",
|
147 |
+
variant="primary",
|
148 |
+
size="lg"
|
149 |
+
)
|
150 |
+
|
151 |
+
# 結果顯示區域
|
152 |
+
result_output = gr.HTML(label="Breed Recommendations")
|
153 |
+
|
154 |
+
return description_input, search_button, result_output
|
dog_database.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import sqlite3
|
3 |
+
from dataclasses import dataclass
|
4 |
+
from typing import List, Dict, Optional
|
5 |
+
from decimal import Decimal
|
6 |
+
from breed_health_info import breed_health_info, default_health_note
|
7 |
+
from breed_noise_info import breed_noise_info
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
|
11 |
+
def create_table():
|
12 |
+
conn = sqlite3.connect('animal_detector.db')
|
13 |
+
cursor = conn.cursor()
|
14 |
+
|
15 |
+
cursor.execute('''
|
16 |
+
CREATE TABLE IF NOT EXISTS AnimalCatalog (
|
17 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
18 |
+
Species TEXT NOT NULL,
|
19 |
+
Breed TEXT NOT NULL,
|
20 |
+
Size_Category TEXT,
|
21 |
+
Typical_Lifespan TEXT,
|
22 |
+
Temperament TEXT,
|
23 |
+
Care_Level TEXT,
|
24 |
+
Good_With_Children BOOLEAN,
|
25 |
+
Exercise_Needs TEXT,
|
26 |
+
Grooming_Needs TEXT,
|
27 |
+
Brief_Description TEXT
|
28 |
+
)
|
29 |
+
''')
|
30 |
+
|
31 |
+
conn.commit()
|
32 |
+
cursor.close()
|
33 |
+
conn.close()
|
34 |
+
|
35 |
+
# 創建表
|
36 |
+
create_table()
|
37 |
+
|
38 |
+
dog_data = [
|
39 |
+
('Dog', 'Afghan_Hound', 'Large', '12-18 years', 'Independent, dignified, aloof', 'High', True, 'High', 'High', 'Ancient sighthounds known for their aristocratic bearing and spectacular flowing coat. Their combination of speed, agility and distinctive appearance makes them unique among hounds.'),
|
40 |
+
('Dog', 'African_Hunting_Dog', 'Medium', '10-12 years', 'Social, intelligent, energetic', 'Very High', False, 'Very High', 'Low', 'These highly social wild canids are master hunters with distinctive mottled coats. Their complex pack behavior and hunting strategies make them fascinating but unsuitable as pets.'),
|
41 |
+
('Dog', 'Airedale', 'Large', '10-12 years', 'Friendly, clever, courageous', 'High', True, 'High', 'High', 'Known as the "King of Terriers," Airedales are the largest of the terrier breeds and very versatile. Originally from Aire Valley of Yorkshire, they served in police and military roles while maintaining their hunting abilities.'),
|
42 |
+
('Dog', 'American_Staffordshire_Terrier', 'Medium', '12-16 years', 'Confident, good-natured, courageous', 'Moderate', True, 'High', 'Low', 'These muscular terriers blend strength with agility and good nature. Despite their powerful build, they are known for their reliability and affection, particularly with children.'),
|
43 |
+
('Dog', 'Appenzeller', 'Medium', '12-15 years', 'Reliable, fearless, lively', 'High', True, 'High', 'Moderate', 'Swiss mountain dogs known for their agility and enthusiasm, Appenzellers make excellent working and family dogs. Traditional cattle herders from the Swiss Alps, they combine working intelligence with devoted guardianship.'),
|
44 |
+
('Dog', 'Australian_Terrier', 'Small', '12-15 years', 'Courageous, spirited, alert', 'Moderate', True, 'Moderate', 'Moderate', 'Small, sturdy terriers originally bred to control rodents, known for their confident personality. First breed developed in Australia, combining the tenacity of old terrier breeds with adaptability to harsh conditions.'),
|
45 |
+
('Dog', 'Bedlington_Terrier', 'Medium', '11-16 years', 'Mild, gentle, lively', 'High', True, 'Moderate', 'High', 'Known for their lamb-like appearance, Bedlington Terriers are energetic and good with families. Despite their gentle look, they were originally miners\' dogs bred for hunting vermin and remain surprisingly fast and athletic.'),
|
46 |
+
('Dog', 'Bernese_Mountain_Dog', 'Large', '6-8 years', 'Good-natured, calm, strong', 'High', True, 'Moderate', 'High', 'Large, tri-colored Swiss working dogs known for their gentle nature and striking appearance. Despite their short lifespan, they are excellent family companions and draft dogs. Often called "Berners", they are patient with children but prone to heat sensitivity due to their thick coat.'),
|
47 |
+
('Dog', 'Bichon_Frise', 'Small', '12-15 years', 'Playful, gentle, affectionate', 'Moderate', True, 'Moderate', 'High', 'Cheerful white powder puffs with playful personalities. Originally bred as companion dogs, Bichon Frises are known for their hypoallergenic cotton-ball coat and merry temperament, making them excellent family pets and therapy dogs.'),
|
48 |
+
('Dog', 'Blenheim_Spaniel', 'Small', '12-14 years', 'Affectionate, gentle, lively', 'Moderate', True, 'Moderate', 'High', 'A beloved variety of Cavalier King Charles Spaniel, distinguished by their pearl-white coat with chestnut markings. Their gentle expression and affectionate nature make them sought-after companions.'),
|
49 |
+
('Dog', 'Border_Collie', 'Medium', '12-15 years', 'Intelligent, energetic, alert', 'High', True, 'Very High', 'Moderate', 'Often considered the most intelligent dog breed, Border Collies are tireless workers with intense herding instincts. Known for their "eye" - a distinctive herding gaze, they excel in dog sports and need constant mental stimulation to prevent boredom.'),
|
50 |
+
('Dog', 'Border_Terrier', 'Small', '12-15 years', 'Affectionate, intelligent, even-tempered', 'Moderate', True, 'High', 'Low', 'These hardy terriers combine typical terrier toughness with unusual adaptability. Their distinctive otter-like head and game nature reflect their origins as fox-hunting companions.'),
|
51 |
+
('Dog', 'Boston_Bull', 'Small', '11-13 years', 'Friendly, lively, intelligent', 'Moderate', True, 'Moderate', 'Low', 'Also known as Boston Terriers, these "American Gentlemen" are friendly and adaptable. First bred in Boston as fighting dogs, they evolved into beloved companions known for their tuxedo-like coat pattern and gentle disposition.'),
|
52 |
+
('Dog', 'Bouvier_Des_Flandres', 'Large', '10-12 years', 'Gentle, loyal, rational', 'High', True, 'High', 'High', 'Large, powerful herding dogs with a tousled coat, known for their versatility and even temperament. Originally bred as cattle drivers in Flanders, they excel in various roles from farm work to family protection.'),
|
53 |
+
('Dog', 'Brabancon_Griffon', 'Small', '12-15 years', 'Self-important, sensitive, affectionate', 'Moderate', False, 'Moderate', 'Low', 'Also known as the Brussels Griffon, these small dogs have a distinctive beard and mustache, giving them an almost human-like expression.'),
|
54 |
+
('Dog', 'Brittany_Spaniel', 'Medium', '12-14 years', 'Bright, fun-loving, upbeat', 'High', True, 'High', 'Moderate', 'Versatile hunting dogs and active companions, Brittanys are known for their energy and intelligence. Originally from France, these agile bird dogs excel in both hunting and family life with their eager and athletic nature.'),
|
55 |
+
('Dog', 'Cardigan', 'Small', '12-15 years', 'Affectionate, loyal, intelligent', 'Moderate', True, 'Moderate', 'Moderate', 'The older of the Welsh Corgi breeds, distinguished by their long tail and larger bone structure. These capable herders combine strength and agility with devoted companionship.'),
|
56 |
+
('Dog', 'Chesapeake_Bay_Retriever', 'Large', '10-13 years', 'Bright, sensitive, affectionate', 'High', True, 'High', 'Moderate', 'Known for their waterproof coat, Chessies are strong swimmers and excellent retrievers. Developed in the American Chesapeake Bay region, they are famous for their ability to work in icy waters and their distinctive wavy coat.'),
|
57 |
+
('Dog', 'Chihuahua', 'Small', '12-20 years', 'Charming, graceful, sassy', 'Moderate', False, 'Low', 'Low', 'One of the smallest dog breeds, known for their big personalities and loyalty to their owners. Named after Mexico\'s largest state, they are ancient companions with terrier-like attitudes and remarkably long lifespans for dogs.'),
|
58 |
+
('Dog', 'Dachshund', 'Small', '12-16 years', 'Clever, stubborn, brave', 'Moderate', True, 'Moderate', 'Moderate', 'Distinctive long-bodied, short-legged dogs originally bred for hunting badgers. Despite their small size, Dachshunds are known for their bold personalities, keen sense of smell, and determined nature, making them both entertaining companions and capable watchdogs.'),
|
59 |
+
('Dog', 'Dandie_Dinmont', 'Small', '12-15 years', 'Independent, intelligent, dignified', 'Moderate', True, 'Moderate', 'Moderate', 'Recognizable by their long body and distinctive topknot of hair on their head. Named after a character in Sir Walter Scott novel, these unique terriers combine determination with dignity, making them distinctive companions.'),
|
60 |
+
('Dog', 'Doberman', 'Large', '10-12 years', 'Loyal, fearless, alert', 'High', True, 'High', 'Low', 'Sleek, athletic dogs known for their intelligence and loyalty, often used as guard dogs. Highly trainable and protective, they excel in both working roles and as family guardians.'),
|
61 |
+
('Dog', 'English_Foxhound', 'Medium', '10-13 years', 'Friendly, active, gentle', 'High', True, 'Very High', 'Low', 'Traditional pack hunters developed for British fox hunting, these athletic hounds possess remarkable endurance. Their powerful voice and strong prey drive reflect their sporting heritage.'),
|
62 |
+
('Dog', 'English_Setter', 'Large', '10-12 years', 'Gentle, friendly, placid', 'High', True, 'High', 'High', 'Distinguished by their unique speckled coat pattern, these elegant bird dogs combine athletic ability with gentle temperament. Their graceful movement and kind nature make them excellent sporting companions.'),
|
63 |
+
('Dog', 'English_Springer', 'Medium', '12-14 years', 'Friendly, playful, obedient', 'High', True, 'High', 'High', 'Energetic and eager to please, Springers are excellent hunting dogs and loving family pets. Their name comes from their hunting style of "springing" at game birds, combining strong work ethics with a merry, affectionate family nature.'),
|
64 |
+
('Dog', 'EntleBucher', 'Medium', '11-13 years', 'Loyal, enthusiastic, intelligent', 'High', True, 'High', 'Low', 'The smallest of the Swiss Mountain Dogs, known for their agility and herding abilities. Originally from the Swiss valley of Entlebuch, they combine the strength of mountain dogs with remarkable agility and quick thinking.'),
|
65 |
+
('Dog', 'Eskimo_Dog', 'Large', '10-15 years', 'Alert, loyal, intelligent', 'High', True, 'High', 'High', 'Also known as the Canadian Eskimo Dog, these are strong, resilient working dogs adapted to Arctic conditions. Ancient breed used by Inuit people for hunting and transportation, known for their power and endurance.'),
|
66 |
+
('Dog', 'French_Bulldog', 'Small', '10-12 years', 'Playful, adaptable, smart', 'Moderate', True, 'Low', 'Low', 'French Bulldogs are small, muscular dogs with a smooth coat, short face, and bat-like ears. They are affectionate, playful, and well-suited for family living.'),
|
67 |
+
('Dog', 'German_Shepherd', 'Large', '10-13 years', 'Confident, courageous, smart', 'High', True, 'High', 'Moderate', 'Renowned for their versatility and intelligence, these dogs excel in all working roles. Their loyalty and trainability have made them preferred choices for police, military, and service work.'),
|
68 |
+
('Dog', 'German_Short-Haired_Pointer', 'Large', '10-12 years', 'Friendly, intelligent, willing to please', 'High', True, 'Very High', 'Moderate', 'Versatile hunting dogs known for their pointer stance, these dogs excel in both water and land retrieving.'),
|
69 |
+
('Dog', 'Gordon_Setter', 'Large', '10-12 years', 'Confident, fearless, alert', 'High', True, 'High', 'High', 'The largest of the setter breeds, Gordon Setters are known for their black and tan coloring and loyal nature. Developed in Scotland, these noble bird dogs combine strong hunting abilities with devoted family loyalty.'),
|
70 |
+
('Dog', 'Great_Dane', 'Giant', '7-10 years', 'Friendly, patient, dependable', 'High', True, 'Moderate', 'Low', 'One of the largest dog breeds, Great Danes are known as gentle giants with a friendly disposition. Originally bred for hunting large game, these noble giants now excel as loving family companions despite their imposing size.'),
|
71 |
+
('Dog', 'Great_Pyrenees', 'Large', '10-12 years', 'Patient, calm, gentle', 'High', True, 'Moderate', 'High', 'Large, powerful dogs originally bred to guard livestock, known for their gentle and protective nature. These ancient guardians of the Pyrenees mountains combine strength and nobility with a deep devotion to family and flock.'),
|
72 |
+
('Dog', 'Greater_Swiss_Mountain_dog', 'Large', '8-11 years', 'Faithful, alert, vigilant', 'Moderate', True, 'Moderate', 'Low', 'These powerful draft and drover dogs feature a distinctive tricolored coat. Their strength and endurance are matched by their calm, steady temperament and natural watchdog abilities.'),
|
73 |
+
('Dog', 'Havanese', 'Small', '13-15 years', 'Social, intelligent, adaptable', 'Moderate', True, 'Moderate', 'High', 'Cuba\'s only native breed, these charming small dogs feature a silky coat and springy gait. Havanese are known for their adaptable nature, strong bond with family members, and ability to thrive in both apartments and houses.'),
|
74 |
+
('Dog', 'Ibizan_Hound', 'Medium', '12-14 years', 'Even-tempered, loyal, independent', 'Moderate', True, 'High', 'Low', 'Sleek, athletic sighthounds known for their large, erect ears and red and white coats. Ancient breed from Balearic Islands, they can jump remarkable heights and were bred to hunt rabbits in difficult terrain.'),
|
75 |
+
('Dog', 'Irish_Setter', 'Large', '11-15 years', 'Outgoing, sweet-tempered, active', 'High', True, 'High', 'High', 'Sporting dogs renowned for their stunning mahogany coat and graceful movement. Their rollicking personality and boundless energy make them enthusiastic hunting partners and family companions.'),
|
76 |
+
('Dog', 'Irish_Terrier', 'Medium', '12-16 years', 'Bold, daring, intelligent', 'Moderate', True, 'High', 'Moderate', 'Known as the Daredevil of dogdom, Irish Terriers are courageous and loyal with a distinctive red coat. One of the oldest terrier breeds, they earned fame for their bravery as messenger dogs in World War I.'),
|
77 |
+
('Dog', 'Irish_Water_Spaniel', 'Large', '10-12 years', 'Playful, brave, intelligent', 'High', True, 'High', 'High', 'Largest of the spaniels, known for their curly, liver-colored coat and rat-like tail. These distinctive water retrievers combine the agility of a spaniel with the endurance of a retriever, featuring a water-repellent double coat.'),
|
78 |
+
('Dog', 'Irish_Wolfhound', 'Giant', '6-8 years', 'Gentle, patient, dignified', 'High', True, 'Moderate', 'Moderate', 'The tallest of all dog breeds, Irish Wolfhounds are gentle giants known for their calm and friendly nature. Ancient warriors of Ireland, they once hunted wolves but now serve as peaceful family companions.'),
|
79 |
+
('Dog', 'Italian_Greyhound', 'Small', '12-15 years', 'Sensitive, alert, playful', 'Moderate', False, 'Moderate', 'Low', 'Miniature sighthounds that combine delicate grace with surprising athleticism. Their refined appearance and affectionate nature made them favored companions of nobility throughout history.'),
|
80 |
+
('Dog', 'Japanese_Spaniel', 'Small', '10-12 years', 'Charming, noble, affectionate', 'Moderate', False, 'Low', 'High', 'These aristocratic companions blend Eastern and Western toy dog characteristics. Their distinctive flat face and elegant bearing reflect their imperial Japanese heritage.'),
|
81 |
+
('Dog', 'Kerry_Blue_Terrier', 'Medium', '12-15 years', 'Alert, adaptable, people-oriented', 'High', True, 'High', 'High', 'Medium-sized terriers with a distinctive blue coat, known for their versatility and intelligence. Originally from County Kerry, Ireland, they were all-purpose farm dogs that evolved into capable working and companion animals.'),
|
82 |
+
('Dog', 'Labrador_Retriever', 'Large', '10-12 years', 'Friendly, outgoing, even-tempered', 'Moderate', True, 'High', 'Moderate', 'One of the most popular dog breeds, known for their friendly nature and excellent retrieving skills. Originally from Newfoundland, these versatile dogs excel as family companions, service dogs, and working retrievers.'),
|
83 |
+
('Dog', 'Lakeland_Terrier', 'Small', '12-16 years', 'Bold, friendly, confident', 'Moderate', True, 'High', 'High', 'Named after the Lake District in England, these terriers are sturdy and bold with a wiry coat. Developed to protect sheep from foxes, they remain confident and fearless while being adaptable family companions.'),
|
84 |
+
('Dog', 'Leonberg', 'Giant', '7-9 years', 'Gentle, friendly, intelligent', 'High', True, 'Moderate', 'High', 'Large, muscular dogs with a lion-like mane, known for their gentle nature and water rescue abilities. Created in the German town of Leonberg, these gentle giants combine strength with remarkable patience and grace.'),
|
85 |
+
('Dog', 'Lhasa', 'Small', '12-15 years', 'Confident, smart, comical', 'High', False, 'Low', 'High', 'Ancient Tibetan breeds who served as monastery sentinels, these small dogs possess remarkable dignity and independence. Their floor-length coat and confident bearing reflect their noble heritage.'),
|
86 |
+
('Dog', 'Maltese_Dog', 'Small', '12-15 years', 'Gentle, playful, charming', 'High', False, 'Low', 'High', 'Small, elegant dogs with long, silky white coats, known for their sweet and affectionate nature. Ancient breed of Mediterranean origin, they were cherished by nobles for centuries and remain adaptable, gentle companions.'),
|
87 |
+
('Dog', 'Mexican_Hairless', 'Varies', '12-15 years', 'Loyal, alert, cheerful', 'Moderate', True, 'Moderate', 'Low', 'Also known as the Xoloitzcuintli, these dogs come in three sizes and can be either hairless or coated, known for their ancient history in Mexico.'),
|
88 |
+
('Dog', 'Newfoundland', 'Giant', '8-10 years', 'Sweet, patient, devoted', 'High', True, 'Moderate', 'High', 'Large, strong dogs known for their water rescue abilities and gentle nature, especially with children. These powerful swimmers have a natural lifesaving instinct and are famous for their calm, noble temperament.'),
|
89 |
+
('Dog', 'Norfolk_Terrier', 'Small', '12-15 years', 'Fearless, spirited, companionable', 'Moderate', True, 'Moderate', 'Moderate', 'Among the smallest working terriers, these sturdy dogs combine typical terrier determination with a charming personality. Their compact size and fearless nature made them excellent ratters.'),
|
90 |
+
('Dog', 'Norwegian_Elkhound', 'Medium', '12-15 years', 'Bold, playful, loyal', 'High', True, 'High', 'High', 'Ancient Viking hunting companions, these spitz-type dogs blend strength with agility. Their thick silver-gray coat and curved tail reflect their Nordic heritage and hunting prowess.'),
|
91 |
+
('Dog', 'Norwich_Terrier', 'Small', '12-15 years', 'Fearless, loyal, affectionate', 'Moderate', True, 'Moderate', 'Moderate', 'These spirited terriers pack big personalities into small frames. Originally bred for ratting and fox bolting, they combine typical terrier toughness with an especially affectionate nature.'),
|
92 |
+
('Dog', 'Old_English_Sheepdog', 'Large', '10-12 years', 'Adaptable, gentle, intelligent', 'High', True, 'Moderate', 'High', 'Recognizable by their shaggy coat, Old English Sheepdogs are adaptable and good-natured. Once droving dogs of western England, they combine herding ability with a playful, protective nature toward their families.'),
|
93 |
+
('Dog', 'Pekinese', 'Small', '12-14 years', 'Affectionate, loyal, regal in manner', 'Moderate', False, 'Low', 'High', 'These ancient Chinese imperial companions maintain their dignified bearing and lion-like appearance. Their distinctive flat face and luxurious coat reflect centuries of careful breeding as palace dogs.'),
|
94 |
+
('Dog', 'Pembroke', 'Small', '12-15 years', 'Affectionate, intelligent, outgoing', 'Moderate', True, 'Moderate', 'Moderate', 'Despite their small stature, these herding dogs possess remarkable strength and agility. Their fox-like face and characteristic short legs reflect their heritage as efficient cattle herders.'),
|
95 |
+
('Dog', 'Pomeranian', 'Small', '12-16 years', 'Lively, bold, inquisitive', 'Moderate', False, 'Low', 'High', 'Small, fluffy dogs with fox-like faces, known for their vivacious personalities and luxurious coats. Once larger sled dogs, these bred-down companions retain their bold spirit and were favored by royalty including Queen Victoria.'),
|
96 |
+
('Dog', 'Rhodesian_Ridgeback', 'Large', '10-12 years', 'Dignified, intelligent, strong-willed', 'Moderate', True, 'High', 'Low', 'Originally bred to hunt lions in Africa, these powerful dogs are distinguished by their unique ridge of backward-growing hair. Their combination of strength and agility makes them formidable hunting companions.'),
|
97 |
+
('Dog', 'Rottweiler', 'Large', '8-10 years', 'Loyal, loving, confident guardian', 'High', True, 'High', 'Low', 'Originally bred to drive cattle and pull carts, these powerful dogs combine impressive strength with intelligence. Their protective instincts and deep devotion make them exceptional family guardians.'),
|
98 |
+
('Dog', 'Saint_Bernard', 'Giant', '8-10 years', 'Gentle, patient, friendly', 'High', True, 'Moderate', 'High', 'These legendary Alpine rescue dogs are known for their massive size and gentle disposition. Their thick coat and powerful build helped them excel at their original mission of mountain rescue.'),
|
99 |
+
('Dog', 'Saluki', 'Large', '12-14 years', 'Gentle, dignified, independent-minded', 'High', True, 'High', 'Low', 'One of the oldest known dog breeds, Salukis combine incredible speed with elegant grace. Their distinctive feathered coat and refined appearance reflect their ancient desert heritage.'),
|
100 |
+
('Dog', 'Samoyed', 'Medium', '12-14 years', 'Friendly, gentle, adaptable', 'High', True, 'High', 'High', 'Beautiful white Arctic dogs known for their "smiling" expression and thick, fluffy coat. Originally bred for sledding and herding reindeer, they combine working dog capability with a warm, family-friendly nature.'),
|
101 |
+
('Dog', 'Scotch_Terrier', 'Small', '11-13 years', 'Independent, confident, spirited', 'Moderate', True, 'Moderate', 'High', 'Also known as the Scottish Terrier, these distinctive dogs with beards and eyebrows are known for their dignified, almost human-like personality.'),
|
102 |
+
('Dog', 'Scottish_Deerhound', 'Large', '8-11 years', 'Gentle, dignified, polite', 'High', True, 'High', 'Moderate', 'Often called the "Royal Dog of Scotland," these noble sighthounds combine great size with gentle dignity. Their rough coat and incredible speed made them ideal deer hunting companions.'),
|
103 |
+
('Dog', 'Sealyham_Terrier', 'Small', '12-14 years', 'Alert, outgoing, calm', 'Moderate', True, 'Moderate', 'High', 'Originally bred for hunting, Sealyhams are now rare but make charming and sturdy companions. Developed in Wales to hunt badgers and otters, they combine terrier tenacity with a surprisingly calm demeanor.'),
|
104 |
+
('Dog', 'Shetland_Sheepdog', 'Small', '12-14 years', 'Playful, energetic, intelligent', 'High', True, 'High', 'High', 'Small herding dogs resembling miniature Collies, known for their intelligence and agility. Originally from the Shetland Islands, these "Shelties" excel in obedience, herding, and agility competitions while being devoted family companions.'),
|
105 |
+
('Dog', 'Shiba_Inu', 'Small', '12-15 years', 'Independent, alert, confident', 'Moderate', True, 'High', 'Moderate', 'Ancient Japanese breed known for their fox-like appearance and independent spirit. Shibas are intelligent, alert, and proud dogs with a strong prey drive and distinctive personality, making them loyal companions for experienced dog owners.'),
|
106 |
+
('Dog', 'Shih-Tzu', 'Small', '10-16 years', 'Affectionate, playful, outgoing', 'High', True, 'Low', 'High', 'Small, affectionate companion dogs known for their long, silky coat and sweet personality. Originally bred for Chinese royalty, they are excellent lap dogs and adapt well to both city and suburban life.'),
|
107 |
+
('Dog', 'Siberian_Husky', 'Medium', '12-14 years', 'Outgoing, mischievous, loyal', 'High', True, 'Very High', 'Moderate', 'Beautiful sled dogs known for their striking blue eyes, thick coats, and wolf-like appearance. Originally bred by the Chukchi people of northeastern Asia, they combine endurance with a friendly, adventurous spirit.'),
|
108 |
+
('Dog', 'Staffordshire_Bullterrier', 'Medium', '12-14 years', 'Courageous, intelligent, loyal', 'Moderate', True, 'High', 'Low', 'Developed for dog fighting but bred for companionship, these muscular terriers are known as "nanny dogs" for their patience with children. Their strength is matched by their affectionate and reliable nature.'),
|
109 |
+
('Dog', 'Sussex_Spaniel', 'Medium', '11-13 years', 'Calm, friendly, merry', 'Moderate', True, 'Moderate', 'Moderate', 'These rare spaniels, distinguished by their rich golden-liver coat and low-set body, combine typical spaniel enthusiasm with a uniquely calm demeanor. Their deliberate movement and melodious voice set them apart.'),
|
110 |
+
('Dog', 'Tibetan_Mastiff', 'Large', '10-12 years', 'Independent, reserved, intelligent', 'High', False, 'Moderate', 'High', 'Ancient guardians of Tibetan monasteries, these imposing dogs combine massive size with remarkable intelligence. Their thick double coat and noble bearing reflect their mountain guardian heritage.'),
|
111 |
+
('Dog', 'Tibetan_Terrier', 'Medium', '12-15 years', 'Affectionate, sensitive, clever', 'High', True, 'Moderate', 'High', 'Despite their name, these ancient Tibetan dogs were bred as companions, not terriers. Their profuse double coat and balanced, agile nature reflect their mountainous origins and adaptable personality.'),
|
112 |
+
('Dog', 'Walker_Hound', 'Large', '12-13 years', 'Smart, brave, friendly', 'Moderate', True, 'High', 'Low', 'Also known as the Treeing Walker Coonhound, these dogs are excellent hunters with a distinctive bark. Developed in Kentucky from Virginia Hounds, they are renowned for their speed, endurance, and melodious voice.'),
|
113 |
+
('Dog', 'Weimaraner', 'Large', '10-13 years', 'Friendly, fearless, obedient', 'High', True, 'High', 'Low', 'Originally bred for hunting large game, these distinctive gray dogs combine athletic prowess with keen intelligence. Their striking appearance and devoted nature have earned them the nickname "Gray Ghost."'),
|
114 |
+
('Dog', 'Welsh_Springer_Spaniel', 'Medium', '12-15 years', 'Active, loyal, affectionate', 'High', True, 'High', 'Moderate', 'Distinguished by their rich red and white coat, Welsh Springers combine the typical spaniel enthusiasm with exceptional devotion to their families. Their compact build and agile nature make them skilled hunting companions.'),
|
115 |
+
('Dog', 'West_Highland_White_Terrier', 'Small', '12-16 years', 'Friendly, hardy, confident', 'Moderate', True, 'Moderate', 'High', 'These distinctive white terriers combine classic terrier toughness with a friendly demeanor. Originally bred for hunting, Westies maintain their bold spirit while being adaptable and affectionate family companions.'),
|
116 |
+
('Dog', 'Yorkshire_Terrier', 'Small', '13-16 years', 'Affectionate, sprightly, tomboyish', 'High', False, 'Moderate', 'High', 'Popular toy breed known for their long silky coat and feisty personality. Despite their small size, they maintain a brave terrier spirit and were originally bred as ratters in Yorkshire mills.'),
|
117 |
+
('Dog', 'Affenpinscher', 'Small', '12-15 years', 'Confident, amusing, stubborn', 'Moderate', False, 'Moderate', 'Moderate', 'Called "monkey dogs" for their distinctive facial features, these small but confident dogs combine terrier-like qualities with toy dog charm. Their bold personality and comical expression make them entertaining companions.'),
|
118 |
+
('Dog', 'Basenji', 'Small', '12-16 years', 'Independent, smart, poised', 'Moderate', False, 'High', 'Low', 'Ancient African breed known for their inability to bark, instead making a unique yodel-like sound. Called "the barkless dog," they are intelligent hunters with cat-like cleanliness and independent nature.'),
|
119 |
+
('Dog', 'Basset', 'Medium', '10-12 years', 'Patient, low-key, charming', 'Moderate', True, 'Low', 'Moderate', 'Short-legged, long-bodied hounds known for their excellent sense of smell and gentle dispositions. Second only to Bloodhounds in scenting ability, these French-origin dogs combine persistence with a sweet, patient nature.'),
|
120 |
+
('Dog', 'Beagle', 'Small', '12-15 years', 'Merry, friendly, curious', 'Moderate', True, 'High', 'Low', 'Small hound dogs known for their excellent sense of smell and friendly, outgoing personalities. Popular family pets and skilled scent hunters, famous for their melodious bay and pack mentality.'),
|
121 |
+
('Dog', 'Black-and-Tan_Coonhound', 'Large', '10-12 years', 'Even-tempered, easygoing, friendly', 'Moderate', True, 'High', 'Low', 'Developed as nocturnal hunters, these powerful scenthounds possess remarkable stamina and tracking abilities. Their distinctive melodious bay and striking coat pattern reflect their specialized hunting heritage.'),
|
122 |
+
('Dog', 'Bloodhound', 'Large', '10-12 years', 'Gentle, patient, stubborn', 'High', True, 'Moderate', 'Moderate', 'Renowned for possessing the most sensitive nose of any dog breed, Bloodhounds combine this extraordinary tracking ability with a gentle, determined nature. Their wrinkled face and long ears are distinctive breed characteristics.'),
|
123 |
+
('Dog', 'Bluetick', 'Large', '11-12 years', 'Friendly, intelligent, active', 'Moderate', True, 'High', 'Low', 'Skilled hunting companions recognized by their distinctive blue-ticked coat pattern. Their keen nose and trademark bawling bark make them exceptional at tracking nocturnal prey.'),
|
124 |
+
('Dog', 'Borzoi', 'Large', '10-12 years', 'Quiet, gentle, athletic', 'High', True, 'Moderate', 'High', 'Aristocratic sighthounds originally bred for wolf hunting in Russia, Borzois combine remarkable speed with elegant grace. Their calm nature and distinctive silky coat make them striking companions who maintain a dignified bearing.'),
|
125 |
+
('Dog', 'Boxer', 'Large', '10-12 years', 'Fun-loving, bright, active', 'Moderate', True, 'High', 'Low', 'Playful and energetic, Boxers are known for their patient and protective nature with children. Originally developed in Germany as working dogs, they combine strength with a uniquely playful and clownish personality.'),
|
126 |
+
('Dog', 'Briard', 'Large', '10-12 years', 'Confident, smart, loyal', 'High', True, 'High', 'High', 'Large French herding dogs with a distinctive long, wavy coat, Briards are loyal and protective. Known as "hearts wrapped in fur," they served as WWI sentries and now excel as both working dogs and devoted family guardians.'),
|
127 |
+
('Dog', 'Bull_mastiff', 'Large', '8-10 years', 'Affectionate, loyal, quiet', 'Moderate', True, 'Moderate', 'Low', 'Developed to be silent guardians of large estates, Bullmastiffs combine impressive strength with a gentle nature. Despite their imposing size, they are known for their patient and calm demeanor with family members.'),
|
128 |
+
('Dog', 'Cairn', 'Small', '13-15 years', 'Alert, cheerful, busy', 'Moderate', True, 'Moderate', 'Moderate', 'Small, rugged terriers known for their shaggy coat and lively personality. Originally bred to hunt in the Scottish Highlands, these hardy dogs are intelligent and make excellent watchdogs despite their small size.'),
|
129 |
+
('Dog', 'Chow', 'Medium', '8-12 years', 'Aloof, loyal, quiet', 'High', False, 'Low', 'High', 'One of the oldest dog breeds, known for their distinctive blue-black tongue and lion-like appearance. Their independent nature and natural dignity reflect their ancient Chinese origins.'),
|
130 |
+
('Dog', 'Clumber', 'Large', '10-12 years', 'Gentle, loyal, thoughtful', 'Moderate', True, 'Moderate', 'High', 'The largest of the spaniels, Clumbers are known for their distinctive white coat and calm demeanor. Developed in France and England, these dignified hunters combine power with a methodical hunting style and gentle nature.'),
|
131 |
+
('Dog', 'Cocker_Spaniel', 'Small', '10-14 years', 'Gentle, smart, happy', 'High', True, 'Moderate', 'High', 'Beloved for their merry temperament and beautiful flowing coat, Cocker Spaniels embody charm and versatility. Their expressive eyes and gentle nature have made them enduring favorites as both show dogs and family companions.'),
|
132 |
+
('Dog', 'Collie', 'Large', '10-14 years', 'Devoted, graceful, proud', 'High', True, 'High', 'High', 'Made famous by "Lassie," Collies are intelligent herding dogs known for their loyalty and grace. Their remarkable intuition and gentle nature make them exceptional family guardians, especially with children.'),
|
133 |
+
('Dog', 'Curly-Coated_Retriever', 'Large', '10-12 years', 'Confident, independent, intelligent', 'Moderate', True, 'High', 'Low', 'Distinguished by their unique mass of tight, crisp curls, these capable water retrievers combine athletic ability with independence. Their waterproof coat and strong swimming skills make them exceptional sporting companions.'),
|
134 |
+
('Dog', 'Dhole', 'Medium', '10-13 years', 'Social, intelligent, athletic', 'High', False, 'High', 'Low', 'Highly social wild canids native to Asia, Dholes are remarkable pack hunters known for their whistling vocalizations. Their reddish coat and unique social structure distinguish them from other wild dogs.'),
|
135 |
+
('Dog', 'Dingo', 'Medium', '10-13 years', 'Independent, intelligent, alert', 'High', False, 'High', 'Low', "Australia's native wild dog, Dingoes are highly adaptable and intelligent apex predators. Their distinctive features include a bushy tail, pointed ears, and characteristic sandy-gold coat."),
|
136 |
+
('Dog', 'Flat-Coated_Retriever', 'Large', '8-10 years', 'Optimistic, good-humored, outgoing', 'High', True, 'Very High', 'Moderate', 'Known for their shiny black or liver-colored coat, Flat-coated Retrievers are energetic and playful, excelling in both hunting and family life.'),
|
137 |
+
('Dog', 'Giant_Schnauzer', 'Large', '10-12 years', 'Loyal, intelligent, powerful', 'High', True, 'High', 'High', 'Developed as robust working dogs, Giant Schnauzers combine strength with intelligence. Their powerful build and protective nature made them excellent guard dogs, while maintaining the alertness characteristic of their smaller cousins.'),
|
138 |
+
('Dog', 'Golden_Retriever', 'Large', '10-12 years', 'Intelligent, friendly, devoted', 'High', True, 'High', 'High', 'Beautiful, golden-coated dogs known for their gentle nature and excellence in various roles. Popular as family companions, therapy dogs, and service animals, they excel in both work and companionship with their eager-to-please attitude.'),
|
139 |
+
('Dog', 'Groenendael', 'Large', '10-12 years', 'Intelligent, protective, loyal', 'High', True, 'High', 'High', 'The black variety of Belgian Shepherd, Groenendaels are intelligent working dogs with a long, black coat. Named after their village of origin, they excel in police work, herding, and as vigilant family guardians.'),
|
140 |
+
('Dog', 'Keeshond', 'Medium', '12-15 years', 'Friendly, lively, outgoing', 'Moderate', True, 'Moderate', 'High', 'Originally Dutch barge dogs, these spitz-type companions are known for their distinctive "spectacles" and thick silver-gray coat. Their friendly nature made them popular as boat watchdogs.'),
|
141 |
+
('Dog', 'Kelpie', 'Medium', '10-13 years', 'Intelligent, energetic, loyal', 'High', True, 'Very High', 'Low', 'Australian herding dogs known for their incredible work ethic and agility. Developed to work in harsh outback conditions, they are renowned for their ability to herd from above, often running across the backs of sheep in large flocks.'),
|
142 |
+
('Dog', 'Komondor', 'Large', '10-12 years', 'Steady, fearless, affectionate', 'High', True, 'Moderate', 'High', 'Large Hungarian sheepdogs known for their distinctive corded white coat, resembling dreadlocks. Their unique coat once helped them blend in with sheep flocks while protecting them from wolves.'),
|
143 |
+
('Dog', 'Kuvasz', 'Large', '10-12 years', 'Protective, loyal, patient', 'High', True, 'Moderate', 'High', 'Large, white guardian dogs from Hungary, Kuvaszok are protective of their families and independent. Once royal guards of Hungarian nobility, they combine impressive strength with natural protective instincts.'),
|
144 |
+
('Dog', 'Malamute', 'Large', '10-12 years', 'Affectionate, loyal, playful', 'High', True, 'Very High', 'High', 'Large, powerful sled dogs with thick coats, known for their strength and endurance. Originally bred by the Mahlemut tribe for hauling heavy loads in arctic conditions, they combine impressive power with a friendly, family-oriented nature.'),
|
145 |
+
('Dog', 'Malinois', 'Medium', '12-14 years', 'Confident, smart, hardworking', 'High', True, 'High', 'Moderate', 'Renowned for their exceptional intelligence and work ethic, Malinois excel in police and military roles. Their intense drive and unwavering loyalty make them outstanding working dogs requiring consistent training and engagement.'),
|
146 |
+
('Dog', 'Miniature_Pinscher', 'Small', '12-16 years', 'Fearless, energetic, alert', 'Moderate', False, 'Moderate', 'Low', 'Often called King of Toys, Miniature Pinschers are small, energetic dogs with a big personality. Despite their small size, these fearless dogs possess proud carriage and spirited animation.'),
|
147 |
+
('Dog', 'Miniature_Poodle', 'Small', '12-15 years', 'Intelligent, active, alert', 'High', True, 'Moderate', 'High', 'Smaller version of the Standard Poodle, known for their intelligence and hypoallergenic coat. Popular show dogs and companions, they retain their larger relatives high intelligence while being more adaptable to city living.'),
|
148 |
+
('Dog', 'Miniature_Schnauzer', 'Small', '12-15 years', 'Friendly, smart, obedient', 'Moderate', True, 'Moderate', 'High', 'The smallest of the Schnauzer breeds, known for their distinctive beard and eyebrows. Originally ratters and farm dogs, they combine intelligence with a spunky personality, making excellent watchdogs and family companions.'),
|
149 |
+
('Dog', 'Otterhound', 'Large', '10-13 years', 'Friendly, boisterous, even-tempered', 'High', True, 'High', 'High', 'Large, shaggy-coated hounds originally bred for hunting otters, now a rare breed. Known for their strong swimming ability and powerful nose, with less than 1000 remaining worldwide, making them rarer than giant pandas.'),
|
150 |
+
('Dog', 'Papillon', 'Small', '13-15 years', 'Happy, alert, friendly', 'Moderate', True, 'Moderate', 'Moderate', 'Small, elegant dogs known for their butterfly-like ears and lively personalities. Despite their delicate appearance, they are surprisingly athletic and intelligent, ranking among the top 10 smartest dog breeds. Also called the Continental Toy Spaniel.'),
|
151 |
+
('Dog', 'Pug', 'Small', '12-15 years', 'Charming, mischievous, loving', 'Moderate', True, 'Low', 'Moderate', 'Small, wrinkly-faced dogs known for their charming personality and comical expression. Once favored by Chinese emperors, these "multum in parvo" (much in little) dogs are excellent companions but need attention to their breathing and temperature regulation.'),
|
152 |
+
('Dog', 'Redbone', 'Large', '10-12 years', 'Even-tempered, amiable, eager to please', 'Moderate', True, 'High', 'Low', 'Known for their solid red coat, Redbone Coonhounds are athletic, warm-hearted dogs originally bred for hunting. Developed in the American South, they excel at tracking and treeing with remarkable stamina and a melodious voice.'),
|
153 |
+
('Dog', 'Schipperke', 'Small', '13-15 years', 'Confident, alert, curious', 'Moderate', True, 'Moderate', 'Moderate', 'Small, black dogs with a fox-like face, Schipperkes are known for their distinctive ruff and small, pointed ears. Originally Belgian barge dogs, these little captains earned their name as boat watchdogs and ratters.'),
|
154 |
+
('Dog', 'Silky_terrier', 'Small', '12-15 years', 'Friendly, quick, alert', 'Moderate', False, 'Moderate', 'High', 'Similar to Yorkshire Terriers but larger, Silky Terriers are playful and enjoy being part of family activities. Developed in Australia, they combine the refinement of toy dogs with the sturdy nature of working terriers.'),
|
155 |
+
('Dog', 'Soft-Coated_Wheaten_Terrier', 'Medium', '12-14 years', 'Happy, steady, self-confident', 'High', True, 'High', 'High', 'Known for their soft, wheat-colored coat and friendly demeanor, they make great family dogs. Developed in Ireland as farm dogs, they combined versatility in herding and hunting with a uniquely soft coat unlike other terriers.'),
|
156 |
+
('Dog', 'Standard_Poodle', 'Large', '10-18 years', 'Intelligent, active, dignified', 'High', True, 'High', 'High', 'Distinguished for their exceptional intelligence and elegant bearing, Standard Poodles excel in both show rings and as working dogs. Their hypoallergenic coat and versatile abilities make them outstanding companions for various activities.'),
|
157 |
+
('Dog', 'Standard_Schnauzer', 'Medium', '13-16 years', 'Friendly, intelligent, obedient', 'High', True, 'High', 'High', 'Originally developed as versatile farm dogs, Standard Schnauzers combine intelligence with a strong work ethic. Their distinctive beard and eyebrows complement their alert personality and natural guarding instincts.'),
|
158 |
+
('Dog', 'Toy_Poodle', 'Small', '12-18 years', 'Intelligent, lively, playful', 'High', True, 'Moderate', 'High', 'The smallest variety of Poodle, known for their intelligence, agility, and hypoallergenic coat. Despite their diminutive size, they retain the intelligence and athletic ability of their larger relatives.'),
|
159 |
+
('Dog', 'Toy_Terrier', 'Small', '12-16 years', 'Lively, bold, intelligent', 'Moderate', False, 'Moderate', 'Low', 'These compact terriers pack big personalities into small frames. Despite their diminutive size, they maintain the classic terrier traits of boldness and alertness, making excellent watchdogs and agile competitors.'),
|
160 |
+
('Dog', 'Vizsla', 'Medium', '10-14 years', 'Affectionate, energetic, gentle', 'High', True, 'High', 'Low', 'Known for their golden-rust coat, Vizslas are versatile hunters and loving family companions. These Hungarian pointers are often called "velcro dogs" for their strong desire to stay close to their owners.'),
|
161 |
+
('Dog', 'Whippet', 'Medium', '12-15 years', 'Gentle, affectionate, quiet', 'Low', True, 'High', 'Low', 'Nicknamed the poor mans racehorse, these elegant sighthounds combine incredible speed with a gentle nature. Their athletic build belies their calm, quiet indoor personality.'),
|
162 |
+
('Dog', 'Wire-Haired_Fox_Terrier', 'Small', '12-15 years', 'Alert, confident, gregarious', 'High', True, 'High', 'High', 'Energetic and wire-coated, these terriers were originally bred for fox hunting. Their tough, dense coat and fearless nature made them ideal for flushing foxes from their dens, and they remain bold and spirited companions.'),
|
163 |
+
]
|
164 |
+
|
165 |
+
def insert_dog_data():
|
166 |
+
conn = sqlite3.connect('animal_detector.db')
|
167 |
+
cursor = conn.cursor()
|
168 |
+
cursor.executemany('''
|
169 |
+
INSERT INTO AnimalCatalog (Species, Breed, Size_Category, Typical_Lifespan, Temperament, Care_Level, Good_With_Children, Exercise_Needs, Grooming_Needs, Brief_Description)
|
170 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
171 |
+
''', dog_data)
|
172 |
+
|
173 |
+
conn.commit()
|
174 |
+
cursor.close()
|
175 |
+
conn.close()
|
176 |
+
|
177 |
+
def get_dog_description(breed):
|
178 |
+
try:
|
179 |
+
conn = sqlite3.connect('animal_detector.db')
|
180 |
+
cursor = conn.cursor()
|
181 |
+
|
182 |
+
breed_name = breed.split('(')[0].strip()
|
183 |
+
|
184 |
+
cursor.execute("""
|
185 |
+
SELECT * FROM AnimalCatalog
|
186 |
+
WHERE Breed = ? OR Breed LIKE ? OR Breed LIKE ?
|
187 |
+
""", (breed_name, f"{breed_name}%", f"%{breed_name}"))
|
188 |
+
|
189 |
+
result = cursor.fetchone()
|
190 |
+
|
191 |
+
cursor.close()
|
192 |
+
conn.close()
|
193 |
+
|
194 |
+
if result:
|
195 |
+
# 標準化運動需求值
|
196 |
+
exercise_needs = result[8]
|
197 |
+
normalized_exercise = exercise_needs.strip().title()
|
198 |
+
if normalized_exercise not in ["Very High", "High", "Moderate", "Low"]:
|
199 |
+
normalized_exercise = "High" # 預設值
|
200 |
+
|
201 |
+
description = {
|
202 |
+
"Breed": result[2],
|
203 |
+
"Size": result[3],
|
204 |
+
"Lifespan": result[4],
|
205 |
+
"Temperament": result[5],
|
206 |
+
"Care Level": result[6],
|
207 |
+
"Good with Children": "Yes" if result[7] else "No",
|
208 |
+
"Exercise Needs": normalized_exercise,
|
209 |
+
"Grooming Needs": result[9],
|
210 |
+
"Description": result[10]
|
211 |
+
}
|
212 |
+
return description
|
213 |
+
else:
|
214 |
+
print(f"No data found for breed: {breed_name}")
|
215 |
+
return None
|
216 |
+
|
217 |
+
except Exception as e:
|
218 |
+
print(f"Error in get_dog_description: {str(e)}")
|
219 |
+
return None
|
220 |
+
|
221 |
+
insert_dog_data()
|
smart_breed_matcher.py
ADDED
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from sentence_transformers import SentenceTransformer, util
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
from typing import List, Dict, Tuple
|
6 |
+
from dataclasses import dataclass
|
7 |
+
from breed_health_info import breed_health_info
|
8 |
+
from breed_noise_info import breed_noise_info
|
9 |
+
|
10 |
+
class SmartBreedMatcher:
|
11 |
+
def __init__(self, dog_data: List[Tuple]):
|
12 |
+
self.dog_data = dog_data
|
13 |
+
self.model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
14 |
+
|
15 |
+
def _categorize_breeds(self) -> Dict:
|
16 |
+
"""自動將狗品種分類"""
|
17 |
+
categories = {
|
18 |
+
'working_dogs': [],
|
19 |
+
'herding_dogs': [],
|
20 |
+
'hunting_dogs': [],
|
21 |
+
'companion_dogs': [],
|
22 |
+
'guard_dogs': []
|
23 |
+
}
|
24 |
+
|
25 |
+
for breed_info in self.dog_data:
|
26 |
+
description = breed_info[9].lower()
|
27 |
+
temperament = breed_info[4].lower()
|
28 |
+
|
29 |
+
# 根據描述和性格特徵自動分類
|
30 |
+
if any(word in description for word in ['herding', 'shepherd', 'cattle', 'flock']):
|
31 |
+
categories['herding_dogs'].append(breed_info[1])
|
32 |
+
elif any(word in description for word in ['hunting', 'hunt', 'retriever', 'pointer']):
|
33 |
+
categories['hunting_dogs'].append(breed_info[1])
|
34 |
+
elif any(word in description for word in ['companion', 'toy', 'family', 'lap']):
|
35 |
+
categories['companion_dogs'].append(breed_info[1])
|
36 |
+
elif any(word in description for word in ['guard', 'protection', 'watchdog']):
|
37 |
+
categories['guard_dogs'].append(breed_info[1])
|
38 |
+
elif any(word in description for word in ['working', 'draft', 'cart']):
|
39 |
+
categories['working_dogs'].append(breed_info[1])
|
40 |
+
|
41 |
+
return categories
|
42 |
+
|
43 |
+
def find_similar_breeds(self, breed_name: str, top_n: int = 5) -> List[Tuple[str, float]]:
|
44 |
+
"""找出與指定品種最相似的其他品種"""
|
45 |
+
target_breed = next((breed for breed in self.dog_data if breed[1] == breed_name), None)
|
46 |
+
if not target_breed:
|
47 |
+
return []
|
48 |
+
|
49 |
+
# 獲取目標品種的特徵
|
50 |
+
target_features = {
|
51 |
+
'breed_name': target_breed[1], # 添加品種名稱
|
52 |
+
'size': target_breed[2],
|
53 |
+
'temperament': target_breed[4],
|
54 |
+
'exercise': target_breed[7],
|
55 |
+
'description': target_breed[9]
|
56 |
+
}
|
57 |
+
|
58 |
+
similarities = []
|
59 |
+
for breed in self.dog_data:
|
60 |
+
if breed[1] != breed_name:
|
61 |
+
breed_features = {
|
62 |
+
'breed_name': breed[1], # 添加品種名稱
|
63 |
+
'size': breed[2],
|
64 |
+
'temperament': breed[4],
|
65 |
+
'exercise': breed[7],
|
66 |
+
'description': breed[9]
|
67 |
+
}
|
68 |
+
|
69 |
+
similarity_score = self._calculate_breed_similarity(target_features, breed_features)
|
70 |
+
similarities.append((breed[1], similarity_score))
|
71 |
+
|
72 |
+
return sorted(similarities, key=lambda x: x[1], reverse=True)[:top_n]
|
73 |
+
|
74 |
+
def _calculate_breed_similarity(self, breed1_features: Dict, breed2_features: Dict) -> float:
|
75 |
+
"""計算兩個品種之間的相似度,包含健康因素"""
|
76 |
+
# 計算描述文本的相似度
|
77 |
+
desc1_embedding = self.model.encode(breed1_features['description'])
|
78 |
+
desc2_embedding = self.model.encode(breed2_features['description'])
|
79 |
+
description_similarity = float(util.pytorch_cos_sim(desc1_embedding, desc2_embedding))
|
80 |
+
|
81 |
+
# 基本特徵相似度
|
82 |
+
size_similarity = 1.0 if breed1_features['size'] == breed2_features['size'] else 0.5
|
83 |
+
exercise_similarity = 1.0 if breed1_features['exercise'] == breed2_features['exercise'] else 0.5
|
84 |
+
|
85 |
+
# 性格相似度
|
86 |
+
temp1_embedding = self.model.encode(breed1_features['temperament'])
|
87 |
+
temp2_embedding = self.model.encode(breed2_features['temperament'])
|
88 |
+
temperament_similarity = float(util.pytorch_cos_sim(temp1_embedding, temp2_embedding))
|
89 |
+
|
90 |
+
# 健康分數相似度
|
91 |
+
health_score1 = self._calculate_health_score(breed1_features['breed_name'])
|
92 |
+
health_score2 = self._calculate_health_score(breed2_features['breed_name'])
|
93 |
+
health_similarity = 1.0 - abs(health_score1 - health_score2)
|
94 |
+
|
95 |
+
# 加權計算
|
96 |
+
weights = {
|
97 |
+
'description': 0.3,
|
98 |
+
'temperament': 0.25,
|
99 |
+
'exercise': 0.15,
|
100 |
+
'size': 0.1,
|
101 |
+
'health': 0.2
|
102 |
+
}
|
103 |
+
|
104 |
+
final_similarity = (
|
105 |
+
description_similarity * weights['description'] +
|
106 |
+
temperament_similarity * weights['temperament'] +
|
107 |
+
exercise_similarity * weights['exercise'] +
|
108 |
+
size_similarity * weights['size'] +
|
109 |
+
health_similarity * weights['health']
|
110 |
+
)
|
111 |
+
|
112 |
+
return final_similarity
|
113 |
+
|
114 |
+
def _calculate_breed_similarity(self, breed1_features: Dict, breed2_features: Dict) -> float:
|
115 |
+
"""計算兩個品種之間的相似度,包含健康和噪音因素"""
|
116 |
+
# 計算描述文本的相似度
|
117 |
+
desc1_embedding = self.model.encode(breed1_features['description'])
|
118 |
+
desc2_embedding = self.model.encode(breed2_features['description'])
|
119 |
+
description_similarity = float(util.pytorch_cos_sim(desc1_embedding, desc2_embedding))
|
120 |
+
|
121 |
+
# 基本特徵相似度
|
122 |
+
size_similarity = 1.0 if breed1_features['size'] == breed2_features['size'] else 0.5
|
123 |
+
exercise_similarity = 1.0 if breed1_features['exercise'] == breed2_features['exercise'] else 0.5
|
124 |
+
|
125 |
+
# 性格相似度
|
126 |
+
temp1_embedding = self.model.encode(breed1_features['temperament'])
|
127 |
+
temp2_embedding = self.model.encode(breed2_features['temperament'])
|
128 |
+
temperament_similarity = float(util.pytorch_cos_sim(temp1_embedding, temp2_embedding))
|
129 |
+
|
130 |
+
# 健康分數相似度
|
131 |
+
health_score1 = self._calculate_health_score(breed1_features['breed_name'])
|
132 |
+
health_score2 = self._calculate_health_score(breed2_features['breed_name'])
|
133 |
+
health_similarity = 1.0 - abs(health_score1 - health_score2)
|
134 |
+
|
135 |
+
# 噪音水平相似度
|
136 |
+
noise_similarity = self._calculate_noise_similarity(
|
137 |
+
breed1_features['breed_name'],
|
138 |
+
breed2_features['breed_name']
|
139 |
+
)
|
140 |
+
|
141 |
+
# 加權計算
|
142 |
+
weights = {
|
143 |
+
'description': 0.25,
|
144 |
+
'temperament': 0.20,
|
145 |
+
'exercise': 0.15,
|
146 |
+
'size': 0.10,
|
147 |
+
'health': 0.15,
|
148 |
+
'noise': 0.15
|
149 |
+
}
|
150 |
+
|
151 |
+
final_similarity = (
|
152 |
+
description_similarity * weights['description'] +
|
153 |
+
temperament_similarity * weights['temperament'] +
|
154 |
+
exercise_similarity * weights['exercise'] +
|
155 |
+
size_similarity * weights['size'] +
|
156 |
+
health_similarity * weights['health'] +
|
157 |
+
noise_similarity * weights['noise']
|
158 |
+
)
|
159 |
+
|
160 |
+
return final_similarity
|
161 |
+
|
162 |
+
|
163 |
+
def _calculate_final_scores(self, breed_name: str, base_scores: Dict,
|
164 |
+
smart_score: float, is_preferred: bool,
|
165 |
+
similarity_score: float = 0.0) -> Dict:
|
166 |
+
"""
|
167 |
+
計算最終分數,包含基礎分數和獎勵分數
|
168 |
+
|
169 |
+
Args:
|
170 |
+
breed_name: 品種名稱
|
171 |
+
base_scores: 基礎評分 (空間、運動等)
|
172 |
+
smart_score: 智能匹配分數
|
173 |
+
is_preferred: 是否為用戶指定品種
|
174 |
+
similarity_score: 與指定品種的相似度 (0-1)
|
175 |
+
"""
|
176 |
+
# 基礎權重
|
177 |
+
weights = {
|
178 |
+
'base': 0.6, # 基礎分數權重
|
179 |
+
'smart': 0.25, # 智能匹配權重
|
180 |
+
'bonus': 0.15 # 獎勵分數權重
|
181 |
+
}
|
182 |
+
|
183 |
+
# 計算基礎分數
|
184 |
+
base_score = base_scores.get('overall', 0.7)
|
185 |
+
|
186 |
+
# 計算獎勵分數
|
187 |
+
bonus_score = 0.0
|
188 |
+
if is_preferred:
|
189 |
+
# 用戶指定品種獲得最高獎勵
|
190 |
+
bonus_score = 0.95
|
191 |
+
elif similarity_score > 0:
|
192 |
+
# 相似品種獲得部分獎勵,但不超過80%的最高獎勵
|
193 |
+
bonus_score = min(0.8, similarity_score) * 0.95
|
194 |
+
|
195 |
+
# 計算最終分數
|
196 |
+
final_score = (
|
197 |
+
base_score * weights['base'] +
|
198 |
+
smart_score * weights['smart'] +
|
199 |
+
bonus_score * weights['bonus']
|
200 |
+
)
|
201 |
+
|
202 |
+
# 更新各項分數
|
203 |
+
scores = base_scores.copy()
|
204 |
+
|
205 |
+
# 如果是用戶指定品種,稍微提升各項基礎分數,但保持合理範圍
|
206 |
+
if is_preferred:
|
207 |
+
for key in scores:
|
208 |
+
if key != 'overall':
|
209 |
+
scores[key] = min(1.0, scores[key] * 1.1) # 最多提升10%
|
210 |
+
|
211 |
+
# 為相似品種調整分數
|
212 |
+
elif similarity_score > 0:
|
213 |
+
boost_factor = 1.0 + (similarity_score * 0.05) # 最多提升5%
|
214 |
+
for key in scores:
|
215 |
+
if key != 'overall':
|
216 |
+
scores[key] = min(0.95, scores[key] * boost_factor) # 確保不超過95%
|
217 |
+
|
218 |
+
return {
|
219 |
+
'final_score': round(final_score, 4),
|
220 |
+
'base_score': round(base_score, 4),
|
221 |
+
'bonus_score': round(bonus_score, 4),
|
222 |
+
'scores': {k: round(v, 4) for k, v in scores.items()}
|
223 |
+
}
|
224 |
+
|
225 |
+
def _calculate_health_score(self, breed_name: str) -> float:
|
226 |
+
"""計算品種的健康分數"""
|
227 |
+
if breed_name not in breed_health_info:
|
228 |
+
return 0.5
|
229 |
+
|
230 |
+
health_notes = breed_health_info[breed_name]['health_notes'].lower()
|
231 |
+
|
232 |
+
# 嚴重健康問題
|
233 |
+
severe_conditions = [
|
234 |
+
'cancer', 'cardiomyopathy', 'epilepsy', 'dysplasia',
|
235 |
+
'bloat', 'progressive', 'syndrome'
|
236 |
+
]
|
237 |
+
|
238 |
+
# 中等健康問題
|
239 |
+
moderate_conditions = [
|
240 |
+
'allergies', 'infections', 'thyroid', 'luxation',
|
241 |
+
'skin problems', 'ear'
|
242 |
+
]
|
243 |
+
|
244 |
+
severe_count = sum(1 for condition in severe_conditions if condition in health_notes)
|
245 |
+
moderate_count = sum(1 for condition in moderate_conditions if condition in health_notes)
|
246 |
+
|
247 |
+
health_score = 1.0
|
248 |
+
health_score -= (severe_count * 0.1)
|
249 |
+
health_score -= (moderate_count * 0.05)
|
250 |
+
|
251 |
+
# 特殊條件調整(根據用戶偏好)
|
252 |
+
if hasattr(self, 'user_preferences'):
|
253 |
+
if self.user_preferences.has_children:
|
254 |
+
if 'requires frequent' in health_notes or 'regular monitoring' in health_notes:
|
255 |
+
health_score *= 0.9
|
256 |
+
|
257 |
+
if self.user_preferences.health_sensitivity == 'high':
|
258 |
+
health_score *= 0.9
|
259 |
+
|
260 |
+
return max(0.3, min(1.0, health_score))
|
261 |
+
|
262 |
+
|
263 |
+
|
264 |
+
def _calculate_noise_similarity(self, breed1: str, breed2: str) -> float:
|
265 |
+
"""計算兩個品種的噪音相似度"""
|
266 |
+
noise_levels = {
|
267 |
+
'Low': 1,
|
268 |
+
'Moderate': 2,
|
269 |
+
'High': 3,
|
270 |
+
'Unknown': 2 # 默認為中等
|
271 |
+
}
|
272 |
+
|
273 |
+
noise1 = breed_noise_info.get(breed1, {}).get('noise_level', 'Unknown')
|
274 |
+
noise2 = breed_noise_info.get(breed2, {}).get('noise_level', 'Unknown')
|
275 |
+
|
276 |
+
# 獲取數值級別
|
277 |
+
level1 = noise_levels.get(noise1, 2)
|
278 |
+
level2 = noise_levels.get(noise2, 2)
|
279 |
+
|
280 |
+
# 計算差異並歸一化
|
281 |
+
difference = abs(level1 - level2)
|
282 |
+
similarity = 1.0 - (difference / 2) # 最大差異是2,所以除以2來歸一化
|
283 |
+
|
284 |
+
return similarity
|
285 |
+
|
286 |
+
def match_user_preference(self, description: str, top_n: int = 10) -> List[Dict]:
|
287 |
+
"""根據用戶描述匹配最適合的品種"""
|
288 |
+
preferred_breed = self._detect_breed_preference(description)
|
289 |
+
|
290 |
+
matches = []
|
291 |
+
if preferred_breed:
|
292 |
+
similar_breeds = self.find_similar_breeds(preferred_breed, top_n=top_n)
|
293 |
+
|
294 |
+
# 首先添加偏好品種
|
295 |
+
breed_info = next((breed for breed in self.dog_data if breed[1] == preferred_breed), None)
|
296 |
+
if breed_info:
|
297 |
+
health_score = self._calculate_health_score(preferred_breed)
|
298 |
+
noise_info = breed_noise_info.get(preferred_breed, {
|
299 |
+
"noise_level": "Unknown",
|
300 |
+
"noise_notes": "No noise information available"
|
301 |
+
})
|
302 |
+
|
303 |
+
# 偏好品種必定是最高分
|
304 |
+
matches.append({
|
305 |
+
'breed': preferred_breed,
|
306 |
+
'score': 1.0,
|
307 |
+
'is_preferred': True,
|
308 |
+
'similarity': 1.0,
|
309 |
+
'health_score': health_score,
|
310 |
+
'noise_level': noise_info['noise_level'],
|
311 |
+
'reason': "Directly matched your preferred breed"
|
312 |
+
})
|
313 |
+
|
314 |
+
# 添加相似品種
|
315 |
+
for breed_name, similarity in similar_breeds:
|
316 |
+
if breed_name != preferred_breed:
|
317 |
+
health_score = self._calculate_health_score(breed_name)
|
318 |
+
noise_info = breed_noise_info.get(breed_name, {
|
319 |
+
"noise_level": "Unknown",
|
320 |
+
"noise_notes": "No noise information available"
|
321 |
+
})
|
322 |
+
|
323 |
+
# 調整相似品種分數計算
|
324 |
+
base_similarity = similarity * 0.6
|
325 |
+
health_factor = health_score * 0.2
|
326 |
+
noise_factor = self._calculate_noise_similarity(preferred_breed, breed_name) * 0.2
|
327 |
+
|
328 |
+
# 確保相似品種分數不會超過偏好品種
|
329 |
+
final_score = min(0.95, base_similarity + health_factor + noise_factor)
|
330 |
+
|
331 |
+
matches.append({
|
332 |
+
'breed': breed_name,
|
333 |
+
'score': final_score,
|
334 |
+
'is_preferred': False,
|
335 |
+
'similarity': similarity,
|
336 |
+
'health_score': health_score,
|
337 |
+
'noise_level': noise_info['noise_level'],
|
338 |
+
'reason': f"Similar to {preferred_breed} in characteristics, health profile, and noise level"
|
339 |
+
})
|
340 |
+
else:
|
341 |
+
matches = self._general_matching(description, top_n)
|
342 |
+
|
343 |
+
return sorted(matches,
|
344 |
+
key=lambda x: (-int(x.get('is_preferred', False)),
|
345 |
+
-x['score'], # 降序排列
|
346 |
+
x['breed']))[:top_n]
|
347 |
+
|
348 |
+
def _detect_breed_preference(self, description: str) -> Optional[str]:
|
349 |
+
"""檢測用戶是否提到特定品種"""
|
350 |
+
description_lower = description.lower()
|
351 |
+
|
352 |
+
for breed_info in self.dog_data:
|
353 |
+
breed_name = breed_info[1]
|
354 |
+
normalized_breed = breed_name.lower().replace('_', ' ')
|
355 |
+
|
356 |
+
if any(phrase in description_lower for phrase in [
|
357 |
+
f"love {normalized_breed}",
|
358 |
+
f"like {normalized_breed}",
|
359 |
+
f"prefer {normalized_breed}",
|
360 |
+
f"want {normalized_breed}",
|
361 |
+
normalized_breed
|
362 |
+
]):
|
363 |
+
return breed_name
|
364 |
+
|
365 |
+
return None
|