Metadata-Version: 2.4
Name: html2pix
Version: 0.6.3
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Multimedia :: Video
Requires-Dist: numpy>=1.24.4
Requires-Dist: pillow>=10.4.0
License-File: LICENSE
License-File: THIRD-PARTY-LICENSES.html
Summary: Fast HTML to pixel rendering using Rust and Blitz. Generate production slates, overlays, and presentations.
Keywords: html,rendering,image,video,slate,presentation,rust,blitz
Author-email: Mel Massadian <7041726+melMass@users.noreply.github.com>
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# html2pix

[![CI](https://github.com/melMass/html2pix/actions/workflows/ci.yml/badge.svg)](https://github.com/melMass/html2pix/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/html2pix)](https://pypi.org/project/html2pix)
[![version](https://img.shields.io/badge/version-v0.6.3-blue)](https://pypi.org/project/html2pix)

Fast HTML to pixel rendering using Rust and [Blitz](https://github.com/DioxusLabs/blitz). Generate production slates, video overlays, and presentation graphics from HTML/CSS templates.


## ✨ Features

- 🎨 **Modern CSS Support**: Gradients, flexbox, grid, border-radius, shadows
- 📝 **Professional Templates**: Presentation templates (title cards, credits, quotes, chapters)
- 🎬 **Video Slate Generation**: Production-ready metadata overlays for videos
- 🖼️ **Image Compositing**: Alpha blend HTML over images and video frames
- 🎯 **RGB/RGBA Output**: Full transparency support
- 💅 **CSS Styling**: Complete CSS customization
- ⚡ **SIMD-Accelerated**: 4x faster compositing using vector instructions
- 🚀 **Native Performance**: Built with Rust/PyO3 for speed
- 🔌 **ComfyUI Integration**: Optional node for ComfyUI workflows

## 🚀 Installation

### From PyPI

```bash
# Standard installation
pip install html2pix

# With ComfyUI support
pip install html2pix[comfyui]
```

### CLI binary

Prebuilt binaries for macOS, Linux (glibc + static musl), and Windows are on the
[downloads page](https://melmass.github.io/html2pix/). Once installed, the CLI
updates itself in place:

```bash
html2pix --self-update          # install the latest release
html2pix --self-update --check  # only report whether one is available
```

### From Source

Requires:
- **Rust toolchain**: Install from [rustup.rs](https://rustup.rs)
- **Python 3.10+**

```bash
git clone https://github.com/melMass/html2pix.git
cd html2pix

# Install with uv (recommended - avoids caching issues)
uv pip install maturin
uv run maturin develop --uv --release

# Or with pip
pip install maturin
maturin develop --release
```

## 📖 Usage

### Python API

#### Basic HTML Rendering

```python
from html2pix_ext import render_html
from pathlib import Path
import numpy as np

# Render HTML to pixels
html = "<h1>Hello World</h1>"
image = render_html(
    html=html,
    css_override=None,
    width=800,
    height=600,
    bg_color=(255, 255, 255, 255),
    input_image=None,
    output_format="RGBA",
    scale_factor=1.0,        # DPI scaling (1.0=normal, 2.0=retina)
    color_scheme="light",    # "light" or "dark"
    time=0.0,                # Animation time in seconds
    resources=None           # Optional: custom fonts/images
)

# Result is numpy array (batch, height, width, channels)
print(image.shape)  # (1, 600, 800, 4)
```

#### Using Custom Fonts

```python
from pathlib import Path

# Load custom font
font_data = Path('fonts/Inter-Bold.woff2').read_bytes()

html = """
<style>
@font-face {
  font-family: 'Inter';
  src: url('Inter-Bold.woff2');
}
h1 { font-family: 'Inter', sans-serif; }
</style>
<h1>Custom Typography!</h1>
"""

image = render_html(
    html=html,
    width=800,
    height=600,
    resources={
        'Inter-Bold.woff2': font_data  # Clean API with Path().read_bytes()
    }
)
```

#### Using Templates

```python
from templates import render_template

# Render a title card
html, css = render_template('title_card', {
    'title': 'Neural Dreams',
    'subtitle': 'A journey through artificial imagination',
    'info': 'Production Company',
    'bottom_text': '2024 • Runtime 4:48'
})

# Render to pixels
image = render_html(
    html=html,
    css_override=css,
    width=1920,
    height=1080,
    bg_color=(10, 10, 10, 255),
    input_image=None,
    output_format="RGBA"
)
```

### Available Templates

**Professional Design System** - All templates follow a minimalist, sophisticated aesthetic:

1. **`title_card`** - Bold, centered title cards for opening sequences
2. **`chapter_card`** - Minimal section markers with timestamps
3. **`quote_card`** - Elegant text presentation with attribution
4. **`credits_card`** - End credits style with role/name pairs
5. **`minimal_overlay`** - Subtle corner text (4-position support)

### Video Processing

**Simple watermark** (3 lines):
```python
from html2pix.video import apply_html_overlay

html = '<div style="position: absolute; top: 20px; left: 20px;">My Watermark</div>'
apply_html_overlay('input.mp4', 'output.mp4', html)
```

**Dynamic per-frame overlays**:
```python
from html2pix.video import process_video

def add_frame_counter(frame, frame_num, info):
    html = f'<div>Frame: {frame_num}/{info["total_frames"]}</div>'
    frame_batch = frame[np.newaxis, ...]
    result = render_html(html, width=info['width'], height=info['height'], input_image=frame_batch)
    return result[0]

process_video('input.mp4', 'output.mp4', add_frame_counter)
```

**VFX breakdown slates**:
```python
from html2pix import generate_video_slate_html
from html2pix.video import process_video

metadata = {
    'title': 'VFX Shot Breakdown',
    'fps': 25,
    'total_frames': 121,
    'inference_settings': {'model': 'SDXL', 'steps': 50},
    'prompt': 'Cinematic establishing shot...'
}

html, css = generate_video_slate_html(metadata, layout='side-by-side')

def add_slate(frame, frame_num, info):
    # Your slate compositing logic here
    ...

process_video('input.mp4', 'output_with_slate.mp4', add_slate)
```

See [examples/showcase_video.py](examples/showcase_video.py) for complete examples.

### ComfyUI Integration

When installed with `pip install html2pix[comfyui]`:

1. Copy `__init__.py` to `ComfyUI/custom_nodes/html2pix/`
2. Restart ComfyUI
3. Find node under `mtb/render → HTML Render (Blitz)`

## 🎬 Template Examples

All templates render at 1920x1080 with professional typography and spacing:

### Title Card
```python
render_template('title_card', {
    'title': 'Neural\nDreams',
    'subtitle': 'A journey through artificial imagination',
    'info': 'Production Company',
    'bottom_text': '2024 • Runtime 4:48'
})
```

### Quote Card
```python
render_template('quote_card', {
    'context': 'On Creation',
    'quote': 'The machine does not dream, but it learns to paint our dreams.',
    'attribution': '— Unknown Artist, 2024'
})
```

### Credits Card
```python
render_template('credits_card', {
    'title': 'Neural Dreams',
    'credits': [
        {'role': 'Directed by', 'name': 'Mel Massadian'},
        {'role': 'Generated with', 'name': 'Stable Diffusion XL'},
        {'role': 'Rendered by', 'name': 'html2pix'},
    ],
    'closing': 'Thank you for watching'
})
```

## 🏗️ Architecture

```
html2pix/
├── __init__.py                  # Python API + ComfyUI node (optional)
├── templates.py                 # Professional template system
├── slate_compositor.py          # Reference image compositing
├── frame_scaler.py              # Video/image scaling utilities
├── render_full_video.py         # Full video processing
├── extension/                   # Rust rendering engine
│   ├── Cargo.toml               # Dependencies (Blitz, wide for SIMD)
│   └── src/lib.rs               # SIMD-optimized compositor
└── pyproject.toml               # Package configuration
```

### How It Works

1. **HTML/CSS Parsing** → Blitz HtmlDocument with style resolution
2. **Layout Engine** → Compute flexbox, grid, and positioning
3. **Rendering** → Blitz paints to RGBA buffer via CPU renderer
4. **SIMD Compositing** → Alpha blend using vectorized operations (4 pixels/instruction)
5. **Batch Processing** → Composite HTML over video frames or images
6. **Output** → Return as numpy arrays (batch, height, width, channels)

#### SIMD Acceleration

The compositor uses **SIMD (Single Instruction, Multiple Data)** for 4x faster alpha blending:

```rust
// Traditional: Process 1 pixel at a time
for pixel in pixels {
    out = html * alpha + bg * (1 - alpha)  // 1 pixel per cycle
}

// SIMD: Process 4 pixels with ONE instruction
let pixels_vec = f32x4::new([p1, p2, p3, p4]);
let out = html * alphas + bg * one_minus_alpha;  // 4 pixels per cycle!
```

**Performance:**
- 1920×1080 render: **~65ms** (down from ~100-150ms)
- Uses `f32x4` vectors via the `wide` crate
- Maps to native CPU instructions (SSE/AVX on x86, NEON on ARM)

## 🔧 Technical Details

### Dependencies

**Core:**
- numpy >=1.24.4
- pillow >=10.4.0

**Optional (ComfyUI):**
- torch >=2.0.0

**Rust (Bundled in wheels):**
- Blitz (commit `2044d690`) - HTML/CSS rendering
- PyO3 (0.22) - Python bindings
- anyrender_vello_cpu (0.7) - CPU renderer with multithreading
- wide (0.7) - Portable SIMD intrinsics

### Performance

- **Rendering**: SIMD-accelerated, ~65ms for 1920x1080
- **Compositing**: 4x faster with f32x4 vector operations
- **Video Processing**: Efficient frame-by-frame with progress
- **Build Time**: ~6-8 seconds (incremental), ~2 minutes (clean)
- **Tested**: Up to 1920x1080 @ 25fps, 121-frame videos

### Supported CSS Features

✅ Flexbox & Grid layouts
✅ Gradients (linear, radial)
✅ Border radius & box shadows
✅ Typography (font-size, weight, color, line-height)
✅ Padding, margin, spacing
✅ Colors (hex, rgb, rgba)
✅ Text anti-aliasing & smooth rendering

## 🚧 Limitations

- Custom resources must be pre-loaded (no live HTTP/filesystem loading)
- CPU rendering only (no GPU acceleration yet)
- No JavaScript support (static HTML/CSS only)
- Blitz is pre-alpha (some advanced CSS features may be incomplete)

## 🗺️ Roadmap

- [x] Multi-platform wheel builds (Linux, macOS, Windows)
- [x] Professional template system
- [x] Video slate generation
- [x] SIMD-accelerated compositing
- [x] Custom font/image loading (pre-bundle API)
- [ ] Publish to PyPI
- [ ] GPU renderer option
- [ ] Auto-loading resources from filesystem/HTTP
- [ ] More template styles
- [ ] CSS animation support (time parameter ready)

## 📚 Documentation

- **[BLITZ_API.md](BLITZ_API.md)**: Blitz rendering API
- **[CLAUDE.md](CLAUDE.md)**: Development log and technical decisions

## 🤝 Contributing

Contributions welcome! The package is structured to make ComfyUI integration optional while providing a powerful standalone Python library.

## 📄 License

MIT License - See LICENSE file

## 🙏 Credits

- **[Blitz](https://github.com/DioxusLabs/blitz)** by DioxusLabs - Blazing fast HTML/CSS rendering engine
- **[wide](https://github.com/Lokathor/wide)** by Lokathor - Portable SIMD intrinsics for Rust
- Built with Rust, PyO3, and love for beautiful design

## 🔗 Links

- **PyPI**: https://pypi.org/project/html2pix/
- **GitHub**: https://github.com/melMass/html2pix
- **Issues**: https://github.com/melMass/html2pix/issues

