Metadata-Version: 2.5
Name: smallpict
Version: 0.0.7
Summary: Official Python SDK for SmallPict Image Optimization API
Project-URL: Homepage, https://smallpict.app
Project-URL: Repository, https://github.com/smallPict/smallpict-python
Project-URL: Documentation, https://smallpict.app/docs/sdks/python
Project-URL: Changelog, https://github.com/smallPict/smallpict-python/blob/main/CHANGELOG.md
Author-email: SmallPict Engineering <support@smallpict.app>
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
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: Topic :: Multimedia :: Graphics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: respx>=0.21.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: pil
Requires-Dist: pillow>=9.0.0; extra == 'pil'
Description-Content-Type: text/markdown

# SmallPict Python SDK

Official Python client for the [SmallPict Image Optimization API](https://smallpict.app) — high-performance next-gen image transcoding (AVIF, WebP), smart compression, Edge CDN delivery, and cache purging.

[![PyPI version](https://img.shields.io/pypi/v/smallpict.svg)](https://pypi.org/project/smallpict/)
[![Python versions](https://img.shields.io/pypi/pyversions/smallpict.svg)](https://pypi.org/project/smallpict/)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)

---

## ⚡ Features

- **🚀 Synchronous & Asynchronous:** First-class sync (`SmallPictClient`) and async (`AsyncSmallPictClient`) clients powered by `httpx`.
- **🖼️ Optional Pillow / PIL Support:** Optimize `PIL.Image` instances directly via `pip install smallpict[pil]`.
- **🛡️ Secure HMAC-SHA256 & Bearer Auth:** Tamper-proof payload verification.
- **✨ 4 Core Unified Methods:** `optimize()`, `get_quota()`, `purge_cdn()`, and `validate_key()`.
- **🔄 Resilience & Fault Tolerance:** Automatic `Idempotency-Key` UUID injection, 30s timeouts, and exponential backoff with jitter on HTTP 429/5xx.
- **🔒 Zero-Leak Privacy:** API keys and credentials are automatically redacted from error traces and logs.
- **🏷️ Fully Typed:** Complete type annotations (PEP 561 `py.typed`) and strict `mypy` compatibility.

---

## 📥 Installation

```bash
# Standard installation
pip install smallpict

# With optional Pillow / PIL integration
pip install "smallpict[pil]"

# With poetry
poetry add smallpict
```

---

## 🚀 Quick Start

### 1. Synchronous Example

```python
import os
from smallpict import SmallPictClient

client = SmallPictClient(
    api_key=os.environ["SMALLPICT_API_KEY"],
    secret_key=os.environ.get("SMALLPICT_SECRET_KEY"),
)

with open("hero-banner.png", "rb") as f:
    image_bytes = f.read()

result = client.optimize(
    image_bytes,
    filename="hero-banner.png",
    format="avif",
    quality=80,
    mode="lossy",  # "lossy" (default), "extreme", "lossless" or "auto", as your plan allows
    folder="blog/2026",  # optional: 1-3 segments, stored lower-cased; result.folder echoes it
    max_width=1920,
)

print(f"Optimized CDN URL: {result.url}")
print(f"Original: {result.original_size}B ➔ Compressed: {result.compressed_size}B")
print(f"Saved: {result.savings_percentage}% ({result.bytes_saved} bytes)")
```

Mode `auto` picks, per image, the lowest quality that keeps the visual score (SSIMULACRA 2) at or above 70, and ignores `quality`. It is on WP Pro and Business, Velocity, Momentum and sandbox keys (5 auto jobs per minute per sandbox key); where it cannot search (PNG or GIF output, animation, time limit) the job is `lossy` and `mode_applied` says so.

Mode `extreme` gives the smallest files on every plan. Leave `quality` out so the server uses its default for the output format; a `quality` you set is kept or raised to the format floor. Mode comparison: https://smallpict.app/en/docs/image-settings

```python
result = client.optimize(image_bytes, filename="hero-banner.png", format="avif", mode="extreme")
```

### 2. Asynchronous Example (FastAPI / Starlette)

```python
import os
from fastapi import FastAPI, UploadFile, File
from smallpict import AsyncSmallPictClient

app = FastAPI()
client = AsyncSmallPictClient(api_key=os.environ["SMALLPICT_API_KEY"])


@app.post("/upload")
async def upload_image(file: UploadFile = File(...)):
    contents = await file.read()
    
    result = await client.optimize(
        contents,
        filename=file.filename,
        format="auto", # Intelligently selects best format (AVIF/WebP)
        quality=85,
    )
    
    return {
        "url": result.url,
        "format": result.format,
        "saved_percentage": f"{result.savings_percentage}%",
    }
```

### 3. Celery Background Worker Task

```python
import os
from celery import Celery
from smallpict import SmallPictClient

app = Celery("tasks", broker="redis://localhost:6379/0")
client = SmallPictClient(api_key=os.environ["SMALLPICT_API_KEY"])


@app.task
def process_user_avatar(file_path: str):
    result = client.optimize(
        file_path,
        format="webp",
        quality=80,
        max_width=400,
        max_height=400,
    )
    return {"cdn_url": result.url, "bytes_saved": result.bytes_saved}
```

### 4. Optional Pillow / PIL Integration

```python
from PIL import Image
from smallpict import SmallPictClient

img = Image.open("photo.jpg")
# Crop or transform with Pillow
img_cropped = img.crop((0, 0, 800, 600))

client = SmallPictClient(api_key="sp_sdk_...")
result = client.optimize(img_cropped, format="avif", quality=85)
print(f"Delivered via CDN: {result.url}")
```

---

## 📊 Checking Quota & Invalidating CDN Cache

```python
from smallpict import SmallPictClient

client = SmallPictClient(api_key="sp_sdk_...")

# 1. Real-time quota metrics
quota = client.get_quota()
print(f"Plan: {quota.plan}, Used: {quota.quota_percentage}%")

# 2. Invalidate CDN cache
client.purge_cdn(["https://cdn.smallpict.app/opt/hero-banner.avif"])
print("CDN edge cache invalidated successfully.")

# 3. Invalidate one upload folder (limited to 10 per hour; PurgeType.ALL to 2 per hour).
# Over the limit raises RateLimitError (code purge_rate_limited), which is not retried.
from smallpict import PurgeType
client.purge_cdn(purge_type=PurgeType.FOLDER, folder="blog/2026")
```

### Capacity and upgrade links

`get_quota()` returns `capacity` for the product of your API key: `storage` (`limit_bytes`, `used_bytes`, `base_bytes`, `addon_blocks`), `cdn` (`limit_bytes`, `used_bytes`, `status`), `booster` balances (`active`, `wp_quota_bytes`, `api_transforms`, `cdn_bytes`, `next_expiry`), the unpaid-account state (`lapse`), `period_end` and `manage_url`. A member that does not apply to your plan is `None`; `capacity` is `None` when the server could not read it or is older. Capacity is read-only here: storage add-ons and boosters are bought in the dashboard.

Errors about capacity carry `upgrade_url`, the dashboard page where you add it (`None` when the error has none). `storage_quota_exceeded` and `account_read_only` raise `QuotaExceededError`; `mode_not_in_plan` raises `PermissionDeniedError` with `allowed_modes`. The SDK never opens these links; show them to your user.

```python
from smallpict import QuotaExceededError

capacity = client.get_quota().capacity
if capacity and capacity.storage:
    print(f"Storage: {capacity.storage.used_bytes} / {capacity.storage.limit_bytes} bytes")

try:
    client.optimize(image_bytes, filename="photo.jpg")
except QuotaExceededError as err:
    print(f"{err.message} Add capacity: {err.upgrade_url or 'https://smallpict.app/dashboard/billing'}")
```

---

## 🧪 Testing

```bash
pytest
mypy smallpict
ruff check .
```

---

## 🔒 Security & Schema Compatibility (2026)

- **`mime_type` & `content_type` Dual Support**: `OptimizeOptions` accepts both `mime_type` and `content_type` attributes. Conversion payloads sent by `SmallPictClient` and `AsyncSmallPictClient` populate both `mime_type` and `content_type` fields, ensuring zero-disruption compatibility across all SmallPict API versions.

---

## 📄 License

MIT © [SmallPict Engineering](https://smallpict.app)
