Metadata-Version: 2.4
Name: pysvgenius
Version: 0.1.6
Summary: A library for text_to_svg, image_to_svg, and SVG resizing and optimization.
Home-page: https://github.com/tamchamchi/pysvgenius
Author: Anh Nguyen
Author-email: anhndt.work@gmail.com
License: MIT
Project-URL: Bug Tracker, https://github.com/tamchamchi/pysvgenius/issues
Project-URL: Documentation, https://github.com/tamchamchi/pysvgenius#readme
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: accelerate<2.0,>=1.0
Requires-Dist: antlr4-python3-runtime==4.9.3
Requires-Dist: beautifulsoup4>=4.12
Requires-Dist: bitsandbytes>=0.46.0
Requires-Dist: bleach>=6.1
Requires-Dist: cairocffi>=1.6
Requires-Dist: CairoSVG>=2.8
Requires-Dist: certifi>=2024.2
Requires-Dist: cffi>=1.15
Requires-Dist: charset-normalizer>=3.0
Requires-Dist: coloredlogs>=15.0
Requires-Dist: contourpy>=1.2
Requires-Dist: cryptography>=41.0
Requires-Dist: cssselect2>=0.7
Requires-Dist: cycler>=0.12
Requires-Dist: defusedxml>=0.7
Requires-Dist: diffusers>=0.32
Requires-Dist: docutils>=0.21
Requires-Dist: filelock>=3.12
Requires-Dist: fonttools>=4.50
Requires-Dist: fsspec>=2024.3
Requires-Dist: ftfy>=6.1
Requires-Dist: greenlet>=3.0
Requires-Dist: huggingface-hub>=0.32
Requires-Dist: humanfriendly>=10.0
Requires-Dist: imageio>=2.34
Requires-Dist: imageio-ffmpeg>=0.5
Requires-Dist: iopath>=0.1
Requires-Dist: Jinja2>=3.1
Requires-Dist: jsonpatch>=1.32
Requires-Dist: jsonpointer>=2.4
Requires-Dist: jeepney>=0.9
Requires-Dist: keyring>=24.0
Requires-Dist: kiwisolver>=1.4
Requires-Dist: kmeans-gpu>=0.0.5
Requires-Dist: kornia>=0.7
Requires-Dist: kornia_rs>=0.1.5
Requires-Dist: lazy_loader>=0.3
Requires-Dist: llvmlite>=0.43
Requires-Dist: lxml>=4.9
Requires-Dist: markdown-it-py>=3.0
Requires-Dist: MarkupSafe>=2.1
Requires-Dist: matplotlib>=3.8
Requires-Dist: mdurl>=0.1
Requires-Dist: more-itertools>=10.0
Requires-Dist: mpmath>=1.3
Requires-Dist: networkx>=3.2
Requires-Dist: nh3>=0.2
Requires-Dist: numpy<2.0,>=1.26
Requires-Dist: omegaconf>=2.3
Requires-Dist: opencv-python>=4.8
Requires-Dist: pandas>=2.2
Requires-Dist: pillow>=10.2
Requires-Dist: pluggy>=1.4
Requires-Dist: portalocker>=3.1
Requires-Dist: protobuf>=5.26
Requires-Dist: pyaml>=24.0
Requires-Dist: pycparser>=2.21
Requires-Dist: pyparsing>=3.1
Requires-Dist: pytest>=8.1
Requires-Dist: python-dotenv>=1.0
Requires-Dist: python-slugify>=8.0
Requires-Dist: pytz>=2024.1
Requires-Dist: PyYAML>=6.0
Requires-Dist: readme_renderer>=43
Requires-Dist: regex>=2024.0
Requires-Dist: requests>=2.31
Requires-Dist: requests-toolbelt>=1.0
Requires-Dist: rfc3986>=2.0
Requires-Dist: rich>=13.0
Requires-Dist: safetensors>=0.4
Requires-Dist: scikit-image<0.23,>=0.21
Requires-Dist: scipy<1.14,>=1.10
Requires-Dist: scour>=0.38
Requires-Dist: seaborn>=0.13
Requires-Dist: SecretStorage>=3.3
Requires-Dist: sentencepiece>=0.2
Requires-Dist: SQLAlchemy>=2.0
Requires-Dist: sympy>=1.12
Requires-Dist: text-unidecode>=1.3
Requires-Dist: tifffile>=2023.12
Requires-Dist: tinycss2>=1.2
Requires-Dist: tokenizers>=0.19
Requires-Dist: tomli>=2.0
Requires-Dist: torch>=2.1
Requires-Dist: torchaudio>=2.1
Requires-Dist: torchvision>=0.18
Requires-Dist: tqdm>=4.66
Requires-Dist: transformers>=4.40
Requires-Dist: triton>=3.0
Requires-Dist: ttools>=0.1
Requires-Dist: twine>=5.0
Requires-Dist: tzdata>=2024.1
Requires-Dist: urllib3>=2.2
Requires-Dist: vtracer>=0.6
Requires-Dist: webencodings>=0.5
Requires-Dist: websocket-client>=1.7
Provides-Extra: diffvg
Provides-Extra: clip
Provides-Extra: diff-jpeg
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

