DawnC commited on
Commit
81f717f
1 Parent(s): c94c3cc

Upload 2 files

Browse files
Files changed (2) hide show
  1. animal_detector.db +0 -0
  2. data_manager.py +642 -0
animal_detector.db ADDED
Binary file (213 kB). View file
 
data_manager.py ADDED
@@ -0,0 +1,642 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import sqlite3
3
+ from dataclasses import dataclass
4
+ from typing import List, Dict, Optional
5
+ import numpy as np
6
+ import random
7
+
8
+ def create_table():
9
+ conn = sqlite3.connect('animal_detector.db')
10
+ cursor = conn.cursor()
11
+
12
+ cursor.execute('''
13
+ CREATE TABLE IF NOT EXISTS AnimalCatalog (
14
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
15
+ Species TEXT NOT NULL,
16
+ Breed TEXT NOT NULL,
17
+ Size_Category TEXT,
18
+ Typical_Lifespan TEXT,
19
+ Temperament TEXT,
20
+ Care_Level TEXT,
21
+ Good_With_Children BOOLEAN,
22
+ Exercise_Needs TEXT,
23
+ Grooming_Needs TEXT,
24
+ Brief_Description TEXT
25
+ )
26
+ ''')
27
+
28
+ conn.commit()
29
+ cursor.close()
30
+ conn.close()
31
+
32
+ # 創建表
33
+ create_table()
34
+
35
+ def insert_dog_data():
36
+ conn = sqlite3.connect('animal_detector.db')
37
+ cursor = conn.cursor()
38
+
39
+ dog_data = [
40
+ ('Dog', 'Afghan_Hound', 'Large', '12-18 years', 'Independent, dignified, aloof', 'High', True, 'High', 'High', 'Known for their long, silky coat and regal appearance, Afghan Hounds are ancient sighthounds with a unique, elegant presence.'),
41
+ ('Dog', 'African_Hunting_Dog', 'Medium', '10-12 years', 'Social, intelligent, energetic', 'Very High', False, 'Very High', 'Low', 'Also called African Wild Dogs, these are not domestic dogs and are endangered in their native habitats.'),
42
+ ('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.'),
43
+ ('Dog', 'American_Staffordshire_Terrier', 'Medium', '12-16 years', 'Confident, good-natured, courageous', 'Moderate', True, 'High', 'Low', 'Often confused with Pit Bulls, Am Staffs are strong, muscular dogs with a gentle and loving nature.'),
44
+ ('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.'),
45
+ ('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.'),
46
+ ('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.'),
47
+ ('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.'),
48
+ ('Dog', 'Blenheim_Spaniel', 'Small', '12-14 years', 'Affectionate, gentle, lively', 'Moderate', True, 'Moderate', 'High', 'A color variety of the Cavalier King Charles Spaniel, known for their red and white coat and friendly nature.'),
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', 'Small but tough terriers with an otter-like head, known for their friendly and adaptable nature.'),
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', 'Distinguished from Pembroke Welsh Corgis by their long tail, Cardigans are intelligent herding dogs with a fox-like appearance.'),
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', '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.'),
59
+ ('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.'),
60
+ ('Dog', 'English_Foxhound', 'Medium', '10-13 years', 'Friendly, active, gentle', 'High', True, 'Very High', 'Low', 'Athletic, pack-oriented hounds originally bred for fox hunting in England. Known for their stamina, melodious voice, and strong hunting instincts.'),
61
+ ('Dog', 'English_Setter', 'Large', '10-12 years', 'Gentle, friendly, placid', 'High', True, 'High', 'High', 'Known for their speckled coat or "belton" markings, English Setters are elegant bird dogs and affectionate companions.'),
62
+ ('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.'),
63
+ ('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.'),
64
+ ('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.'),
65
+ ('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.'),
66
+ ('Dog', 'German_Shepherd', 'Large', '10-13 years', 'Confident, courageous, smart', 'High', True, 'High', 'Moderate', 'Versatile working dogs, German Shepherds excel in various roles from police work to family protection.'),
67
+ ('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.'),
68
+ ('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.'),
69
+ ('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.'),
70
+ ('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.'),
71
+ ('Dog', 'Greater_Swiss_Mountain_dog', 'Large', '8-11 years', 'Faithful, alert, vigilant', 'Moderate', True, 'Moderate', 'Low', 'Large, strong working dogs with a tricolor coat, Swissies are gentle giants with a calm temperament.'),
72
+ ('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.'),
73
+ ('Dog', 'Irish_Setter', 'Large', '11-15 years', 'Outgoing, sweet-tempered, active', 'High', True, 'High', 'High', 'Recognizable by their rich red coat, Irish Setters are energetic and playful dogs that love family life.'),
74
+ ('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.'),
75
+ ('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.'),
76
+ ('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.'),
77
+ ('Dog', 'Italian_Greyhound', 'Small', '12-15 years', 'Sensitive, alert, playful', 'Moderate', False, 'Moderate', 'Low', 'Miniature sighthounds known for their elegant appearance and affectionate nature, Italian Greyhounds make excellent companion dogs.'),
78
+ ('Dog', 'Japanese_Spaniel', 'Small', '10-12 years', 'Charming, noble, affectionate', 'Moderate', False, 'Low', 'High', 'Also known as the Japanese Chin, these small companion dogs have a distinctive flat face and were once favorites of Japanese nobility.'),
79
+ ('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.'),
80
+ ('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.'),
81
+ ('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.'),
82
+ ('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.'),
83
+ ('Dog', 'Lhasa', 'Small', '12-15 years', 'Confident, smart, comical', 'High', False, 'Low', 'High', 'Lhasa Apsos are small but sturdy dogs with a long, flowing coat. They were originally bred as indoor sentinel dogs in Buddhist monasteries.'),
84
+ ('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.'),
85
+ ('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.'),
86
+ ('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.'),
87
+ ('Dog', 'Norfolk_Terrier', 'Small', '12-15 years', 'Fearless, spirited, companionable', 'Moderate', True, 'Moderate', 'Moderate', 'Small, sturdy terriers with a wiry coat, known for their playful and affectionate nature.'),
88
+ ('Dog', 'Norwegian_Elkhound', 'Medium', '12-15 years', 'Bold, playful, loyal', 'High', True, 'High', 'High', 'Ancient Nordic breed known for their silver-gray coat and curled tail, originally used for hunting moose and other large game.'),
89
+ ('Dog', 'Norwich_Terrier', 'Small', '12-15 years', 'Fearless, loyal, affectionate', 'Moderate', True, 'Moderate', 'Moderate', 'One of the smallest terriers, Norwich Terriers are hardy, fearless, and affectionate companions.'),
90
+ ('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.'),
91
+ ('Dog', 'Pekinese', 'Small', '12-14 years', 'Affectionate, loyal, regal in manner', 'Moderate', False, 'Low', 'High', 'Also spelled Pekingese, these small dogs with flat faces and long coats were once sacred to Chinese royalty.'),
92
+ ('Dog', 'Pembroke', 'Small', '12-15 years', 'Affectionate, intelligent, outgoing', 'Moderate', True, 'Moderate', 'Moderate', 'Known for their short legs and long bodies, Pembroke Welsh Corgis are herding dogs favored by the British royal family.'),
93
+ ('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.'),
94
+ ('Dog', 'Rhodesian_Ridgeback', 'Large', '10-12 years', 'Dignified, intelligent, strong-willed', 'Moderate', True, 'High', 'Low', 'Large, muscular dogs known for the ridge of hair along their backs, originally bred to hunt lions in Africa.'),
95
+ ('Dog', 'Rottweiler', 'Large', '8-10 years', 'Loyal, loving, confident guardian', 'High', True, 'High', 'Low', 'Powerful and protective, Rottweilers are excellent guard dogs but also loving family companions when well-trained.'),
96
+ ('Dog', 'Saint_Bernard', 'Giant', '8-10 years', 'Gentle, patient, friendly', 'High', True, 'Moderate', 'High', 'Known for their massive size and gentle nature, Saint Bernards were originally bred for rescue work in the Swiss Alps.'),
97
+ ('Dog', 'Saluki', 'Large', '12-14 years', 'Gentle, dignified, independent-minded', 'High', True, 'High', 'Low', 'Ancient sighthounds known for their grace and speed, Salukis have a distinctive feathered coat and ears.'),
98
+ ('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.'),
99
+ ('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.'),
100
+ ('Dog', 'Scottish_Deerhound', 'Large', '8-11 years', 'Gentle, dignified, polite', 'High', True, 'High', 'Moderate', 'Large, wiry-coated sighthounds resembling Greyhounds, known for their gentle nature and hunting ability.'),
101
+ ('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.'),
102
+ ('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.'),
103
+ ('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.'),
104
+ ('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.'),
105
+ ('Dog', 'Staffordshire_Bullterrier', 'Medium', '12-14 years', 'Courageous, intelligent, loyal', 'Moderate', True, 'High', 'Low', 'Strong, muscular terriers known for their courage and affectionate nature, especially with children.'),
106
+ ('Dog', 'Sussex_Spaniel', 'Medium', '11-13 years', 'Calm, friendly, merry', 'Moderate', True, 'Moderate', 'Moderate', 'Rare breed of spaniel known for their golden-liver coat and low-set body, originally bred for hunting.'),
107
+ ('Dog', 'Tibetan_Mastiff', 'Large', '10-12 years', 'Independent, reserved, intelligent', 'High', False, 'Moderate', 'High', 'Ancient guardian breed known for their massive size and thick coat, Tibetan Mastiffs are independent and protective.'),
108
+ ('Dog', 'Tibetan_Terrier', 'Medium', '12-15 years', 'Affectionate, sensitive, clever', 'High', True, 'Moderate', 'High', 'Not actually terriers, these dogs were bred in Tibet and are known for their profuse, long coat.'),
109
+ ('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.'),
110
+ ('Dog', 'Weimaraner', 'Large', '10-13 years', 'Friendly, fearless, obedient', 'High', True, 'High', 'Low', 'Known as the "Gray Ghost," Weimaraners are athletic and intelligent dogs with a distinctive silver-gray coat.'),
111
+ ('Dog', 'Welsh_Springer_Spaniel', 'Medium', '12-15 years', 'Active, loyal, affectionate', 'High', True, 'High', 'Moderate', 'Similar to English Springers but with a distinctive red and white coat, Welsh Springers are devoted and energetic.'),
112
+ ('Dog', 'West_Highland_White_Terrier', 'Small', '12-16 years', 'Friendly, hardy, confident', 'Moderate', True, 'Moderate', 'High', 'Commonly known as "Westies," these white terriers are friendly and sturdy with a bright personality.'),
113
+ ('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.'),
114
+ ('Dog', 'Affenpinscher', 'Small', '12-15 years', 'Confident, amusing, stubborn', 'Moderate', False, 'Moderate', 'Moderate', 'Small terrier-like toys known as "monkey dogs" due to their distinctive facial appearance.'),
115
+ ('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.'),
116
+ ('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.'),
117
+ ('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.'),
118
+ ('Dog', 'Black-and-Tan_Coonhound', 'Large', '10-12 years', 'Even-tempered, easygoing, friendly', 'Moderate', True, 'High', 'Low', 'Large, powerful scent hounds known for their distinctive black and tan coloration and melodious bay.'),
119
+ ('Dog', 'Bloodhound', 'Large', '10-12 years', 'Gentle, patient, stubborn', 'High', True, 'Moderate', 'Moderate', 'Known for their exceptional sense of smell, Bloodhounds are large, gentle dogs often used in tracking.'),
120
+ ('Dog', 'Bluetick', 'Large', '11-12 years', 'Friendly, intelligent, active', 'Moderate', True, 'High', 'Low', 'Known for their mottled blue coat, Bluetick Coonhounds are skilled hunting dogs with a keen sense of smell and a melodious howl.'),
121
+ ('Dog', 'Borzoi', 'Large', '10-12 years', 'Quiet, gentle, athletic', 'High', True, 'Moderate', 'High', 'Also known as Russian Wolfhounds, Borzois are elegant sighthounds known for their silky coat and graceful demeanor.'),
122
+ ('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.'),
123
+ ('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.'),
124
+ ('Dog', 'Bull_mastiff', 'Large', '8-10 years', 'Affectionate, loyal, quiet', 'Moderate', True, 'Moderate', 'Low', 'Large, powerful dogs originally bred to guard estates, Bullmastiffs are gentle giants with a calm demeanor.'),
125
+ ('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.'),
126
+ ('Dog', 'Chow', 'Medium', '8-12 years', 'Aloof, loyal, quiet', 'High', False, 'Low', 'High', 'Ancient Chinese breed known for their lion-like mane and blue-black tongues. Independent and dignified, they make excellent watchdogs but require early socialization.'),
127
+ ('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.'),
128
+ ('Dog', 'Cocker_Spaniel', 'Small', '10-14 years', 'Gentle, smart, happy', 'High', True, 'Moderate', 'High', 'Known for their long, silky ears and expressive eyes, Cockers are popular family dogs with a merry disposition.'),
129
+ ('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.'),
130
+ ('Dog', 'Curly-Coated_Retriever', 'Large', '10-12 years', 'Confident, independent, intelligent', 'Moderate', True, 'High', 'Low', 'Sporting dogs with a distinctive curly coat, known for their excellent swimming and retrieving abilities.'),
131
+ ('Dog', 'Dhole', 'Medium', '10-13 years', 'Social, intelligent, athletic', 'High', False, 'High', 'Low', 'Also known as the Asiatic wild dog, Dholes are not typically kept as pets but are important in Asian ecosystems.'),
132
+ ('Dog', 'Dingo', 'Medium', '10-13 years', 'Independent, intelligent, alert', 'High', False, 'High', 'Low', 'Native wild dogs of Australia, dingoes are not typically kept as pets and are important to the Australian ecosystem.'),
133
+ ('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.'),
134
+ ('Dog', 'Giant_Schnauzer', 'Large', '10-12 years', 'Loyal, intelligent, powerful', 'High', True, 'High', 'High', 'Large and powerful, Giant Schnauzers were originally bred as working dogs and require plenty of exercise.'),
135
+ ('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.'),
136
+ ('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.'),
137
+ ('Dog', 'Keeshond', 'Medium', '12-15 years', 'Friendly, lively, outgoing', 'Moderate', True, 'Moderate', 'High', 'Distinctive "spectacles" marking around their eyes, Keeshonds are fluffy, fox-like dogs known for their friendly and affectionate nature.'),
138
+ ('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.'),
139
+ ('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.'),
140
+ ('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.'),
141
+ ('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.'),
142
+ ('Dog', 'Malinois', 'Medium', '12-14 years', 'Confident, smart, hardworking', 'High', True, 'High', 'Moderate', 'One of four varieties of Belgian Shepherd, known for their intelligence and use in police and military work.'),
143
+ ('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.'),
144
+ ('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.'),
145
+ ('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.'),
146
+ ('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.'),
147
+ ('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.'),
148
+ ('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.'),
149
+ ('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.'),
150
+ ('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.'),
151
+ ('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.'),
152
+ ('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.'),
153
+ ('Dog', 'Standard_Poodle', 'Large', '10-18 years', 'Intelligent, active, dignified', 'High', True, 'High', 'High', 'Highly intelligent and elegant dogs, known for their hypoallergenic coat and versatility in various dog sports.'),
154
+ ('Dog', 'Standard_Schnauzer', 'Medium', '13-16 years', 'Friendly, intelligent, obedient', 'High', True, 'High', 'High', 'The original Schnauzer breed, known for their distinctive beard and eyebrows and versatile working abilities.'),
155
+ ('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.'),
156
+ ('Dog', 'Toy_Terrier', 'Small', '12-16 years', 'Lively, bold, intelligent', 'Moderate', False, 'Moderate', 'Low', 'A general term for small terrier breeds, often referring to breeds like the English Toy Terrier or Toy Fox Terrier.'),
157
+ ('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.'),
158
+ ('Dog', 'Whippet', 'Medium', '12-15 years', 'Gentle, affectionate, quiet', 'Low', True, 'High', 'Low', 'Slender, athletic sighthounds known for their speed - capable of reaching 35mph. Despite high exercise needs, they are calm indoor companions and excellent apartment dogs.'),
159
+ ('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.'),
160
+ ]
161
+
162
+ cursor.executemany('''
163
+ INSERT INTO AnimalCatalog (Species, Breed, Size_Category, Typical_Lifespan, Temperament, Care_Level, Good_With_Children, Exercise_Needs, Grooming_Needs, Brief_Description)
164
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
165
+ ''', dog_data)
166
+
167
+ conn.commit()
168
+ cursor.close()
169
+ conn.close()
170
+
171
+ def get_dog_description(breed):
172
+ try:
173
+ conn = sqlite3.connect('animal_detector.db')
174
+ cursor = conn.cursor()
175
+
176
+ breed_name = breed.split('(')[0].strip()
177
+
178
+ cursor.execute("""
179
+ SELECT * FROM AnimalCatalog
180
+ WHERE Breed = ? OR Breed LIKE ? OR Breed LIKE ?
181
+ """, (breed_name, f"{breed_name}%", f"%{breed_name}"))
182
+
183
+ result = cursor.fetchone()
184
+
185
+ cursor.close()
186
+ conn.close()
187
+
188
+ if result:
189
+ # 標準化運動需求值
190
+ exercise_needs = result[8]
191
+ normalized_exercise = exercise_needs.strip().title()
192
+ if normalized_exercise not in ["Very High", "High", "Moderate", "Low"]:
193
+ normalized_exercise = "High" # 預設值
194
+
195
+ description = {
196
+ "Breed": result[2],
197
+ "Size": result[3],
198
+ "Lifespan": result[4],
199
+ "Temperament": result[5],
200
+ "Care Level": result[6],
201
+ "Good with Children": "Yes" if result[7] else "No",
202
+ "Exercise Needs": normalized_exercise,
203
+ "Grooming Needs": result[9],
204
+ "Description": result[10]
205
+ }
206
+ return description
207
+ else:
208
+ print(f"No data found for breed: {breed_name}")
209
+ return None
210
+
211
+ except Exception as e:
212
+ print(f"Error in get_dog_description: {str(e)}")
213
+ return None
214
+
215
+ insert_dog_data()
216
+
217
+
218
+ @dataclass
219
+ class UserPreferences:
220
+ """使用者偏好設定的資料結構"""
221
+ living_space: str # "apartment", "house_small", "house_large"
222
+ exercise_time: int # minutes per day
223
+ grooming_commitment: str # "low", "medium", "high"
224
+ experience_level: str # "beginner", "intermediate", "advanced"
225
+ has_children: bool
226
+ noise_tolerance: str # "low", "medium", "high"
227
+ space_for_play: bool
228
+ other_pets: bool
229
+ climate: str # "cold", "moderate", "hot"
230
+
231
+
232
+ def calculate_compatibility_score(breed_info: dict, user_prefs: UserPreferences) -> dict:
233
+ """計算品種與使用者條件的相容性分數"""
234
+ scores = {}
235
+ try:
236
+ # 1. 空間相容性計算
237
+ def calculate_space_score(size, living_space, has_yard):
238
+ base_scores = {
239
+ "Small": {"apartment": 0.95, "house_small": 1.0, "house_large": 0.90},
240
+ "Medium": {"apartment": 0.65, "house_small": 0.90, "house_large": 1.0},
241
+ "Large": {"apartment": 0.35, "house_small": 0.75, "house_large": 1.0},
242
+ "Giant": {"apartment": 0.15, "house_small": 0.55, "house_large": 1.0}
243
+ }
244
+
245
+ base_score = base_scores.get(size, base_scores["Medium"])[living_space]
246
+ adjustments = 0
247
+
248
+ # 特殊情況調整
249
+ if living_space == "apartment":
250
+ if size == "Small":
251
+ adjustments += 0.05
252
+ elif size in ["Large", "Giant"]:
253
+ adjustments -= 0.15
254
+
255
+ if has_yard and living_space in ["house_small", "house_large"]:
256
+ adjustments += 0.05
257
+
258
+ return min(1.0, max(0, base_score + adjustments))
259
+
260
+ # 2. 運動相容性計算
261
+ def calculate_exercise_score(breed_exercise_needs, user_exercise_time):
262
+ exercise_needs = {
263
+ 'VERY HIGH': 120,
264
+ 'HIGH': 90,
265
+ 'MODERATE': 60,
266
+ 'LOW': 30,
267
+ 'VARIES': 60
268
+ }
269
+
270
+ breed_need = exercise_needs.get(breed_exercise_needs.strip().upper(), 60)
271
+ difference = abs(user_exercise_time - breed_need) / breed_need
272
+
273
+ if difference == 0:
274
+ return 1.0
275
+ elif difference <= 0.2:
276
+ return 0.95
277
+ elif difference <= 0.4:
278
+ return 0.85
279
+ elif difference <= 0.6:
280
+ return 0.70
281
+ elif difference <= 0.8:
282
+ return 0.50
283
+ else:
284
+ return 0.30
285
+
286
+ # 3. 美容需求計算
287
+ def calculate_grooming_score(breed_grooming_needs, user_commitment, breed_size):
288
+ base_scores = {
289
+ "High": {"low": 0.3, "medium": 0.7, "high": 1.0},
290
+ "Moderate": {"low": 0.5, "medium": 0.9, "high": 1.0},
291
+ "Low": {"low": 1.0, "medium": 0.95, "high": 0.9}
292
+ }
293
+
294
+ base_score = base_scores.get(breed_grooming_needs, base_scores["Moderate"])[user_commitment]
295
+
296
+ if breed_size == "Large" and user_commitment == "low":
297
+ base_score *= 0.80
298
+ elif breed_size == "Giant" and user_commitment == "low":
299
+ base_score *= 0.70
300
+
301
+ return base_score
302
+
303
+ # 4. 經驗等級計算
304
+ def calculate_experience_score(care_level, user_experience, temperament):
305
+ base_scores = {
306
+ "High": {"beginner": 0.3, "intermediate": 0.7, "advanced": 1.0},
307
+ "Moderate": {"beginner": 0.6, "intermediate": 0.9, "advanced": 1.0},
308
+ "Low": {"beginner": 0.9, "intermediate": 1.0, "advanced": 1.0}
309
+ }
310
+
311
+ score = base_scores.get(care_level, base_scores["Moderate"])[user_experience]
312
+
313
+ temperament_lower = temperament.lower()
314
+ if user_experience == "beginner":
315
+ if any(trait in temperament_lower for trait in ['stubborn', 'independent', 'intelligent']):
316
+ score *= 0.80
317
+ if any(trait in temperament_lower for trait in ['easy', 'gentle', 'friendly']):
318
+ score *= 1.15
319
+
320
+ return min(1.0, score)
321
+
322
+ # 計算各項分數
323
+ scores['space'] = calculate_space_score(
324
+ breed_info['Size'],
325
+ user_prefs.living_space,
326
+ user_prefs.space_for_play
327
+ )
328
+
329
+ scores['exercise'] = calculate_exercise_score(
330
+ breed_info.get('Exercise Needs', 'Moderate'),
331
+ user_prefs.exercise_time
332
+ )
333
+
334
+ scores['grooming'] = calculate_grooming_score(
335
+ breed_info.get('Grooming Needs', 'Moderate'),
336
+ user_prefs.grooming_commitment.lower(),
337
+ breed_info['Size']
338
+ )
339
+
340
+ scores['experience'] = calculate_experience_score(
341
+ breed_info.get('Care Level', 'Moderate'),
342
+ user_prefs.experience_level,
343
+ breed_info.get('Temperament', '')
344
+ )
345
+
346
+ # 基礎權重
347
+ weights = {
348
+ 'space': 0.30,
349
+ 'exercise': 0.25,
350
+ 'grooming': 0.15,
351
+ 'experience': 0.30
352
+ }
353
+
354
+ # 基礎分數計算
355
+ base_score = sum(score * weights[category]
356
+ for category, score in scores.items()
357
+ if category != 'overall')
358
+
359
+ # 根據性格特徵調整
360
+ temperament = breed_info.get('Temperament', '').lower()
361
+ personality_bonus = 0
362
+
363
+ positive_traits = ['friendly', 'gentle', 'affectionate']
364
+ negative_traits = ['aggressive', 'stubborn', 'dominant']
365
+
366
+ personality_bonus += sum(0.02 for trait in positive_traits if trait in temperament)
367
+ personality_bonus -= sum(0.02 for trait in negative_traits if trait in temperament)
368
+
369
+ adjusted_score = base_score + personality_bonus
370
+
371
+ # 最終分數,加入微小隨機變化
372
+ final_score = min(1.0, max(0, adjusted_score + random.uniform(-0.005, 0.005)))
373
+ scores['overall'] = round(final_score, 4)
374
+
375
+ return scores
376
+
377
+ except Exception as e:
378
+ print(f"Error in calculate_compatibility_score: {str(e)}")
379
+ return {
380
+ 'space': 0.5,
381
+ 'exercise': 0.5,
382
+ 'grooming': 0.5,
383
+ 'experience': 0.5,
384
+ 'overall': 0.5
385
+ }
386
+
387
+ def get_breed_recommendations(user_prefs: UserPreferences, top_n: int = 5) -> List[Dict]:
388
+ """基於使用者偏好推薦狗品種"""
389
+ recommendations = []
390
+ seen_breeds = set()
391
+
392
+ try:
393
+ conn = sqlite3.connect('animal_detector.db')
394
+ cursor = conn.cursor()
395
+ cursor.execute("SELECT Breed FROM AnimalCatalog")
396
+ all_breeds = cursor.fetchall()
397
+ conn.close()
398
+
399
+ # 收集所有品種的評分
400
+ for breed_tuple in all_breeds:
401
+ breed = breed_tuple[0]
402
+ base_breed = breed.split('(')[0].strip()
403
+
404
+ if base_breed in seen_breeds:
405
+ continue
406
+ seen_breeds.add(base_breed)
407
+
408
+ breed_info = get_dog_description(breed)
409
+ if not isinstance(breed_info, dict):
410
+ continue
411
+
412
+ # 計算基礎相容性分數
413
+ scores = calculate_compatibility_score(breed_info, user_prefs)
414
+
415
+ # 計算額外因素
416
+ extra_score = calculate_breed_bonus(breed_info, user_prefs)
417
+
418
+ final_score = min(1.0, scores['overall'] * (1 + extra_score))
419
+
420
+ recommendations.append({
421
+ 'breed': breed,
422
+ 'overall_score': final_score,
423
+ 'scores': scores,
424
+ 'info': breed_info
425
+ })
426
+
427
+ # 排序並應用排名調整
428
+ recommendations.sort(key=lambda x: -x['overall_score'])
429
+
430
+ # 確保排名間有足夠差距
431
+ final_recommendations = []
432
+ for i, rec in enumerate(recommendations):
433
+ if i >= top_n:
434
+ break
435
+
436
+ # 根據排名位置調整分數
437
+ rank_adjustment = (top_n - i) * 0.01
438
+
439
+ # 第一名保持原分,其他依序遞減
440
+ if i > 0:
441
+ prev_score = final_recommendations[-1]['overall_score']
442
+ min_gap = 0.005 * (top_n - i) # 確保最小差距
443
+ new_score = min(rec['overall_score'], prev_score - min_gap)
444
+ rec['overall_score'] = round(new_score, 4)
445
+
446
+ final_recommendations.append(rec)
447
+
448
+ # 印出結果以供驗證
449
+ print("\nFinal Rankings:")
450
+ for i, rec in enumerate(final_recommendations, 1):
451
+ print(f"#{i} {rec['breed']}: {rec['overall_score']:.4f}")
452
+
453
+ return final_recommendations
454
+
455
+ except Exception as e:
456
+ print(f"Error in get_breed_recommendations: {str(e)}")
457
+ return []
458
+
459
+ def calculate_breed_bonus(breed_info: dict, user_prefs: UserPreferences) -> float:
460
+ """計算品種額外加分"""
461
+ bonus = 0.0
462
+
463
+ # 壽命加分
464
+ try:
465
+ lifespan = breed_info.get('Lifespan', '10-12 years')
466
+ years = [int(x) for x in lifespan.split('-')[0].split()[0:1]]
467
+ longevity_bonus = min(0.05, (max(years) - 10) * 0.01)
468
+ bonus += longevity_bonus
469
+ except:
470
+ pass
471
+
472
+ # 性格特徵加分
473
+ temperament = breed_info.get('Temperament', '').lower()
474
+ if user_prefs.has_children:
475
+ if 'gentle' in temperament or 'patient' in temperament:
476
+ bonus += 0.03
477
+
478
+ # 適應性加分
479
+ if breed_info.get('Size') == "Small" and user_prefs.living_space == "apartment":
480
+ bonus += 0.02
481
+
482
+ return bonus
483
+
484
+ def calculate_additional_factors(breed_info: dict, user_prefs: UserPreferences) -> dict:
485
+ """計算額外的排序因素"""
486
+ factors = {
487
+ 'versatility': 0.0,
488
+ 'health_score': 0.0,
489
+ 'adaptability': 0.0
490
+ }
491
+
492
+ # 計算多功能性分數
493
+ temperament = breed_info.get('Temperament', '').lower()
494
+ versatile_traits = ['intelligent', 'adaptable', 'versatile', 'trainable']
495
+ factors['versatility'] = sum(trait in temperament for trait in versatile_traits) / len(versatile_traits)
496
+
497
+ # 計算健康分數(基於預期壽命)
498
+ lifespan = breed_info.get('Lifespan', '10-12 years')
499
+ try:
500
+ years = [int(x) for x in lifespan.split('-')[0].split()[0:1]]
501
+ factors['health_score'] = min(1.0, max(years) / 15) # 標準化到0-1範圍
502
+ except:
503
+ factors['health_score'] = 0.5 # 預設值
504
+
505
+ # 計算適應性分數
506
+ size = breed_info.get('Size', 'Medium')
507
+ factors['adaptability'] = {
508
+ 'Small': 0.9,
509
+ 'Medium': 0.7,
510
+ 'Large': 0.5,
511
+ 'Giant': 0.3
512
+ }.get(size, 0.5)
513
+
514
+ return factors
515
+
516
+ def format_recommendation_html(recommendations: List[Dict]) -> str:
517
+ """將推薦結果格式化為HTML"""
518
+ html_content = "<div class='recommendations-container'>"
519
+
520
+ for i, rec in enumerate(recommendations, 1):
521
+ breed = rec['breed']
522
+ scores = rec['scores']
523
+ info = rec['info']
524
+
525
+ html_content += f"""
526
+ <div class="dog-info-card recommendation-card">
527
+ <div class="breed-info">
528
+ <h2 class="section-title">
529
+ <span class="icon">🏆</span> #{i} {breed.replace('_', ' ')}
530
+ <span class="score-badge">
531
+ Overall Match: {scores['overall']*100:.1f}%
532
+ </span>
533
+ </h2>
534
+
535
+ <div class="compatibility-scores">
536
+ <div class="score-item">
537
+ <span class="label">Space Compatibility:</span>
538
+ <div class="progress-bar">
539
+ <div class="progress" style="width: {scores['space']*100}%"></div>
540
+ </div>
541
+ <span class="percentage">{scores['space']*100:.1f}%</span>
542
+ </div>
543
+
544
+ <div class="score-item">
545
+ <span class="label">Exercise Match:</span>
546
+ <div class="progress-bar">
547
+ <div class="progress" style="width: {scores['exercise']*100}%"></div>
548
+ </div>
549
+ <span class="percentage">{scores['exercise']*100:.1f}%</span>
550
+ </div>
551
+
552
+ <div class="score-item">
553
+ <span class="label">Grooming Match:</span>
554
+ <div class="progress-bar">
555
+ <div class="progress" style="width: {scores['grooming']*100}%"></div>
556
+ </div>
557
+ <span class="percentage">{scores['grooming']*100:.1f}%</span>
558
+ </div>
559
+
560
+ <div class="score-item">
561
+ <span class="label">Experience Match:</span>
562
+ <div class="progress-bar">
563
+ <div class="progress" style="width: {scores['experience']*100}%"></div>
564
+ </div>
565
+ <span class="percentage">{scores['experience']*100:.1f}%</span>
566
+ </div>
567
+ </div>
568
+
569
+ <div class="breed-details-section">
570
+ <h3 class="subsection-title">
571
+ <span class="icon">📋</span> Breed Details
572
+ </h3>
573
+ <div class="details-grid">
574
+ <div class="detail-item">
575
+ <span class="tooltip">
576
+ <span class="icon">📏</span>
577
+ <span class="label">Size:</span>
578
+ <span class="tooltip-icon">ⓘ</span>
579
+ <span class="tooltip-text">
580
+ <strong>Size Categories:</strong><br>
581
+ • Small: Under 20 pounds<br>
582
+ • Medium: 20-60 pounds<br>
583
+ • Large: Over 60 pounds
584
+ </span>
585
+ <span class="value">{info['Size']}</span>
586
+ </span>
587
+ </div>
588
+
589
+ <div class="detail-item">
590
+ <span class="tooltip">
591
+ <span class="icon">🏃</span>
592
+ <span class="label">Exercise Needs:</span>
593
+ <span class="tooltip-icon">ⓘ</span>
594
+ <span class="tooltip-text">
595
+ <strong>Exercise Needs:</strong><br>
596
+ • Low: Short walks<br>
597
+ • Moderate: 1-2 hours daily<br>
598
+ • High: 2+ hours daily<br>
599
+ • Very High: Constant activity
600
+ </span>
601
+ <span class="value">{info['Exercise Needs']}</span>
602
+ </span>
603
+ </div>
604
+
605
+ <div class="detail-item">
606
+ <span class="tooltip">
607
+ <span class="icon">👨‍👩‍👧‍👦</span>
608
+ <span class="label">Good with Children:</span>
609
+ <span class="tooltip-icon">ⓘ</span>
610
+ <span class="tooltip-text">
611
+ <strong>Child Compatibility:</strong><br>
612
+ • Yes: Excellent with kids<br>
613
+ • Moderate: Good with older children<br>
614
+ • No: Better for adult households
615
+ </span>
616
+ <span class="value">{info['Good with Children']}</span>
617
+ </span>
618
+ </div>
619
+ </div>
620
+ </div>
621
+
622
+ <div class="description-section">
623
+ <h3 class="subsection-title">
624
+ <span class="icon">📝</span> Description
625
+ </h3>
626
+ <p class="description-text">{info.get('Description', '')}</p>
627
+ </div>
628
+
629
+ <div class="action-section">
630
+ <a href="https://www.akc.org/dog-breeds/{breed.lower().replace('_', '-')}/"
631
+ target="_blank"
632
+ class="akc-button">
633
+ <span class="icon">🌐</span>
634
+ Learn more about {breed.replace('_', ' ')} on AKC website
635
+ </a>
636
+ </div>
637
+ </div>
638
+ </div>
639
+ """
640
+
641
+ html_content += "</div>"
642
+ return html_content