Metadata-Version: 2.4
Name: safereel
Version: 0.2.0
Summary: Official Python client for the SafeReel NSFW detection API
Author-email: SafeReel <support@safereel.ai>
License: MIT
Project-URL: Homepage, https://safereel.ai
Project-URL: Documentation, https://safereel.ai/docs
Project-URL: Repository, https://github.com/safereel/safereel-python
Project-URL: Changelog, https://github.com/safereel/safereel-python/blob/main/CHANGELOG.md
Keywords: safereel,nsfw,content-moderation,image-classification,video-moderation
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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: Topic :: Internet :: WWW/HTTP
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# safereel-python

Official Python client for the [SafeReel NSFW detection API](https://safereel.ai).

[![CI](https://github.com/safereel/safereel-python/actions/workflows/ci.yml/badge.svg)](https://github.com/safereel/safereel-python/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/safereel.svg)](https://pypi.org/project/safereel/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

Server-side only: **never call this API from a browser or ship your API key in
client-side code.** Sync-only for v1; requires Python 3.9+; the single runtime
dependency is [`httpx`](https://www.python-httpx.org/).

## Install

```bash
pip install safereel
```

## Quickstart

Get an API key at [safereel.ai](https://safereel.ai), then either pass it
explicitly or export it:

```bash
export SAFEREEL_API_KEY=sr_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

### Check an image

```python
import safereel

with safereel.Client() as client:  # reads SAFEREEL_API_KEY by default
    with open("frame.jpg", "rb") as f:
        result = client.check_image(f.read(), "image/jpeg")

print(result.verdict, result.confidence, result.cached)
# "clean" | "nsfw" — content types other than jpeg/png/webp raise ValueError
# client-side, before any network call.
```

### Scan a video and wait for the verdict

```python
import safereel

with safereel.Client() as client:
    submission = client.submit_video(
        "https://cdn.example.com/movie.mp4",
        webhook_url="https://you.example.com/safereel-hook",  # optional
    )
    print(submission.id, submission.webhook_secret)  # store the secret!

    # Polls until done/failed: ~2s interval growing to 5s with jitter,
    # 10-minute default timeout, cancellable via threading.Event.
    job = client.wait_for_verdict(submission.id, timeout=600)
    print(job.status, job.verdict, job.frames, job.flagged)
```

`submit_video` automatically generates and sends a random-UUID
`Idempotency-Key` header, so a retry after a transport error replays the
original submission instead of creating a duplicate job (reusing a key with a
different body returns 409 `idempotency_conflict`). Pass your own
`idempotency_key=` if you need it stable across process restarts.

### Verify a webhook

The signature covers the **exact raw request body** — verify before parsing,
and never re-serialize the JSON first. With Flask, for example:

```python
from flask import Flask, request, abort
import safereel

app = Flask(__name__)

@app.post("/safereel-hook")
def safereel_hook():
    raw_body = request.get_data()  # raw bytes, NOT request.get_json()
    signature = request.headers.get("X-SafeReel-Signature", "")
    try:
        job = safereel.parse_webhook_event(raw_body, signature, WEBHOOK_SECRET)
    except safereel.WebhookVerificationError:
        abort(401)
    print(job.id, job.status, job.verdict)
    return "", 204
```

Or verify manually: `safereel.verify_webhook_signature(raw_body, signature, secret) -> bool`
(constant-time comparison, validates the `sha256=` prefix and hex format).

## Error handling

All errors derive from `safereel.SafereelError` and carry `http_status`,
`code` (the raw API code string, even for codes this SDK version doesn't
know), `message`, and `retry_after`:

```python
import safereel

try:
    with safereel.Client() as client:
        result = client.check_image(open("frame.jpg", "rb").read(), "image/jpeg")
except safereel.RateLimitError as e:
    print(f"slow down, retry after {e.retry_after}s")
except safereel.QuotaError:
    print("plan allowance exhausted — upgrade at https://safereel.ai/dash")
except safereel.AuthenticationError:
    print("check your API key")
except safereel.TransientServiceError as e:
    print(f"capacity full, retries exhausted: {e}")
except safereel.TransportError as e:
    print(f"network failure after all retries: {e}")
except safereel.SafereelError as e:
    print(f"[{e.http_status}] {e.code}: {e.message}")
```

Specific subclasses: `AuthenticationError`, `QuotaError`, `RateLimitError`,
`NotFoundError`, `IdempotencyConflictError`, `InvalidRequestError`
(`PayloadTooLargeError`, `UnsupportedMediaError`), `ServerError`,
`TransientServiceError`, `TransportError`, plus `PollingTimeoutError` /
`PollingCancelledError` from `wait_for_verdict`.

## Retries

Built in, finite (3 attempts by default, configurable via
`Client(max_attempts=...)`):

- `429 rate_limited` — waits the error body's `retry_after` seconds.
- `503 inference_unavailable` / `service_starting` — exponential backoff from
  1s, capped at ~30s, with jitter.
- Transport errors (connection reset, timeouts) — retried for every call;
  `submit_video` is safe because of the automatic `Idempotency-Key`.
- `400/401/402/404/409/413/415/500` are **never** retried.

## Configuration

```python
client = safereel.Client(
    api_key="sr_live_...",                  # or SAFEREEL_API_KEY env var
    base_url="https://api.safereel.ai",     # override for sandbox
    timeout=30.0,                           # per-request seconds
    max_attempts=3,                         # total attempts incl. retries
)
```

## CLI

Installing the package also provides a `safereel` command, so you can script
checks without writing code. It reads `SAFEREEL_API_KEY` (or `--api-key`) and
`SAFEREEL_BASE_URL` (or `--base-url`), prints JSON to stdout, and exits 0 on
success, 1 when a waited-on video job failed, 2 on errors.

```bash
safereel status                                   # no API key needed
safereel check frame.jpg --pretty                 # prints the verdict JSON
safereel submit https://cdn.example.com/movie.mp4 --wait
safereel poll vid_52271e017ebc44e6
```

## Deliberately not included

Browser usage (the API key must stay server-side), the anonymous
`/v1/demo/check` endpoint, programmatic signup, batching, caching, and
framework middleware (see `examples/` for a Flask webhook receiver instead).

## Resources

- API docs: https://safereel.ai/docs
- Measured accuracy: https://safereel.ai/accuracy
- Security & data handling: https://safereel.ai/trust

Need an API key? https://safereel.ai
