Metadata-Version: 2.5
Name: smallpict
Version: 0.0.8
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<1,>=0.24.0
Requires-Dist: pydantic<3,>=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: ruff>=0.1.0; extra == 'dev'
Provides-Extra: pil
Requires-Dist: pillow>=10.3.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]`.
- **🛡️ HMAC-SHA256 request signing:** every request is signed with your secret key; both `api_key` and `secret_key` are required.
- **✨ 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["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 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)")
```

### What `optimize()` does

The API is asynchronous: `POST /v1/optimize` queues a job and returns a pre-signed upload URL. `optimize()` runs the whole flow for you: it uploads the bytes to that URL (within the 30 seconds the worker waits for them), polls `GET /v1/optimize/status` every second, and returns once the job is `completed` with `url`, `format`, `bytes_saved`, `mode_applied`, `quality_applied` and `folder` from the job status. `url` for managed storage is a pre-signed link valid 10 minutes; `get_job_status(result.job_id)` returns a fresh one.

- A failed job raises `SmallPictError` whose `code` is `job_failed` and whose message is the server's (for example `client upload never arrived`); `details["job_id"]` names the job. A storage that refuses the upload raises `SmallPictError` with `code` `upload_failed` and the HTTP status.
- A job still running after `wait_timeout` (default 120 seconds) raises `TimeoutError` naming the job id; the job keeps running, so you can call `get_job_status()` later. `poll_interval` (default 1 second) sets the polling interval. Both are constructor arguments of `SmallPictClient` and `AsyncSmallPictClient`, in seconds: `SmallPictClient(api_key=..., poll_interval=0.5, wait_timeout=60)`.
- Pass bytes, a local file path, a binary file object or a PIL image. An `http(s)` URL raises `ValidationError`: the API does not fetch URLs, so download the image yourself first.

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"],
    secret_key=os.environ["SMALLPICT_SECRET_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"],
    secret_key=os.environ["SMALLPICT_SECRET_KEY"],
)


@app.task
def process_user_avatar(file_path: str):  # a local file path, not a URL
    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

A `PIL.Image` is re-encoded before upload: JPEG and WebP at `quality` or 95 when you set none, animated GIF and WebP with all their frames. Pass the original file bytes instead when you want the server to start from the untouched file.

```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_...", secret_key="sps_...")
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_...", secret_key="sps_...")

# 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)

- **`content_type` alias**: `OptimizeOptions` still accepts `content_type` as an alias of `mime_type` for older callers; only `mime_type` is sent, which is the field the API reads.

---

## 📄 License

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