# PureSVG - Pure Python SVG Renderer

A pure Python library for rendering SVG files to numpy bitmap arrays without external rendering dependencies.

## Features

- **Pure Python**: Uses only Python standard library + numpy/scipy (no Cairo, librsvg, or other C dependencies)
- **Cross-Platform**: Works on Windows, macOS, and Linux
- **Numpy Output**: Renders to numpy RGBA arrays for easy integration with scientific Python ecosystem
- **SVG 1.1 Support**: Handles basic shapes, transforms, styling, and paths
- **Type-Safe**: Full type hints with mypy strict mode
- **Well-Tested**: 85%+ test coverage with contract, integration, and unit tests

## Installation

```bash
pip install puresvg
```

For development:

```bash
git clone https://github.com/puresvg/puresvg.git
cd puresvg
pip install -e ".[dev]"
```

## Quick Start

```python
import puresvg
import numpy as np

# Render SVG file to numpy array with default 4x anti-aliasing
array = puresvg.render('logo.svg', width=256, height=256)
print(array.shape)  # (256, 256, 4) - RGBA

# Render from SVG string
svg_content = '''
<svg width="100" height="100">
    <circle cx="50" cy="50" r="40" fill="blue"/>
</svg>
'''
array = puresvg.render(svg_content, width=100, height=100)

# Parse SVG to document object
doc = puresvg.parse('drawing.svg')
array = doc.render(width=512, height=512)
```

## Anti-Aliasing with Supersampling

PureSVG provides high-quality anti-aliasing through supersampling with Pillow integration. The `supersample` parameter controls rendering quality:

```python
from puresvg import render

# Default 4x supersampling (balanced quality/performance)
image = render("icon.svg", width=256, height=256)

# Performance mode: no anti-aliasing (fastest, for large images)
image = render("background.svg", width=1920, height=1080, supersample=1)

# Light anti-aliasing: 2x supersampling
image = render("graphic.svg", width=512, height=512, supersample=2)

# Maximum quality: 8x supersampling (best for small icons/logos)
image = render("logo.svg", width=128, height=128, supersample=8)
```

**Supersample Factors**:
- `1`: No anti-aliasing (fastest, no downsampling overhead)
- `2`: Light anti-aliasing (2x faster than 4x, good for draft previews)
- `4`: **Default** - optimal quality/performance balance for most use cases
- `8`: Maximum quality (4x slower than 4x, best for retina display icons)

**Technical Details**:
- Uses hybrid rendering: numpy scanline rasterizer + Pillow LANCZOS downsampling
- Memory usage: ~16× peak during supersampling (e.g., 4x @ 256×256 = 64MB intermediate)
- Performance: ~11s for 256×256 @ 4x (CPU-intensive scanline algorithm)
- 100% backward compatible: existing code works unchanged with improved quality

## Supported Features

### Shapes (US1 - Priority P1)
- Rectangle (`<rect>`)
- Circle (`<circle>`)
- Ellipse (`<ellipse>`)
- Line (`<line>`)
- Polyline (`<polyline>`)
- Polygon (`<polygon>`)
- Path (`<path>`) with M, L, C, Q, A, Z commands

### Transforms (US2 - Priority P2)
- translate, rotate, scale
- skewX, skewY, matrix
- Nested group transforms

### Styling (US3 - Priority P3)
- Fill colors (hex, rgb, rgba, named)
- Stroke colors and width
- Opacity (fill-opacity, stroke-opacity, overall)

### Text (US4 - Priority P4)
- Basic text rendering (planned)

## Requirements

### Python Version
- Python 3.11 or higher required
- Tested on Python 3.11, 3.12, and 3.13

### Dependencies

PureSVG automatically installs these required dependencies:

- **numpy >= 1.24.0** - Numerical computing and array operations
- **scipy >= 1.11.0** - Scientific computing utilities (used for advanced path operations)
- **Pillow >= 10.0.0** - Python Imaging Library (used internally for color management)

All dependencies are automatically installed when you install puresvg via pip. No manual installation needed.

### Optional Development Dependencies

For contributors and developers:

```bash
pip install -e ".[dev]"
```

This installs additional tools:
- **pytest** - Testing framework
- **pytest-cov** - Coverage reporting
- **hypothesis** - Property-based testing
- **mypy** - Static type checker
- **ruff** - Fast Python linter
- **black** - Code formatter
- **build** - Package building tool
- **twine** - PyPI publishing tool

## Accessing Package Metadata

### Version Information

You can access the package version in multiple ways:

**Method 1: Direct attribute access**
```python
import puresvg
print(puresvg.__version__)  # Output: 0.1.0
```