<h1 align="center">✨ Pysvgenius ✨</h1>

<p align="center">
<b>Text ➜ SVG | Image ➜ SVG | Smart SVG Resizing</b><br>
Turn your text or images into optimized, scalable SVGs effortlessly.
</p>

<p align="center">
  <a href="https://pypi.org/project/pysvgenius/">
    <img src="https://img.shields.io/pypi/v/pysvgenius?color=blue&label=PyPI" alt="PyPI Version">
  </a>
  <a href="https://github.com/tamchamchi/pysvgenius/blob/main/LICENSE">
    <img src="https://img.shields.io/github/license/tamchamchi/pysvgenius" alt="License">
  </a>
  <a href="https://www.python.org/">
    <img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python">
  </a>
  <a href="https://github.com/tamchamchi/pysvgenius/stargazers">
    <img src="https://img.shields.io/github/stars/tamchamchi/pysvgenius?style=social" alt="GitHub Stars">
  </a>
</p>

---

## 📖 Description

**Pysvgenius** is a powerful Python library designed for **generating and optimizing scalable vector graphics (SVGs)**. It provides an end‑to‑end workflow that includes:
- **Text‑to‑SVG**: Generate SVG illustrations directly from text prompts.

- **Image‑to‑SVG**: Convert raster images into clean, scalable vector graphics.

- **Smart SVG Optimization & Resizing**: Optimize paths and file size while preserving visual quality.

With **Pysvgenius**, you can effortlessly create high‑quality SVGs for **design**, **AI applications**, and **modern web projects**, ensuring both **scalability** and **efficiency**.


## 🖼️ Demo

<div align="center">

| Input | Text-to-Image | Image-to-SVG | Optimized SVG |
|-------|---------------|--------------|---------------|
| **"A lighthouse overlooking the ocean"** | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/lighthouse_image.png" width="150" alt="Generated Image"> | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/lighthouse_svg.svg" width="150" alt="SVG Conversion"> | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/lighthouse_optimized.svg" width="150" alt="Optimized SVG"> |
| **"A serene Asian dragon"** | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/dragon_image.png" width="150" alt="Dragon Image"> | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/dragon_svg.svg" width="150" alt="Dragon SVG"> | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/dragon_optimized.svg" width="150" alt="Dragon Optimized"> |
| **"Futuristic skyscraper with neon lights"** | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/skyscraper_image.png" width="150" alt="Skyscraper Image"> | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/skyscraper_svg.svg" width="150" alt="Skyscraper SVG"> | <img src="https://raw.githubusercontent.com/tamchamchi/pysvgenius/main/assets/skyscraper_optimized.svg" width="150" alt="Skyscraper Optimized"> |

</div>

## 🖥️ System Requirements

To install and run **pysvgenius** smoothly, we recommend the following minimum setup:

- **OS**: Linux / macOS / Windows 10+ (x86_64)
- **Python**: 3.10 or higher  
- **CPU**: 4 cores (Intel i5/Ryzen 5 or higher)  
- **RAM**: 16 GB minimum (24 GB recommended for large models)  
- **Storage**: ~30 GB for models & caches  
- **GPU**: NVIDIA GPU with CUDA 11+ for faster generation and DiffVG optimization  
  - Recommended: 16 GB VRAM or more  

> ⚡ **Tip**: CPU-only mode works but is slower for image generation and optimization.
## 📦 Installation
```bash
# Basic installation
pip install pysvgenius

# With OpenAI CLIP support
pip install git+https://github.com/openai/CLIP.git
```
### 🔧 (Optional) Build DiffVG and Diff-JPEG for Optimizer


