# Website Color and Font Analyzer

A powerful Python tool for analyzing website design elements including colors, fonts, and typography. Extracts primary and secondary color palettes, font families, and provides comprehensive design analysis for web design research, inspiration, and accessibility auditing.

## 🚀 Features

- **Comprehensive Color Analysis**:
  - Extract all colors from CSS stylesheets and computed styles
  - Generate primary, secondary, and accent color palettes
  - Color harmony and relationship analysis
  - WCAG accessibility and contrast ratio analysis
  - Color temperature analysis (warm/cool/neutral)
  - Visual color swatch generation

- **Advanced Typography Analysis**:
  - Extract all font families from CSS and computed styles
  - Categorize fonts (serif, sans-serif, monospace, display)
  - Identify web-safe vs custom fonts
  - Google Fonts detection and analysis
  - Font stack analysis

- **Technical Analysis**:
  - CSS source analysis (inline vs external stylesheets)
  - Computed style inspection using Selenium
  - Screenshot capture for visual reference
  - Complete CSS extraction and saving
  - Detailed metadata preservation

- **Design Intelligence**:
  - Color grouping and similarity analysis
  - Complementary color pair detection
  - Dominant hue identification
  - Accessibility compliance checking
  - Professional design insights

## 📋 Requirements

### System Dependencies
- **Python 3.7+**
- **Google Chrome/Chromium browser**
- **ChromeDriver** (managed automatically by Selenium 4.x)

### Python Libraries
- requests>=2.31.0
- selenium>=4.15.0
- beautifulsoup4>=4.12.0
- Pillow>=10.0.0
- css-parser>=1.0.8
- lxml>=4.9.0

## 🛠️ Installation

### 1. Install System Dependencies

**Ubuntu/Debian:**
```bash
# Install Chrome
wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
sudo apt-get update
sudo apt-get install google-chrome-stable python3-pip
```

**macOS:**
```bash
# Install Chrome and Python
brew install --cask google-chrome
brew install python3
```