**Method 2: Using importlib.metadata (Python 3.8+)**
```python
from importlib.metadata import version
print(version('puresvg'))  # Output: 0.1.0
```

### Full Metadata

Access complete package metadata including dependencies, license, and more:

```python
from importlib.metadata import metadata

meta = metadata('puresvg')
print(f"Name: {meta['Name']}")                    # puresvg
print(f"Version: {meta['Version']}")              # 0.1.0
print(f"Summary: {meta['Summary']}")              # Package description
print(f"License: {meta.get('License')}")          # MIT
print(f"Python: {meta['Requires-Python']}")       # >=3.11

# List all dependencies
requires = meta.get_all('Requires-Dist') or []
for req in requires:
    print(f"  - {req}")
```

This is useful for:
- Programmatic version checking in scripts
- Compatibility validation before import
- Automated dependency auditing
- Integration with version management tools

## Performance

- Typical 256x256 icon with 10-20 shapes: < 100ms
- Memory usage: < 10MB per megapixel
- Supports output up to 4096x4096 pixels

## Contributing

Contributions welcome! For development setup and guidelines, see below.

### Development Setup

```bash
# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Type checking
mypy puresvg

# Linting
ruff check puresvg

# Formatting
black puresvg tests
```

### Running Tests

PureSVG uses pytest with custom markers to organize tests by type and speed. **By default, slow tests are excluded** for faster development iteration.

**Fast Development Tests** (default):
```bash
pytest
```
This excludes slow packaging/installation tests and completes in ~2-3 minutes, providing faster feedback during development.

**Complete Test Suite** (including slow tests):
```bash
pytest -m "slow or not slow"
```
Runs all tests including slow tests (packaging validation, performance benchmarks). Takes ~25-30 minutes.

**Slow Tests Only** (for packaging/performance testing):
```bash
pytest -m slow
```
Runs only tests marked as slow (packaging, installation, performance benchmarks).

**Note**: To override the default and run all tests, use `pytest -m "slow or not slow"`.

**Test Categories**:
- `contract` - Public API stability tests
- `integration` - End-to-end workflow tests
- `unit` - Individual component tests
- `slow` - Tests taking over 5 seconds (packaging, installation, etc.)

**Coverage Reporting**:
```bash
pytest -m "not slow" --cov=puresvg --cov-report=html
```

**When to Run Slow Tests**:
- After completing all implementation phases
- Before creating pull requests
- When working on packaging or installation features
- In CI/CD pipelines (automatic)

See [Testing Guidelines](.specify/docs/testing-guidelines.md) for more details on test organization and marking criteria.

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Architecture

PureSVG follows a library-first architecture with clear separation of concerns:

- `puresvg.parser` - SVG XML parsing to element tree
- `puresvg.shapes` - Geometric shape primitives
- `puresvg.transforms` - Affine transformation matrices
- `puresvg.styles` - Style parsing and inheritance
- `puresvg.colors` - Color format parsing
- `puresvg.rasterizer` - Scanline rasterization with anti-aliasing
- `puresvg.canvas` - Bitmap canvas and compositing
- `puresvg.renderer` - High-level rendering API

## Project Status

**Current Version**: 0.1.0 (Alpha)

### SVG Rendering Feature (001-svg-bitmap-renderer)
- ✅ Phase 1: Setup complete
- ✅ Phase 2: Foundational infrastructure complete
- ✅ Phase 3: US1 - Basic shape rendering (MVP)
- ✅ Phase 4-6: US2-US4 implementation complete
- ⏳ Phase 7: Polish and optimization (in progress)

### PIP Packaging Feature (002-pip-packaging)
- ✅ US1: Install via pip (P1 - MVP) - Complete
- ✅ US2: Source/editable install (P2) - Complete
- ✅ US3: Dependency management (P2) - Complete
- ✅ US4: Build distributions (P3) - Complete
- ✅ US5: Metadata access (P3) - Complete
- 🚧 Final polish: Documentation and multi-Python testing (7/67 tasks remaining)

**Overall Progress**: Production-ready package with 133 passing tests. Ready for PyPI publication.

## Resources

- [Documentation](https://puresvg.readthedocs.io)
- [Issue Tracker](https://github.com/puresvg/puresvg/issues)
- [Specification](specs/001-svg-bitmap-renderer/spec.md)
- [Implementation Plan](specs/001-svg-bitmap-renderer/plan.md)

## Acknowledgments

Built following the [PureSVG Constitution](.specify/memory/constitution.md) principles:
- Library-First Architecture
- Pythonic Simplicity
- Test-First Development (TDD)
- Type Safety & Documentation
- Observability & Debugging