To use advanced **SVG optimization** features, you need to build [diffvg](https://github.com/BachiLi/diffvg) from source.

```bash
# 1. DiffVG (SVG optimizer)
git clone https://github.com/BachiLi/diffvg.git
cd diffvg

git submodule update --init --recursive

pip install svgwrite
pip install svgpathtools
pip install cssutils
pip install numba
pip install torch-tools
pip install visdom

python setup.py install

# 2. Diff-JPEG (Differentiable JPEG compression)
pip install git+https://github.com/necla-ml/Diff-JPEG
```
## 🚀 Usage

### 1️⃣ Text-to-SVG Generation
Generate SVGs directly from text prompts using the built-in generator:

```python
from pysvgenius.generator import load_generator
from pysvgenius.common import registry

# List all available generator models
print(registry.list_generator())  

# Load the generator (example: SDXL-Turbo)
generator = load_generator("sdxl-turbo")

# Generate 5 SVGs from a text prompt
images = generator("A lighthouse overlooking the ocean", num_images=5)

# images is a list of PIL.Image objects or SVG paths depending on the mode
for idx, img in enumerate(images):
    img.save(f"lighthouse_{idx}.png")
```
### 2️⃣ Image-to-SVG Converter
Convert images to SVG paths with the built-in converters:

```python
from pysvgenius.converter import load_converter
from pysvgenius.common import registry

# List all available converters
print(registry.list_converter())

# Load the converter (example: VTracer Binary Search)
converter = load_converter("vtracer-binary-search")

# Convert an image to SVG paths
# `image` can be a PIL.Image or a path to an image
svgs = converter(image, limit=10000)

# `svgs` is a list of SVG path strings
for idx, svg in enumerate(svgs):
    with open(f"output_{idx}.svg", "w") as f:
        f.write(svg)
```
## 3️⃣ SVG Ranking (Optional)

After generating SVG candidates, you can **rank** them using different strategies:

- **Aesthetic Ranker** → Scores based on visual aesthetics.  
- **SigLIP Ranker** → Scores based on semantic similarity to a text prompt.

```python
from pysvgenius import setup_path
from pysvgenius.ranker import load_ranker
from pysvgenius.common import registry

# ✅ Setup paths (run ONCE at the start of your script)
setup_path()

# Check available rankers
print(registry.list_ranker())

# Load rankers
aesthetic_ranker = load_ranker("aesthetic")
siglip_ranker = load_ranker("siglip")

# Rank purely by visual aesthetics (top 5 SVGs)
aesthetic_results, score = aesthetic_ranker(svgs=svgs, top_k=5)

# Rank by semantic similarity to a text prompt (top 1 SVG)
prompt = "a serene Asian dragon flying over green mountains"
siglip_results, score = siglip_ranker(svgs=svgs, prompt=prompt, top_k=1)

print("Aesthetic Ranking:", aesthetic_results)
print("SigLIP Ranking:", siglip_results)
```
## 4️⃣ Optimize SVGs with DiffVG (Optional)
```python
from pysvgenius.optimizer import load_optimizer
from pysvgenius import load_config, setup_path

# Initialize paths and configuration
setup_path()                     # Run once before loading any model
config = load_config()           # Load default configuration
args = config.optimizer_cfg["diffvg"]["args"]  # Get DiffVG optimizer arguments

# Load the DiffVG Optimizer
optimizer = load_optimizer("diffvg")

# Optimize the SVG based on the original image
# ⚠ Note: 'limit' should match the converter's limit for the best results
optimized_svg = optimizer(
    svg=svgs[0],         # Input SVG
    image=image,         # Original image for comparison
    args=args,           # Optimizer arguments
    limit=20000          # Sampling points, ideally the same as converter's limit
)
```
## 📂 Project Structure

```
pysvgenius/
├── src/
│   ├── generator/          # Text-to-image generation models
│   │   ├── sdxl_turbo_generator.py
│   │   ├── factory.py
│   │   └── base.py
│   ├── converter/          # Image-to-SVG conversion
│   │   ├── vtracer.py
│   │   ├── factory.py
│   │   └── base.py
│   ├── ranker/            # Aesthetic & similarity ranking
│   │   ├── aesthetic_ranker.py
│   │   ├── siglip_ranker.py
│   │   ├── paligemma_ranker.py
│   │   ├── factory.py
│   │   └── base.py
│   ├── optimizer/         # SVG optimization with DiffVG
│   │   ├── diffvg_optimizer.py
│   │   ├── factory.py
│   │   └── base.py
│   ├── utils/             # Utilities and helpers
│   │   ├── image_utils.py
│   │   ├── svg_utils.py
│   │   └── logger.py
│   └── services/          # Service layer
├── configs/               # Configuration files
│   └── configs.yaml
├── models/               # Pre-trained model cache
├── data/                 # Test data and results
│   ├── test/            # Sample input files
│   └── results/         # Output results
├── notebooks/            # Example notebooks
```
## 📚 References & Acknowledgments

This project builds upon the amazing work of the following projects and research:

1. **VTracer** – Vector image tracer  
   - [GitHub](https://github.com/visioncortex/vtracer)

2. **CLIP** – Connecting vision and language  
   - [OpenAI CLIP](https://github.com/openai/CLIP)

3. **Improved Aesthetic Predictor**  
   - [GitHub](https://github.com/christophschuhmann/improved-aesthetic-predictor)

4. **DiffVG** – Differentiable Vector Graphics  
   - Li, Tzu-Mao, et al. *"Differentiable Vector Graphics Rasterization for Editing and Learning."*  
     [Paper](https://arxiv.org/abs/2005.13084) | [GitHub](https://github.com/BachiLi/diffvg)

5. **Hugging Face Transformers** – Model hosting and inference  
   - [Hugging Face](https://huggingface.co/)

6. **Kaggle: Drawing with LLMs** – Discussion and inspiration  
   - [Kaggle Discussion](https://www.kaggle.com/competitions/drawing-with-llms/discussion/581024)

## 🤝 Contributing
Contributions are welcome! Please open an issue or submit a pull request.