**Windows:**
- Download Chrome from [https://www.google.com/chrome/](https://www.google.com/chrome/)
- Install Python from [python.org](https://python.org)

### 2. Install Python Dependencies
```bash
pip install -r requirements.txt
```

### 3. Make Script Executable
```bash
chmod +x website_analyzer.py
```

## 📖 Usage

### Basic Analysis

**Analyze a website:**
```bash
python website_analyzer.py analyze https://example.com
```

**Extract color palette only:**
```bash
python website_analyzer.py palette https://example.com
```

**Get analysis statistics:**
```bash
python website_analyzer.py stats
```

### Advanced Usage

**Custom output directory:**
```bash
python website_analyzer.py analyze https://example.com -o custom_analysis
```

**Run in non-headless mode (show browser):**
```bash
python website_analyzer.py analyze https://example.com --no-headless
```

**Verbose logging:**
```bash
python website_analyzer.py analyze https://example.com -v
```

**Limit color analysis:**
```bash
python website_analyzer.py analyze https://example.com --max-colors 15
```

## 🔧 Command Line Options

| Option | Description | Default |
|--------|-------------|---------|
| `action` | Action to perform (analyze/palette/stats) | Required |
| `url` | Website URL to analyze | Required (for analyze/palette) |
| `-o, --output` | Output directory | `website_analysis` |
| `--headless` | Run browser in headless mode | True |
| `--max-colors` | Maximum colors to analyze in palette | 20 |
| `-v, --verbose` | Verbose logging | False |

## 📁 Output Structure

The tool creates a comprehensive output structure:

```
website_analysis/
├── colors/              # Color analysis files
├── fonts/               # Font analysis files  
├── palettes/            # Visual color swatches (PNG)
├── screenshots/         # Website screenshots (PNG)
├── css/                 # Extracted CSS files
└── reports/             # JSON analysis reports
```

## 🎯 Analysis Features

### Color Analysis
- **Color Extraction**: From CSS stylesheets, inline styles, and computed styles
- **Palette Generation**: Primary (top 3), secondary (next 3), accent colors
- **Color Harmony**: Complementary pairs, analogous groups, triadic relationships
- **Accessibility**: WCAG AA/AAA compliance, contrast ratios
- **Temperature**: Warm/cool/neutral color classification
- **Grouping**: Similar color clustering and frequency analysis

### Typography Analysis
- **Font Detection**: All font families from CSS and computed styles
- **Categorization**: Serif, sans-serif, monospace, display fonts
- **Web Safety**: Web-safe vs custom font identification
- **Google Fonts**: Automatic detection of Google Fonts usage
- **Font Stacks**: Complete font fallback analysis

### Technical Analysis
- **CSS Sources**: Inline styles vs external stylesheet analysis
- **Computed Styles**: Real-time browser style computation
- **Visual Assets**: Screenshots and color swatches
- **Metadata**: Complete design element documentation

## 🎨 Examples

### Example 1: Complete Website Analysis

```bash
python website_analyzer.py analyze https://stripe.com -v
```

**Output:**
```
✅ Successfully analyzed https://stripe.com
🎨 Found 47 colors
🔤 Found 12 fonts
📁 Output directory: website_analysis

🎨 Top Colors:
  #635bff
  #ffffff
  #000000
  #f6f9fc
  #425466
  #1a1f36
  #0a2540
  #00d924
  #ff5722
  #6772e5

🔤 Top Fonts:
  Inter
  sans-serif
  -apple-system
  BlinkMacSystemFont
  Segoe UI
```

**Files created:**
- `website_analysis/screenshots/stripe_com_20231201_143022.png`
- `website_analysis/palettes/stripe_com_20231201_143022_swatch.png`
- `website_analysis/css/stripe_com_20231201_143022.css`
- `website_analysis/reports/stripe_com_20231201_143022_analysis.json`

### Example 2: Color Palette Focus

```bash
python website_analyzer.py palette https://dribbble.com
```

**Output:**
```
🎨 Color Palette for https://dribbble.com
==================================================
Primary Colors:
  #ea4c89
  #ffffff
  #000000

Secondary Colors:
  #f7f7f7
  #9e9ea7
  #6e6d7a

Accent Colors:
  #ff6b6b
  #4ecdc4
  #45b7d1

Dominant Hue: 330-360 degrees
Color Temperature: warm
```

### Example 3: Design Agency Analysis

```bash
python website_analyzer.py analyze https://www.awwwards.com --max-colors 25
```

Comprehensive analysis including:
- Award-winning design color schemes
- Premium typography selections
- Advanced color relationships
- Professional design patterns

### Example 4: E-commerce Color Study

```bash
python website_analyzer.py analyze https://shopify.com -o ecommerce_analysis
```

Specialized for:
- Brand color consistency
- Conversion-focused color psychology
- Accessibility compliance
- User experience color patterns

### Example 5: Analysis Statistics

```bash
python website_analyzer.py stats
```

**Output:**
```
📊 Website Analysis Statistics:
========================================
Total Analyses: 23

Recent Websites:
  stripe_com - 2023-12-01
  dribbble_com - 2023-12-01
  awwwards_com - 2023-11-30
  shopify_com - 2023-11-30
  figma_com - 2023-11-29

Color Statistics:
  Total Colors Found: 847
  Unique Colors: 234
  Most Common Colors: {'#ffffff': 23, '#000000': 19, '#f6f9fc': 12}

Font Statistics:
  Total Fonts Found: 156
  Unique Fonts: 45
  Most Common Fonts: {'Inter': 8, 'Helvetica': 7, 'Arial': 6}
```

## ⚙️ Advanced Configuration

### Color Analysis Customization

**Grouping Sensitivity:**
```python
# Modify in ColorAnalyzer.group_similar_colors()
threshold = 20.0  # Lower = more groups, Higher = fewer groups
```

**Palette Size:**
```python
# Modify in WebsiteAnalyzer.generate_color_palette()
max_colors = 15  # Increase for larger palettes
```

### Font Analysis Enhancement

**Custom Font Categories:**
```python
# Add to WebsiteAnalyzer.analyze_typography()
custom_fonts = ['Your Custom Font', 'Brand Font']
display_fonts.extend(custom_fonts)
```

### Visual Output Customization

**Color Swatch Size:**
```python
# Modify in WebsiteAnalyzer.create_color_swatch()
swatch_width = 1200  # Increase for wider swatches
swatch_height = 300  # Increase for taller swatches
```

## 🔍 Analysis Output Details

### JSON Report Structure

```json
{
  "success": true,
  "url": "https://example.com",
  "domain": "example_com",
  "analysis_date": "2023-12-01T14:30:22",
  "colors": {
    "total_found": 47,
    "unique_colors": ["#635bff", "#ffffff", ...],
    "palette_analysis": {
      "primary_colors": ["#635bff", "#ffffff", "#000000"],
      "secondary_colors": ["#f6f9fc", "#425466", "#1a1f36"],
      "accent_colors": ["#0a2540", "#00d924", "#ff5722"],
      "color_harmony": {
        "complementary_pairs": [["#635bff", "#ffb563"]],
        "dominant_hue": "240-270 degrees"
      },
      "accessibility": {
        "wcag_aa_compliant": [
          {
            "color1": "#000000",
            "color2": "#ffffff", 
            "contrast_ratio": 21.0
          }
        ]
      },
      "color_temperature": {
        "warm_colors": ["#ff5722", "#ffb563"],
        "cool_colors": ["#635bff", "#00d924"],
        "overall_temperature": "neutral"
      }
    }
  },
  "typography": {
    "total_fonts": 12,
    "font_families": ["Inter", "sans-serif", ...],
    "analysis": {
      "font_categories": {
        "serif": 2,
        "sans-serif": 8,
        "monospace": 1,
        "display": 1
      },
      "web_safe_fonts": ["Arial", "sans-serif"],
      "custom_fonts": ["Inter", "SF Pro Display"]
    }
  }
}
```

### Color Harmony Analysis

The tool identifies several color relationships:

**Complementary Colors:**
- Colors opposite on the color wheel (150-210° apart)
- High contrast pairs ideal for emphasis
- Automatically detected and reported

**Analogous Colors:**
- Colors adjacent on the color wheel
- Harmonious and pleasing combinations
- Great for gradient and theme consistency

**Color Temperature:**
- **Warm**: Red to yellow range (0-60°, 300-360°)
- **Cool**: Green to blue range (120-240°)
- **Neutral**: Grays and transition areas

### Accessibility Features

**WCAG Compliance:**
- **AA Standard**: 4.5:1 contrast ratio minimum
- **AAA Standard**: 7:1 contrast ratio minimum
- Automatic compliance checking for all color pairs

**Contrast Analysis:**
- Luminance calculation using WCAG formula
- Gamma correction for accurate perception
- Detailed contrast ratio reporting

## 🐛 Troubleshooting

### Common Issues

1. **"ChromeDriver not found" error**
   ```bash
   # Ensure Chrome is installed first
   pip install webdriver-manager
   # The script will auto-download ChromeDriver
   ```

2. **"CSS parser error" warnings**
   ```bash
   pip install --upgrade css-parser
   # Or ignore if analysis still works
   ```

3. **Selenium timeout errors**
   - Check internet connection
   - Verify website is accessible
   - Increase timeout in script if needed

4. **Color extraction issues**
   - Some colors may be in images (not extracted)
   - Dynamic colors from JavaScript may be missed
   - Use computed styles analysis for complete coverage

5. **Font detection limitations**
   - Web fonts may load after analysis
   - Some fonts only in images won't be detected
   - Font stacks may include fallbacks

### Performance Tips

- **Large websites**: May take 30-60 seconds for complete analysis
- **CSS-heavy sites**: External stylesheet fetching can be slow
- **JavaScript-heavy sites**: Allow extra time for rendering
- **Memory usage**: Monitor for very large websites

### Website-Specific Issues

**Single Page Applications (SPAs):**
- May need longer load times
- Dynamic content might be missed
- Consider multiple analyses at different states

**CSS Framework Detection:**
- Bootstrap, Tailwind CSS automatically detected
- Framework colors included in analysis
- Utility classes properly parsed

**Custom CSS:**
- Variables and calculations supported
- @import statements followed
- Minified CSS properly parsed

## 📈 Use Cases

### Web Design Research
- **Color Trend Analysis**: Study popular color schemes across industries
- **Competitive Analysis**: Compare brand color strategies
- **Inspiration Gathering**: Build design mood boards from real websites

### Brand Analysis
- **Brand Consistency**: Verify color usage across web properties
- **Color Psychology**: Analyze emotional impact of color choices
- **Accessibility Audit**: Ensure WCAG compliance across sites

### Development Workflow
- **Design Handoff**: Extract exact colors and fonts from designs
- **Style Guide Creation**: Generate comprehensive design systems
- **QA Testing**: Verify implementation matches designs

### Academic Research
- **Web Design Evolution**: Study color and typography trends over time
- **Cultural Analysis**: Compare design preferences across regions
- **Accessibility Studies**: Analyze compliance patterns

## 🎓 Color Theory Integration

### Color Wheel Analysis
The tool uses HSL color space for accurate color relationship detection:

**Hue Relationships:**
- **0°**: Red
- **60°**: Yellow  
- **120°**: Green
- **180°**: Cyan
- **240°**: Blue
- **300°**: Magenta

**Harmony Rules:**
- **Complementary**: 180° apart
- **Triadic**: 120° apart
- **Analogous**: 30° apart
- **Split-complementary**: 150° apart

### Typography Classification

**Serif Fonts:**
- Traditional, formal appearance
- Good for body text, print
- Examples: Times New Roman, Georgia

**Sans-serif Fonts:**
- Modern, clean appearance
- Good for digital screens, UI
- Examples: Arial, Helvetica, Inter

**Monospace Fonts:**
- Fixed-width characters
- Good for code, technical content
- Examples: Courier New, Monaco

**Display Fonts:**
- Decorative, artistic fonts
- Good for headlines, branding
- Examples: Custom brand fonts

## 📚 API Reference

### WebsiteAnalyzer Class

```python
from website_analyzer import WebsiteAnalyzer

# Initialize analyzer
analyzer = WebsiteAnalyzer(output_dir="custom_output", headless=True)

# Analyze website
result = analyzer.analyze_website("https://example.com")

# Get statistics
stats = analyzer.get_analysis_stats()

# Cleanup
analyzer.close_driver()
```

### ColorAnalyzer Utilities

```python
from website_analyzer import ColorAnalyzer

# Color conversions
rgb = ColorAnalyzer.hex_to_rgb("#ff5722")
hex_color = ColorAnalyzer.rgb_to_hex((255, 87, 34))
hsl = ColorAnalyzer.rgb_to_hsl((255, 87, 34))

# Color analysis
luminance = ColorAnalyzer.get_color_luminance((255, 87, 34))
contrast = ColorAnalyzer.calculate_contrast_ratio((0, 0, 0), (255, 255, 255))
is_dark = ColorAnalyzer.is_color_dark((255, 87, 34))

# Color grouping
groups = ColorAnalyzer.group_similar_colors(["#ff5722", "#ff6733", "#e64a19"])
```

### Custom Analysis Scripts

```python
# Batch analysis example
websites = ["https://site1.com", "https://site2.com", "https://site3.com"]
analyzer = WebsiteAnalyzer()

results = []
for site in websites:
    result = analyzer.analyze_website(site)
    results.append(result)
    
# Compare color palettes
for result in results:
    if result['success']:
        colors = result['colors']['palette_analysis']['primary_colors']
        print(f"{result['domain']}: {colors}")
```

## 🤝 Contributing

### Feature Requests
- Additional color space support (LAB, XYZ)
- Advanced typography metrics
- Website comparison tools
- Color accessibility recommendations

### Bug Reports
Please include:
1. Website URL being analyzed
2. Error messages and logs
3. Python and dependency versions
4. System information (OS, Chrome version)

## 📞 Support

### Quick Start Checklist
- [ ] Python 3.7+ installed
- [ ] Chrome browser installed  
- [ ] Dependencies installed (`pip install -r requirements.txt`)
- [ ] Script permissions set (`chmod +x website_analyzer.py`)
- [ ] Target website is accessible

### Common Commands
```bash
# Test installation
python website_analyzer.py stats

# Basic analysis
python website_analyzer.py analyze https://example.com

# Color palette only
python website_analyzer.py palette https://example.com -v

# Custom output directory
python website_analyzer.py analyze https://example.com -o custom_dir
```

### Dependency Installation Help

**For Ubuntu/Debian:**
```bash
sudo apt update
sudo apt install python3-pip google-chrome-stable
pip3 install -r requirements.txt
```

**For macOS:**
```bash
brew install python3
brew install --cask google-chrome
pip3 install -r requirements.txt
```

**For Windows:**
1. Install Python from python.org
2. Install Chrome from google.com/chrome
3. Run: `pip install -r requirements.txt`

---

**Happy Design Analysis! 🎨**

**Remember**: This tool is for research and inspiration. Always respect website terms of service and consider performance impact when analyzing sites. 