Spaces:
Running
on
Zero
Running
on
Zero
import os | |
import numpy as np | |
import torch | |
import torch.nn as nn | |
import gradio as gr | |
from torchvision.models import efficientnet_v2_m, EfficientNet_V2_M_Weights | |
from torchvision.ops import nms, box_iou | |
import torch.nn.functional as F | |
from torchvision import transforms | |
from PIL import Image, ImageDraw, ImageFont, ImageFilter | |
from data_manager import get_dog_description, UserPreferences, get_breed_recommendations, format_recommendation_html | |
from history_manager import UserHistoryManager | |
from search_history import create_history_tab | |
from styles import get_css_styles | |
from breed_detection import create_detection_tab | |
from breed_comparison import create_comparison_tab | |
from breed_recommendation import create_recommendation_tab | |
from urllib.parse import quote | |
from ultralytics import YOLO | |
import asyncio | |
import traceback | |
model_yolo = YOLO('yolov8l.pt') | |
history_manager = UserHistoryManager() | |
dog_breeds = ["Afghan_Hound", "African_Hunting_Dog", "Airedale", "American_Staffordshire_Terrier", | |
"Appenzeller", "Australian_Terrier", "Bedlington_Terrier", "Bernese_Mountain_Dog", | |
"Blenheim_Spaniel", "Border_Collie", "Border_Terrier", "Boston_Bull", "Bouvier_Des_Flandres", | |
"Brabancon_Griffon", "Brittany_Spaniel", "Cardigan", "Chesapeake_Bay_Retriever", | |
"Chihuahua", "Dandie_Dinmont", "Doberman", "English_Foxhound", "English_Setter", | |
"English_Springer", "EntleBucher", "Eskimo_Dog", "French_Bulldog", "German_Shepherd", | |
"German_Short-Haired_Pointer", "Gordon_Setter", "Great_Dane", "Great_Pyrenees", | |
"Greater_Swiss_Mountain_Dog", "Ibizan_Hound", "Irish_Setter", "Irish_Terrier", | |
"Irish_Water_Spaniel", "Irish_Wolfhound", "Italian_Greyhound", "Japanese_Spaniel", | |
"Kerry_Blue_Terrier", "Labrador_Retriever", "Lakeland_Terrier", "Leonberg", "Lhasa", | |
"Maltese_Dog", "Mexican_Hairless", "Newfoundland", "Norfolk_Terrier", "Norwegian_Elkhound", | |
"Norwich_Terrier", "Old_English_Sheepdog", "Pekinese", "Pembroke", "Pomeranian", | |
"Rhodesian_Ridgeback", "Rottweiler", "Saint_Bernard", "Saluki", "Samoyed", | |
"Scotch_Terrier", "Scottish_Deerhound", "Sealyham_Terrier", "Shetland_Sheepdog", | |
"Shih-Tzu", "Siberian_Husky", "Staffordshire_Bullterrier", "Sussex_Spaniel", | |
"Tibetan_Mastiff", "Tibetan_Terrier", "Walker_Hound", "Weimaraner", | |
"Welsh_Springer_Spaniel", "West_Highland_White_Terrier", "Yorkshire_Terrier", | |
"Affenpinscher", "Basenji", "Basset", "Beagle", "Black-and-Tan_Coonhound", "Bloodhound", | |
"Bluetick", "Borzoi", "Boxer", "Briard", "Bull_Mastiff", "Cairn", "Chow", "Clumber", | |
"Cocker_Spaniel", "Collie", "Curly-Coated_Retriever", "Dhole", "Dingo", | |
"Flat-Coated_Retriever", "Giant_Schnauzer", "Golden_Retriever", "Groenendael", "Keeshond", | |
"Kelpie", "Komondor", "Kuvasz", "Malamute", "Malinois", "Miniature_Pinscher", | |
"Miniature_Poodle", "Miniature_Schnauzer", "Otterhound", "Papillon", "Pug", "Redbone", | |
"Schipperke", "Silky_Terrier", "Soft-Coated_Wheaten_Terrier", "Standard_Poodle", | |
"Standard_Schnauzer", "Toy_Poodle", "Toy_Terrier", "Vizsla", "Whippet", | |
"Wire-Haired_Fox_Terrier"] | |
class MultiHeadAttention(nn.Module): | |
def __init__(self, in_dim, num_heads=8): | |
super().__init__() | |
self.num_heads = num_heads | |
self.head_dim = max(1, in_dim // num_heads) | |
self.scaled_dim = self.head_dim * num_heads | |
self.fc_in = nn.Linear(in_dim, self.scaled_dim) | |
self.query = nn.Linear(self.scaled_dim, self.scaled_dim) | |
self.key = nn.Linear(self.scaled_dim, self.scaled_dim) | |
self.value = nn.Linear(self.scaled_dim, self.scaled_dim) | |
self.fc_out = nn.Linear(self.scaled_dim, in_dim) | |
def forward(self, x): | |
N = x.shape[0] | |
x = self.fc_in(x) | |
q = self.query(x).view(N, self.num_heads, self.head_dim) | |
k = self.key(x).view(N, self.num_heads, self.head_dim) | |
v = self.value(x).view(N, self.num_heads, self.head_dim) | |
energy = torch.einsum("nqd,nkd->nqk", [q, k]) | |
attention = F.softmax(energy / (self.head_dim ** 0.5), dim=2) | |
out = torch.einsum("nqk,nvd->nqd", [attention, v]) | |
out = out.reshape(N, self.scaled_dim) | |
out = self.fc_out(out) | |
return out | |
class BaseModel(nn.Module): | |
def __init__(self, num_classes, device='cuda' if torch.cuda.is_available() else 'cpu'): | |
super().__init__() | |
self.device = device | |
self.backbone = efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.IMAGENET1K_V1) | |
self.feature_dim = self.backbone.classifier[1].in_features | |
self.backbone.classifier = nn.Identity() | |
self.num_heads = max(1, min(8, self.feature_dim // 64)) | |
self.attention = MultiHeadAttention(self.feature_dim, num_heads=self.num_heads) | |
self.classifier = nn.Sequential( | |
nn.LayerNorm(self.feature_dim), | |
nn.Dropout(0.3), | |
nn.Linear(self.feature_dim, num_classes) | |
) | |
self.to(device) | |
def forward(self, x): | |
x = x.to(self.device) | |
features = self.backbone(x) | |
attended_features = self.attention(features) | |
logits = self.classifier(attended_features) | |
return logits, attended_features | |
num_classes = 120 | |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') | |
model = BaseModel(num_classes=num_classes, device=device) | |
checkpoint = torch.load('best_model_81_dog.pth', map_location=torch.device('cpu')) | |
model.load_state_dict(checkpoint['model_state_dict']) | |
# evaluation mode | |
model.eval() | |
# Image preprocessing function | |
def preprocess_image(image): | |
# If the image is numpy.ndarray turn into PIL.Image | |
if isinstance(image, np.ndarray): | |
image = Image.fromarray(image) | |
# Use torchvision.transforms to process images | |
transform = transforms.Compose([ | |
transforms.Resize((224, 224)), | |
transforms.ToTensor(), | |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), | |
]) | |
return transform(image).unsqueeze(0) | |
def get_akc_breeds_link(breed): | |
base_url = "https://www.akc.org/dog-breeds/" | |
breed_url = breed.lower().replace('_', '-') | |
return f"{base_url}{breed_url}/" | |
async def predict_single_dog(image): | |
image_tensor = preprocess_image(image) | |
with torch.no_grad(): | |
output = model(image_tensor) | |
logits = output[0] if isinstance(output, tuple) else output | |
probabilities = F.softmax(logits, dim=1) | |
topk_probs, topk_indices = torch.topk(probabilities, k=3) | |
top1_prob = topk_probs[0][0].item() | |
topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]] | |
# Calculate relative probabilities for display | |
raw_probs = [prob.item() for prob in topk_probs[0]] | |
sum_probs = sum(raw_probs) | |
relative_probs = [f"{(prob/sum_probs * 100):.2f}%" for prob in raw_probs] | |
return top1_prob, topk_breeds, relative_probs | |
async def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.45): | |
results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0] | |
dogs = [] | |
boxes = [] | |
for box in results.boxes: | |
if box.cls == 16: # COCO dataset class for dog is 16 | |
xyxy = box.xyxy[0].tolist() | |
confidence = box.conf.item() | |
boxes.append((xyxy, confidence)) | |
if not boxes: | |
dogs.append((image, 1.0, [0, 0, image.width, image.height])) | |
else: | |
nms_boxes = non_max_suppression(boxes, iou_threshold) | |
for box, confidence in nms_boxes: | |
x1, y1, x2, y2 = box | |
w, h = x2 - x1, y2 - y1 | |
x1 = max(0, x1 - w * 0.05) | |
y1 = max(0, y1 - h * 0.05) | |
x2 = min(image.width, x2 + w * 0.05) | |
y2 = min(image.height, y2 + h * 0.05) | |
cropped_image = image.crop((x1, y1, x2, y2)) | |
dogs.append((cropped_image, confidence, [x1, y1, x2, y2])) | |
return dogs | |
def non_max_suppression(boxes, iou_threshold): | |
keep = [] | |
boxes = sorted(boxes, key=lambda x: x[1], reverse=True) | |
while boxes: | |
current = boxes.pop(0) | |
keep.append(current) | |
boxes = [box for box in boxes if calculate_iou(current[0], box[0]) < iou_threshold] | |
return keep | |
def calculate_iou(box1, box2): | |
x1 = max(box1[0], box2[0]) | |
y1 = max(box1[1], box2[1]) | |
x2 = min(box1[2], box2[2]) | |
y2 = min(box1[3], box2[3]) | |
intersection = max(0, x2 - x1) * max(0, y2 - y1) | |
area1 = (box1[2] - box1[0]) * (box1[3] - box1[1]) | |
area2 = (box2[2] - box2[0]) * (box2[3] - box2[1]) | |
iou = intersection / float(area1 + area2 - intersection) | |
return iou | |
async def process_single_dog(image): | |
top1_prob, topk_breeds, relative_probs = await predict_single_dog(image) | |
# Case 1: Low confidence - unclear image or breed not in dataset | |
if top1_prob < 0.2: | |
error_message = ''' | |
<div class="dog-info-card"> | |
<div class="breed-info"> | |
<p class="warning-message"> | |
<span class="icon">⚠️</span> | |
The image is unclear or the breed is not in the dataset. Please upload a clearer image of a dog. | |
</p> | |
</div> | |
</div> | |
''' | |
initial_state = { | |
"explanation": error_message, | |
"image": None, | |
"is_multi_dog": False | |
} | |
return error_message, None, initial_state | |
breed = topk_breeds[0] | |
# Case 2: High confidence - single breed result | |
if top1_prob >= 0.45: | |
description = get_dog_description(breed) | |
formatted_description = format_description_html(description, breed) # 使用 format_description_html | |
html_content = f''' | |
<div class="dog-info-card"> | |
<div class="breed-info"> | |
{formatted_description} | |
</div> | |
</div> | |
''' | |
initial_state = { | |
"explanation": html_content, | |
"image": image, | |
"is_multi_dog": False | |
} | |
return html_content, image, initial_state | |
# Case 3: Medium confidence - show top 3 breeds with relative probabilities | |
else: | |
breeds_html = "" | |
for i, (breed, prob) in enumerate(zip(topk_breeds, relative_probs)): | |
description = get_dog_description(breed) | |
formatted_description = format_description_html(description, breed) # 使用 format_description_html | |
breeds_html += f''' | |
<div class="dog-info-card"> | |
<div class="breed-info"> | |
<div class="breed-header"> | |
<span class="breed-name">Breed {i+1}: {breed}</span> | |
<span class="confidence-badge">Confidence: {prob}</span> | |
</div> | |
{formatted_description} | |
</div> | |
</div> | |
''' | |
initial_state = { | |
"explanation": breeds_html, | |
"image": image, | |
"is_multi_dog": False | |
} | |
return breeds_html, image, initial_state | |
def create_breed_comparison(breed1: str, breed2: str) -> dict: | |
breed1_info = get_dog_description(breed1) | |
breed2_info = get_dog_description(breed2) | |
# 標準化數值轉換 | |
value_mapping = { | |
'Size': {'Small': 1, 'Medium': 2, 'Large': 3, 'Giant': 4}, | |
'Exercise_Needs': {'Low': 1, 'Moderate': 2, 'High': 3, 'Very High': 4}, | |
'Care_Level': {'Low': 1, 'Moderate': 2, 'High': 3}, | |
'Grooming_Needs': {'Low': 1, 'Moderate': 2, 'High': 3} | |
} | |
comparison_data = { | |
breed1: {}, | |
breed2: {} | |
} | |
for breed, info in [(breed1, breed1_info), (breed2, breed2_info)]: | |
comparison_data[breed] = { | |
'Size': value_mapping['Size'].get(info['Size'], 2), # 預設 Medium | |
'Exercise_Needs': value_mapping['Exercise_Needs'].get(info['Exercise Needs'], 2), # 預設 Moderate | |
'Care_Level': value_mapping['Care_Level'].get(info['Care Level'], 2), | |
'Grooming_Needs': value_mapping['Grooming_Needs'].get(info['Grooming Needs'], 2), | |
'Good_with_Children': info['Good with Children'] == 'Yes', | |
'Original_Data': info | |
} | |
return comparison_data | |
async def predict(image): | |
if image is None: | |
return "Please upload an image to start.", None, None | |
try: | |
if isinstance(image, np.ndarray): | |
image = Image.fromarray(image) | |
dogs = await detect_multiple_dogs(image) | |
# 更新顏色組合 | |
single_dog_color = '#34C759' # 清爽的綠色作為單狗顏色 | |
color_list = [ | |
'#FF5733', # 珊瑚紅 | |
'#28A745', # 深綠色 | |
'#3357FF', # 寶藍色 | |
'#FF33F5', # 粉紫色 | |
'#FFB733', # 橙黃色 | |
'#33FFF5', # 青藍色 | |
'#A233FF', # 紫色 | |
'#FF3333', # 紅色 | |
'#33FFB7', # 青綠色 | |
'#FFE033' # 金黃色 | |
] | |
annotated_image = image.copy() | |
draw = ImageDraw.Draw(annotated_image) | |
try: | |
font = ImageFont.truetype("arial.ttf", 24) | |
except: | |
font = ImageFont.load_default() | |
dogs_info = "" | |
for i, (cropped_image, detection_confidence, box) in enumerate(dogs): | |
color = single_dog_color if len(dogs) == 1 else color_list[i % len(color_list)] | |
# 優化圖片上的標記 | |
draw.rectangle(box, outline=color, width=4) | |
label = f"Dog {i+1}" | |
label_bbox = draw.textbbox((0, 0), label, font=font) | |
label_width = label_bbox[2] - label_bbox[0] | |
label_height = label_bbox[3] - label_bbox[1] | |
label_x = box[0] + 5 | |
label_y = box[1] + 5 | |
draw.rectangle( | |
[label_x - 2, label_y - 2, label_x + label_width + 4, label_y + label_height + 4], | |
fill='white', | |
outline=color, | |
width=2 | |
) | |
draw.text((label_x, label_y), label, fill=color, font=font) | |
top1_prob, topk_breeds, relative_probs = await predict_single_dog(cropped_image) | |
combined_confidence = detection_confidence * top1_prob | |
# 開始資訊卡片 | |
dogs_info += f'<div class="dog-info-card" style="border-left: 6px solid {color};">' | |
if combined_confidence < 0.2: | |
dogs_info += f''' | |
<div class="dog-info-header" style="background-color: {color}10;"> | |
<span class="dog-label" style="color: {color};">Dog {i+1}</span> | |
</div> | |
<div class="breed-info"> | |
<p class="warning-message"> | |
<span class="icon">⚠️</span> | |
The image is unclear or the breed is not in the dataset. Please upload a clearer image. | |
</p> | |
</div> | |
''' | |
elif top1_prob >= 0.45: | |
breed = topk_breeds[0] | |
description = get_dog_description(breed) | |
dogs_info += f''' | |
<div class="dog-info-header" style="background-color: {color}10;"> | |
<span class="dog-label" style="color: {color};"> | |
<span class="icon">🐾</span> {breed} | |
</span> | |
</div> | |
<div class="breed-info"> | |
<h2 class="section-title"> | |
<span class="icon">📋</span> BASIC INFORMATION | |
</h2> | |
<div class="info-section"> | |
<div class="info-item"> | |
<span class="tooltip tooltip-left"> | |
<span class="icon">📏</span> | |
<span class="label">Size:</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Size Categories:</strong><br> | |
• Small: Under 20 pounds<br> | |
• Medium: 20-60 pounds<br> | |
• Large: Over 60 pounds<br> | |
• Giant: Over 100 pounds<br> | |
• Varies: Depends on variety | |
</span> | |
</span> | |
<span class="value">{description['Size']}</span> | |
</div> | |
<div class="info-item"> | |
<span class="tooltip"> | |
<span class="icon">⏳</span> | |
<span class="label">Lifespan:</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Average Lifespan:</strong><br> | |
• Short: 6-8 years<br> | |
• Average: 10-15 years<br> | |
• Long: 12-20 years<br> | |
• Varies by size: Larger breeds typically have shorter lifespans | |
</span> | |
</span> | |
<span class="value">{description['Lifespan']}</span> | |
</div> | |
</div> | |
<h2 class="section-title"> | |
<span class="icon">🐕</span> TEMPERAMENT & PERSONALITY | |
</h2> | |
<div class="temperament-section"> | |
<span class="tooltip"> | |
<span class="value">{description['Temperament']}</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Temperament Guide:</strong><br> | |
• Describes the dog's natural behavior and personality<br> | |
• Important for matching with owner's lifestyle<br> | |
• Can be influenced by training and socialization | |
</span> | |
</span> | |
</div> | |
<h2 class="section-title"> | |
<span class="icon">💪</span> CARE REQUIREMENTS | |
</h2> | |
<div class="care-section"> | |
<div class="info-item"> | |
<span class="tooltip tooltip-left"> | |
<span class="icon">🏃</span> | |
<span class="label">Exercise:</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Exercise Needs:</strong><br> | |
• Low: Short walks and play sessions<br> | |
• Moderate: 1-2 hours of daily activity<br> | |
• High: Extensive exercise (2+ hours/day)<br> | |
• Very High: Constant activity and mental stimulation needed | |
</span> | |
</span> | |
<span class="value">{description['Exercise Needs']}</span> | |
</div> | |
<div class="info-item"> | |
<span class="tooltip"> | |
<span class="icon">✂️</span> | |
<span class="label">Grooming:</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Grooming Requirements:</strong><br> | |
• Low: Basic brushing, occasional baths<br> | |
• Moderate: Weekly brushing, occasional grooming<br> | |
• High: Daily brushing, frequent professional grooming needed<br> | |
• Professional care recommended for all levels | |
</span> | |
</span> | |
<span class="value">{description['Grooming Needs']}</span> | |
</div> | |
<div class="info-item"> | |
<span class="tooltip"> | |
<span class="icon">⭐</span> | |
<span class="label">Care Level:</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Care Level Explained:</strong><br> | |
• Low: Basic care and attention needed<br> | |
• Moderate: Regular care and routine needed<br> | |
• High: Significant time and attention needed<br> | |
• Very High: Extensive care, training and attention required | |
</span> | |
</span> | |
<span class="value">{description['Care Level']}</span> | |
</div> | |
</div> | |
<h2 class="section-title"> | |
<span class="icon">👨👩👧👦</span> FAMILY COMPATIBILITY | |
</h2> | |
<div class="family-section"> | |
<div class="info-item"> | |
<span class="tooltip"> | |
<span class="icon"></span> | |
<span class="label">Good with Children:</span> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Child Compatibility:</strong><br> | |
• Yes: Excellent with kids, patient and gentle<br> | |
• Moderate: Good with older children<br> | |
• No: Better suited for adult households | |
</span> | |
</span> | |
<span class="value">{description['Good with Children']}</span> | |
</div> | |
</div> | |
<h2 class="section-title"> | |
<span class="icon">📝</span> DESCRIPTION | |
</h2> | |
<div class="description-section"> | |
<p>{description.get('Description', '')}</p> | |
</div> | |
<div class="action-section"> | |
<a href="{get_akc_breeds_link(breed)}" target="_blank" class="akc-button"> | |
<span class="icon">🌐</span> | |
Learn more about {breed} on AKC website | |
</a> | |
</div> | |
</div> | |
''' | |
else: | |
dogs_info += f''' | |
<div class="dog-info-header" style="background-color: {color}10;"> | |
<span class="dog-label" style="color: {color};">Dog {i+1}</span> | |
</div> | |
<div class="breed-info"> | |
<div class="model-uncertainty-note"> | |
<span class="icon">ℹ️</span> | |
Note: The model is showing some uncertainty in its predictions. | |
Here are the most likely breeds based on the available visual features. | |
</div> | |
<div class="breeds-list"> | |
''' | |
for j, (breed, prob) in enumerate(zip(topk_breeds, relative_probs)): | |
description = get_dog_description(breed) | |
dogs_info += f''' | |
<div class="breed-option uncertainty-mode"> | |
<div class="breed-header"> | |
<span class="option-number">Option {j+1}</span> | |
<span class="breed-name">{breed}</span> | |
<span class="confidence-badge" style="background-color: {color}20; color: {color};"> | |
Confidence: {prob} | |
</span> | |
</div> | |
<div class="breed-content"> | |
{format_description_html(description, breed)} | |
</div> | |
</div> | |
''' | |
dogs_info += '</div></div>' | |
dogs_info += '</div>' | |
html_output = f""" | |
<div class="dog-info-card"> | |
{dogs_info} | |
</div> | |
""" | |
initial_state = { | |
"dogs_info": dogs_info, | |
"image": annotated_image, | |
"is_multi_dog": len(dogs) > 1, | |
"html_output": html_output | |
} | |
return html_output, annotated_image, initial_state | |
except Exception as e: | |
error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}" | |
print(error_msg) | |
return error_msg, None, None | |
def show_details_html(choice, previous_output, initial_state): | |
if not choice: | |
return previous_output, gr.update(visible=True), initial_state | |
try: | |
breed = choice.split("More about ")[-1] | |
description = get_dog_description(breed) | |
formatted_description = format_description_html(description, breed) | |
html_output = f""" | |
<div class="dog-info"> | |
<h2>{breed}</h2> | |
{formatted_description} | |
</div> | |
""" | |
initial_state["current_description"] = html_output | |
initial_state["original_buttons"] = initial_state.get("buttons", []) | |
return html_output, gr.update(visible=True), initial_state | |
except Exception as e: | |
error_msg = f"An error occurred while showing details: {e}" | |
print(error_msg) | |
return f"<p style='color: red;'>{error_msg}</p>", gr.update(visible=True), initial_state | |
def format_description_html(description, breed): | |
html = "<ul style='list-style-type: none; padding-left: 0;'>" | |
if isinstance(description, dict): | |
for key, value in description.items(): | |
if key != "Breed": # 跳過重複的品種顯示 | |
if key == "Size": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Size Categories:</strong><br> | |
• Small: Under 20 pounds<br> | |
• Medium: 20-60 pounds<br> | |
• Large: Over 60 pounds | |
</span> | |
</span> {value} | |
</li> | |
''' | |
elif key == "Exercise Needs": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Exercise Needs:</strong><br> | |
• High: 2+ hours of daily exercise<br> | |
• Moderate: 1-2 hours of daily activity<br> | |
• Low: Short walks and play sessions | |
</span> | |
</span> {value} | |
</li> | |
''' | |
elif key == "Grooming Needs": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Grooming Requirements:</strong><br> | |
• High: Daily brushing, regular professional care<br> | |
• Moderate: Weekly brushing, occasional grooming<br> | |
• Low: Minimal brushing, basic maintenance | |
</span> | |
</span> {value} | |
</li> | |
''' | |
elif key == "Care Level": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Care Level Explained:</strong><br> | |
• High: Needs significant training and attention<br> | |
• Moderate: Regular care and routine needed<br> | |
• Low: More independent, basic care sufficient | |
</span> | |
</span> {value} | |
</li> | |
''' | |
elif key == "Good with Children": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Child Compatibility:</strong><br> | |
• Yes: Excellent with kids, patient and gentle<br> | |
• Moderate: Good with older children<br> | |
• No: Better suited for adult households | |
</span> | |
</span> {value} | |
</li> | |
''' | |
elif key == "Lifespan": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Average Lifespan:</strong><br> | |
• Short: 6-8 years<br> | |
• Average: 10-15 years<br> | |
• Long: 12-20 years | |
</span> | |
</span> {value} | |
</li> | |
''' | |
elif key == "Temperament": | |
html += f''' | |
<li style='margin-bottom: 10px;'> | |
<span class="tooltip"> | |
<strong>{key}:</strong> | |
<span class="tooltip-icon">ⓘ</span> | |
<span class="tooltip-text"> | |
<strong>Temperament Guide:</strong><br> | |
• Describes the dog's natural behavior<br> | |
• Important for matching with owner | |
</span> | |
</span> {value} | |
</li> | |
''' | |
else: | |
# 其他欄位保持原樣顯示 | |
html += f"<li style='margin-bottom: 10px;'><strong>{key}:</strong> {value}</li>" | |
else: | |
html += f"<li>{description}</li>" | |
html += "</ul>" | |
# 添加AKC連結 | |
html += f''' | |
<div class="action-section"> | |
<a href="{get_akc_breeds_link(breed)}" target="_blank" class="akc-button"> | |
<span class="icon">🌐</span> | |
Learn more about {breed} on AKC website | |
</a> | |
</div> | |
''' | |
return html | |
with gr.Blocks(css=get_css_styles()) as iface: | |
gr.HTML(""" | |
<header style='text-align: center; padding: 20px; margin-bottom: 20px;'> | |
<h1 style='font-size: 2.5em; margin-bottom: 10px; color: #2D3748;'> | |
🐾 PawMatch AI | |
</h1> | |
<h2 style='font-size: 1.2em; font-weight: normal; color: #4A5568; margin-top: 5px;'> | |
Your Smart Dog Breed Guide | |
</h2> | |
<div style='width: 50px; height: 3px; background: linear-gradient(90deg, #4299e1, #48bb78); margin: 15px auto;'></div> | |
<p style='color: #718096; font-size: 0.9em;'> | |
Powered by AI • Breed Recognition • Smart Matching • Companion Guide | |
</p> | |
</header> | |
""") | |
def main(): | |
with gr.Blocks(css=get_css_styles()) as iface: | |
# Header HTML | |
gr.HTML(""" | |
<header style='text-align: center; padding: 20px; margin-bottom: 20px;'> | |
<h1 style='font-size: 2.5em; margin-bottom: 10px; color: #2D3748;'> | |
🐾 PawMatch AI | |
</h1> | |
<h2 style='font-size: 1.2em; font-weight: normal; color: #4A5568; margin-top: 5px;'> | |
Your Smart Dog Breed Guide | |
</h2> | |
<div style='width: 50px; height: 3px; background: linear-gradient(90deg, #4299e1, #48bb78); margin: 15px auto;'></div> | |
<p style='color: #718096; font-size: 0.9em;'> | |
Powered by AI • Breed Recognition • Smart Matching • Companion Guide | |
</p> | |
</header> | |
""") | |
# 先創建歷史組件實例(但不創建標籤頁) | |
history_component = create_history_component() | |
with gr.Tabs(): | |
# 1. 品種檢測標籤頁 | |
example_images = [ | |
'Border_Collie.jpg', | |
'Golden_Retriever.jpeg', | |
'Saint_Bernard.jpeg', | |
'Samoyed.jpg', | |
'French_Bulldog.jpeg' | |
] | |
detection_components = create_detection_tab(predict, example_images) | |
# 2. 品種比較標籤頁 | |
comparison_components = create_comparison_tab( | |
dog_breeds=dog_breeds, | |
get_dog_description=get_dog_description | |
) | |
# 3. 品種推薦標籤頁 | |
recommendation_components = create_recommendation_tab( | |
UserPreferences=UserPreferences, | |
get_breed_recommendations=get_breed_recommendations, | |
format_recommendation_html=format_recommendation_html, | |
history_component=history_component | |
) | |
# 4. 最後創建歷史記錄標籤頁 | |
create_history_tab(history_component) | |
# Footer | |
gr.HTML(''' | |
For more details on this project and other work, feel free to visit my GitHub | |
<a href="https://github.com/Eric-Chung-0511/Learning-Record/tree/main/Data%20Science%20Projects/Dog_Breed_Classifier"> | |
Dog Breed Classifier | |
</a> | |
''') | |
return iface | |
if __name__ == "__main__": | |
iface = main() | |
iface.launch(share=True) |