import random from typing import List, Dict from breed_health_info import breed_health_info, default_health_note from breed_noise_info import breed_noise_info from dog_database import get_dog_description from recommendation_formatter import ( generate_breed_characteristics_data, parse_noise_information, parse_health_information, calculate_breed_bonus_factors, generate_dimension_scores_for_display ) class RecommendationHTMLFormatter: """處理推薦結果的HTML和CSS格式化""" def __init__(self): self.description_search_css = """ """ self.criteria_search_css = """ """ self.unified_css = """ """ def format_unified_percentage(self, score: float) -> str: """統一格式化百分比顯示,確保數值邏輯一致""" try: # 確保分數在0-1範圍內 normalized_score = max(0.0, min(1.0, float(score))) # 轉換為百分比並保留一位小數 percentage = normalized_score * 100 return f"{percentage:.1f}%" except Exception as e: print(f"Error formatting percentage: {str(e)}") return "70.0%" def generate_unified_progress_bar(self, score: float) -> str: """Generate unified progress bar HTML with width directly corresponding to score""" try: # Ensure score is in 0-1 range normalized_score = max(0.0, min(1.0, float(score))) # Progress bar width with reasonable visual mapping # High scores get enhanced visual representation for impact if normalized_score >= 0.9: width_percentage = 85 + (normalized_score - 0.9) * 130 # 85-98% for excellent scores elif normalized_score >= 0.8: width_percentage = 70 + (normalized_score - 0.8) * 150 # 70-85% for very good scores elif normalized_score >= 0.7: width_percentage = 55 + (normalized_score - 0.7) * 150 # 55-70% for good scores elif normalized_score >= 0.5: width_percentage = 30 + (normalized_score - 0.5) * 125 # 30-55% for fair scores else: width_percentage = 8 + normalized_score * 44 # 8-30% for low scores # Ensure reasonable bounds width_percentage = max(5, min(98, width_percentage)) # Choose color based on score with appropriate theme # This is used for unified recommendations (Description search) if normalized_score >= 0.9: color = '#10b981' # Excellent (emerald green) elif normalized_score >= 0.8: color = '#06b6d4' # Good (cyan) elif normalized_score >= 0.7: color = '#3b82f6' # Fair (blue) elif normalized_score >= 0.6: color = '#1d4ed8' # Average (darker blue) elif normalized_score >= 0.5: color = '#1e40af' # Below average (dark blue) else: color = '#ef4444' # Poor (red) return f'''
''' except Exception as e: print(f"Error generating progress bar: {str(e)}") return '
' def generate_progress_bar(self, score: float, score_type: str = None, is_percentage_display: bool = False, is_description_search: bool = False) -> dict: """ Generate progress bar width and color with consistent score-to-visual mapping Parameters: score: Score value (float between 0-1 or percentage 0-100) score_type: Score type for special handling is_percentage_display: Whether the score is in percentage format Returns: dict: Dictionary containing width and color """ # Normalize score to 0-1 range if is_percentage_display: normalized_score = score / 100.0 # Convert percentage to 0-1 range else: normalized_score = score # Ensure score is within valid range normalized_score = max(0.0, min(1.0, normalized_score)) # Calculate progress bar width - simplified for Find by Criteria if not is_description_search and score_type != 'bonus': # Find by Criteria: 調整為更有說服力的視覺比例 percentage = normalized_score * 100 if percentage >= 95: width = 92 + (percentage - 95) * 1.2 # 95%+ 顯示為 92-98% elif percentage >= 90: width = 85 + (percentage - 90) # 90-95% 顯示為 85-92% elif percentage >= 80: width = 75 + (percentage - 80) * 1.0 # 80-90% 顯示為 75-85% elif percentage >= 70: width = 60 + (percentage - 70) * 1.5 # 70-80% 顯示為 60-75% else: width = percentage * 0.8 # 70% 以下按比例縮放 width = max(5, min(98, width)) elif score_type == 'bonus': # Bonus scores are typically smaller, need amplified display width = max(5, min(95, normalized_score * 150)) # Amplified for visibility else: # Find by Description: 保持現有的複雜計算 if normalized_score >= 0.8: width = 75 + (normalized_score - 0.8) * 115 # 75-98% range for high scores elif normalized_score >= 0.6: width = 50 + (normalized_score - 0.6) * 125 # 50-75% range for good scores elif normalized_score >= 0.4: width = 25 + (normalized_score - 0.4) * 125 # 25-50% range for fair scores else: width = 5 + normalized_score * 50 # 5-25% range for low scores width = max(3, min(98, width)) # Color coding based on normalized score - Criteria uses green gradation if is_description_search: # Find by Description uses blue theme if normalized_score >= 0.9: color = '#10b981' # Excellent (emerald green) elif normalized_score >= 0.85: color = '#06b6d4' # Very good (cyan) elif normalized_score >= 0.8: color = '#3b82f6' # Good (blue) elif normalized_score >= 0.7: color = '#1d4ed8' # Fair (darker blue) elif normalized_score >= 0.6: color = '#1e40af' # Below average (dark blue) elif normalized_score >= 0.5: color = '#f59e0b' # Poor (amber) else: color = '#ef4444' # Very poor (red) else: # Find by Criteria uses original green gradation if normalized_score >= 0.9: color = '#22c55e' # Excellent (bright green) elif normalized_score >= 0.85: color = '#65a30d' # Very good (green) elif normalized_score >= 0.8: color = '#a3a332' # Good (yellow-green) elif normalized_score >= 0.7: color = '#d4a332' # Fair (yellow) elif normalized_score >= 0.6: color = '#e67e22' # Below average (orange) elif normalized_score >= 0.5: color = '#e74c3c' # Poor (red) else: color = '#c0392b' # Very poor (dark red) return { 'width': width, 'color': color } def get_css_styles(self, is_description_search: bool) -> str: """根據搜尋類型返回對應的CSS樣式""" if is_description_search: return self.description_search_css else: return self.criteria_search_css def generate_breed_card_header(self, breed: str, rank: int, final_score: float, is_description_search: bool) -> str: """生成品種卡片標題部分的HTML""" rank_class = f"rank-{rank}" if rank <= 3 else "rank-other" percentage = final_score * 100 if percentage >= 90: score_class = "score-excellent" fill_class = "fill-excellent" match_label = "EXCELLENT MATCH" elif percentage >= 70: score_class = "score-good" fill_class = "fill-good" match_label = "GOOD MATCH" else: score_class = "score-moderate" fill_class = "fill-moderate" match_label = "MODERATE MATCH" if is_description_search: # Find by Description: 使用現有複雜設計 return f"""
#{rank}

{breed.replace('_', ' ')}

{percentage:.1f}%
{match_label}
""" else: # Find by Criteria: 使用簡潔設計,包含獎盃圖示 # 計算進度條寬度 - 調整為更有說服力的視覺比例 if percentage >= 95: score_width = 92 + (percentage - 95) * 1.2 # 95%+ 顯示為 92-98% elif percentage >= 90: score_width = 85 + (percentage - 90) # 90-95% 顯示為 85-92% elif percentage >= 80: score_width = 75 + (percentage - 80) * 1.0 # 80-90% 顯示為 75-85% elif percentage >= 70: score_width = 60 + (percentage - 70) * 1.5 # 70-80% 顯示為 60-75% else: score_width = percentage * 0.8 # 70% 以下按比例縮放 score_width = max(5, min(98, score_width)) return f"""
🏆 #{rank}

{breed.replace('_', ' ')}

{percentage:.1f}%
OVERALL MATCH
""" def generate_tooltips_section(self) -> str: """生成提示氣泡HTML""" return ''' Space Compatibility Score:
• Evaluates how well the breed adapts to your living environment
• Considers if your home (apartment/house) and yard access suit the breed's size
• Higher score means the breed fits well in your available space.
''' def generate_detailed_sections_html(self, breed: str, info: dict, noise_characteristics: List[str], barking_triggers: List[str], noise_level: str, health_considerations: List[str], health_screenings: List[str]) -> str: """生成詳細區段的HTML""" # 生成特徵和觸發因素的HTML noise_characteristics_html = '\n'.join([f'
  • {item}
  • ' for item in noise_characteristics]) barking_triggers_html = '\n'.join([f'
  • {item}
  • ' for item in barking_triggers]) health_considerations_html = '\n'.join([f'
  • {item}
  • ' for item in health_considerations]) health_screenings_html = '\n'.join([f'
  • {item}
  • ' for item in health_screenings]) return f"""

    📋 Breed Details

    📏 Size: Size Categories:
    • Small: Under 20 pounds
    • Medium: 20-60 pounds
    • Large: Over 60 pounds
    {info['Size']}
    🏃 Exercise Needs: Exercise Needs:
    • Low: Short walks
    • Moderate: 1-2 hours daily
    • High: 2+ hours daily
    • Very High: Constant activity
    {info['Exercise Needs']}
    👨‍👩‍👧‍👦 Good with Children: Child Compatibility:
    • Yes: Excellent with kids
    • Moderate: Good with older children
    • No: Better for adult households
    {info['Good with Children']}
    Lifespan: Average Lifespan:
    • Short: 6-8 years
    • Average: 10-15 years
    • Long: 12-20 years
    • Varies by size: Larger breeds typically have shorter lifespans
    {info['Lifespan']}

    📝 Description

    {info.get('Description', '')}

    🔊 Noise Behavior Noise Behavior:
    • Typical vocalization patterns
    • Common triggers and frequency
    • Based on breed characteristics

    Typical noise characteristics:

    Moderate to high barker
    Alert watch dog
    Attention-seeking barks
    Social vocalizations

    Noise level:

    Moderate-High

    Barking triggers:

    Separation anxiety
    Attention needs
    Strange noises
    Excitement

    Source: Compiled from various breed behavior resources, 2024

    Individual dogs may vary in their vocalization patterns.

    Training can significantly influence barking behavior.

    Environmental factors may affect noise levels.

    🏥 Health Insights Health information is compiled from multiple sources including veterinary resources, breed guides, and international canine health databases. Each dog is unique and may vary from these general guidelines.

    Common breed-specific health considerations:

    Patellar luxation
    Progressive retinal atrophy
    Von Willebrand's disease
    Open fontanel

    Recommended health screenings:

    Patella evaluation
    Eye examination
    Blood clotting tests
    Skull development monitoring

    Source: Compiled from various veterinary and breed information resources, 2024

    This information is for reference only and based on breed tendencies.

    Each dog is unique and may not develop any or all of these conditions.

    Always consult with qualified veterinarians for professional advice.

    """