Metadata-Version: 2.4
Name: craterview
Version: 0.4.59
Summary: Python client for the CraterView.ai API: AI photo upscaling, denoising, restoration, headshots and AI image detection
Author-email: CraterView Vision Technologies Inc <support@craterview.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://craterview.ai
Project-URL: Features, https://craterview.ai/features
Project-URL: Documentation, https://api.craterview.ai/docs
Project-URL: Source, https://github.com/craterviewai/craterview-python
Project-URL: Issues, https://github.com/craterviewai/craterview-python/issues
Keywords: upscaling,super-resolution,image-restoration,api-client,image-upscaler,photo-enhancer,denoising,photo-restoration,headshot,ai-image-detector,content-moderation
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
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 :: Multimedia :: Graphics :: Graphics Conversion
Classifier: Topic :: Scientific/Engineering :: Image Processing
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31
Requires-Dist: pillow>=10.0
Requires-Dist: pi-heif>=0.16
Dynamic: license-file

# craterview

Python client for the [CraterView.ai](https://craterview.ai) image enhancement and
restoration API.

New to it? The [guide to the clients](https://craterview.ai/guides/clients#python) walks
through a first job, a folder of photos and two tools in a row. This README is the reference.

```bash
pip install craterview
```

Python 3.9 or newer. Three dependencies: `requests` for the API, and Pillow with `pi-heif` to
read an image's size from its header — nothing is decoded — so a job's wait can be estimated
for the picture you actually send, HEIC included.

## What it does

Each model has its own page on the site:

- [AI photo enhancer and upscaler](https://craterview.ai/features/enhance): `cv-enhance-v3`
  enlarges a photo and rebuilds its fine detail at the new size.
- [AI photo denoiser for grainy, low-light shots](https://craterview.ai/features/denoise):
  `cv-denoise-v1` takes out the grain and keeps the colours, light and detail.
- [AI photo restoration for old, damaged prints](https://craterview.ai/features/restore):
  `cv-restore-v1` removes tears, creases, scratches and dust and corrects faded colour.
- [AI face enhancer for group photos](https://craterview.ai/features/small-faces):
  `cv-faces-v1` redraws faces too small or blurred to look natural.
- [AI headshot generator from a snapshot](https://craterview.ai/features/headshot):
  `cv-headshot-v1` turns a photo of a person into a professional headshot.
- [AI image detector](https://craterview.ai/features/real-or-ai): `cv-real-check-v2`
  estimates whether an image was made by a generative model.
- [Check whether an image was made with CraterView.ai](https://craterview.ai/features/mark-check):
  `cv-mark-check-v1` reads the marks on every image CraterView.ai makes or changes.
- [AI content moderation for images](https://craterview.ai/features/content-moderation):
  `cv-content-check-v1` screens an image against the content policy.

[All features](https://craterview.ai/features) are on one page. What each model costs, its
limits and its parameters are in the catalogue: `cv.models()`.

## Quickstart

```python
from craterview import CraterView

cv = CraterView(api_key="cv_...")
result = cv.run("photo.jpg", scale=4)
result.save("photo-4x")      # → photo-4x.jpg, or .png where a JPEG cannot hold the result
```

`run()` collapses the upload → submit → poll sequence into one call. That sequence is the
API's shape rather than an accident, but it is not something every caller should have to
reimplement.

Build against `echo` first. It costs no credits, needs no GPU and returns a real result — a
plain upscale — so the request, the parameters and the response are the ones a paid model
gives, and your integration needs no change when you switch. When you are ready, swap the
model id for the one you want.

```python
job = cv.run(
    # echo is free, for building against. Swap in a paid model when you are ready —
    # cv-enhance-v3 to enlarge, cv-restore-v1 to repair, cv-headshot-v1 for portraits.
    "image.jpg", model="echo",
    scale=2, wait=30,
)
job.save("image-2x")
```

A parameter one model publishes is not necessarily one another accepts — `cv.models()` says which — and
a value a model does not publish is refused at submit rather than ignored.

## An API key

Keys begin with `cv_` and are issued from your dashboard. Pass one to the constructor; every
call but the model catalogue needs one.

```python
cv = CraterView(api_key=os.environ["CV_API_KEY"])
```

A key carries your whole allowance and does not expire, so keep it server-side. It is a
credential for programs; it is not a login.

## The one call

```python
job = cv.run(
    image,                       # path, str, bytes, or a file object
    model="cv-enhance-v3",       # default
    wait=30.0,                   # seconds to hold the connection open
    timeout=600,                 # total seconds before giving up
    raise_on_failure=True,
    **params,                    # model parameters, e.g. scale=4
)
```

It waits server-side first, so a job that finishes quickly costs a single round trip, then
falls back to polling for anything slower. With `raise_on_failure=False` a failed job is
returned rather than raised, and `job.error` says why.

Past `timeout` only the waiting stops. The job carries on and is charged only if it succeeds;
the `CraterViewError` raised carries its `.job_id`, and `cv.wait_for(error.job_id)` collects
it. Calling `run()` again would start, and bill, a second job.

Which parameters a model accepts is published by the API rather than hard-coded here — see
`cv.models()`.

## The explicit path

Useful when you want to hold the key, submit later, or fan out.

```python
input_key = cv.upload("photo.jpg")                       # → "inputs/..."
job = cv.submit("cv-enhance-v3", input_key, scale=4)
job = cv.wait_for(job, timeout=600)
data = job.bytes()
```

Image bytes never pass through the API. `upload()` PUTs them straight to object storage on
a presigned URL and `bytes()` GETs the result the same way; the API moves keys, not pixels.

## Sending a result on

To run another model on a result, give `run()` the finished job, or make its upload with
`upload_from_job()`:

```python
enhanced = cv.run("group.jpg", scale=2)
faces = cv.run(enhanced, model="cv-faces-v1")

input_key = cv.upload_from_job(enhanced)                 # the same, step by step
```

The result is copied inside storage, never downloaded. A model that marks its result works from
it as it was before CraterView.ai's marks, so the new result carries one mark, and its Content
Credential names the earlier result as what it came from. A result downloaded and uploaded again
is marked over its marks.

## Retries are yours to write

**Outside `run()` and `wait_for()`, this client does not retry.** `run()` sends its submission
once more, under one idempotency key, when the first got no answer or a failure on the
platform's side, and `wait_for()` reads on through the same until its timeout; neither can make a
second job. Every other call is sent once. That is deliberate: only the caller knows where one
logical request ends and the next begins, and a retry the client invented would be a second
job you are billed for.

What it gives you instead is a key generator. Make one key per *logical request* and reuse
it for every attempt at that request:

```python
from craterview import new_idempotency_key

key = new_idempotency_key()                # once, before the first attempt
for attempt in range(3):
    try:
        job = cv.submit("cv-enhance-v3", input_key, idempotency_key=key, scale=4)
        break
    except (ConnectionError, TimeoutError):
        continue                           # same key, so at most one job is ever created
```

The two it catches are `ConnectionFailed` and `TimedOut`, raised when a request got no
whole answer; each is also the builtin the loop names. An answer from the API, even a refusal, is
not a reason to send the request again.

Generating a fresh key per attempt defeats the point entirely — the server has nothing to
match against and every attempt starts its own job. Reusing a key with a *different* body
is rejected with 409 rather than quietly handing back the earlier result. Claims are kept
for as long as the job's record is, which is not deleted; the same key always returns
the same job.

## Errors

Everything raised by this client descends from `CraterViewError`, so one `except` catches
the lot. `.status` carries the HTTP status where there was one, `.code` the API's stable name for a refusal — branch on it, not on the message — and `.trace_id` the API's
`X-Trace-Id` for a request it answered and refused — the id to quote when you ask us about
it. `.job_id` names the job an error is about, where there is one.

| Exception | Meaning |
|---|---|
| `RateLimited` | 429 — one of five limits, and `.code` says which: `rate_limited` (the account's request rate), `too_many_uploads`, `too_many_keys`, `too_many_jobs` or `queue_full`. `.retry_after` is seconds to wait: until the window rolls over for the two per-minute limits, until a new key can be made for the hourly one, or an interval to poll on for the other two. |
| `JobFailed` | The job ran and did not succeed. `.args[0]` says what you can do about it; `.error_code` is the half to branch on; `.job_id` is the job. |
| `ConnectionFailed` | The request never reached the API or storage: refused, reset, or a name that would not resolve; or its answer was cut off on the way. Also a builtin `ConnectionError`. Safe to repeat with the same idempotency key. |
| `TimedOut` | No answer within the client's `timeout`. Also a builtin `TimeoutError`. The request may have arrived, so repeat a submission with the same idempotency key, never a new one. From `run()`, which uploads afresh each time, look for the job in `jobs()` instead. |
| `InvalidId` | An id that is not one the API issued, refused before any request is made, so it carries no `.status`. Pass a job's or a key's `id` exactly as the API returned it. Also a builtin `ValueError`. |
| `InvalidSignature` | A webhook delivery did not verify. Do not act on its body. |
| `CraterViewError` | Everything else, including 4xx and 5xx from the API, and storage refusing an upload or a download. |

## `Job`

Every field the API publishes on a job is exposed here.

| | |
|---|---|
| `id`, `model`, `status` | `status` is one of `queued`, `running`, `succeeded`, `failed` |
| `created_at` | Timezone-aware `datetime` |
| `succeeded`, `done` | `done` covers both terminal states |
| `error` | Set when the job failed. Safe to show a user |
| `error_code` | The same fact, as a stable identifier. Branch on this, show the other |
| `credits` | **What you were billed.** Nothing past your balance is collected |
| `eta_seconds` | Seconds until the job is expected to finish, recomputed on every read — it counts down while the job runs. Absent once the job has settled. Estimated for your image's size when `upload()` could read it — its header is read with Pillow, nothing is decoded — or when you pass `input_megapixels` to `submit()`; for a typical image otherwise |
| `community` | True when the job is on the community queue, which runs on shared, free capacity and can wait longer at busy times |
| `output_url`, `download_url` | The result, presigned. One to display, one to save. None on a job from `jobs()`: read it with `job(id)` |
| `thumbnail_url` | A small JPEG of the job's picture, for listings — the result, or what the model worked from when it produced no file. Null when none was drawn, and on a job from `jobs()` unless asked with `include_thumbnails=True` |
| `input_url` | The picture the model worked from — the region, where you named one. None on a job from `jobs()` |
| `output_content_type` | The result's media type |
| `output_bytes` | The result's size in bytes |
| `output_width`, `output_height` | The result's size in pixels |
| `bytes()`, `save(path)` | Download the result; `save` adds the result's suffix to a path with none and returns the path written |

`result` is the whole of what the job produced, and the rows above it that describe the
result's file are accessors onto `result["output"]` rather than separate fields — the API
states those links once. A model with no file to hand back returns its answer in `result` and
leaves every one of them null; the fields it answers with are its `result_schema` in
`cv.models()`.

`credits` is the only figure about cost the API states, and each model publishes its price in
`cv.models()` — `credits_per_image`, and `credit_steps` where a smaller image costs less — so
an invoice reconciles against `credits` alone. For how long a job took, subtract
`created_at` from `finished_at` — that is the wait you had, queue included.

**Uploads declare their size.** `upload()` and `run()` measure the bytes they are about
to send and declare that figure; the API signs it into the presigned URL, so storage accepts
exactly that length and nothing else. You do not pass it — it is read off the data in hand,
which is what makes it impossible to get wrong.

**Running out of credit does not stop you.** A job at a balance of zero is accepted. Without a
subscription, or once a limited subscription's monthly allowance is spent, it runs free on the
community queue: same models, smaller size limits on some of them, longer waits
at busy times. It comes back with `community` set, and `usage()` reports the same flag for your
next job before you send it. There
is no payment error to handle: credit or a subscription moves work onto paid compute that scales
with demand.
`eta_seconds` covers the whole wait, queue time included, so a community job simply
reports a longer one.

`output_url` and `download_url` are the same object signed two ways; the content
disposition is signed in, so the second cannot be derived from the first. Both expire, so
fetch the result rather than storing the link.

`thumbnail_url` and `input_url` are for building a job listing: a few-hundred-pixel preview so a
page of jobs costs kilobytes, and the picture the model worked from so a result can be
shown against it. `cv.jobs(include_thumbnails=True)` gives each job its preview and no other
link; read a job with `cv.job(id)` when one is opened, for its result and `input_url`.
Where you named a region, `input_url` is that region — so a before-and-after
is a true pair, and what was used is something you can look at rather than something to take
on trust. It is not the file you uploaded but a new one written from it, not copied —
so do not expect a hash of it to match your file's, and a JPEG or WebP is compressed
again. Yours is removed on its own schedule. Both expire with the job's other pictures. A
model that produces no file has no result to preview, so `thumbnail_url` is a preview of the
picture it answered about.

## Webhooks

Pass `webhook_url` on submit — an absolute `http` or `https` URL, refused at submit if it is
not one — and we `POST` to it once the job settles. Verify every delivery before you act on
it: anyone who learns your URL can send you a plausible-looking body. Retries stop within a
minute; to find a delivery that never arrived, keep the ids of jobs you submitted and have not
heard about, and read each with `cv.job(id)`.

```python
from craterview import CraterView, verify_webhook, InvalidSignature

secret = CraterView(api_key="cv_...").webhook_secret()   # the same one every delivery is signed with

@app.post("/hooks/craterview")
def hook(request):
    try:
        event = verify_webhook(request.body, request.headers, secret)
    except InvalidSignature:
        return 400                       # not from us; do nothing at all

    # Answer now and work afterwards. A slow endpoint is retried while it is still
    # working, so treat deliveries as at-least-once and make this idempotent on `id`.
    enqueue(event["id"])
    return 200
```

Every copy of a delivery states the same thing, so the first one you accept is the whole
answer — later copies of an `id` you have already handled can be dropped rather than
reconciled.

**Pass the raw bytes.** Most frameworks parse JSON for you, and re-serializing it changes the
bytes the signature was computed over. In Flask that is `request.get_data()`, in Django
`request.body`, in FastAPI `await request.body()`.

The body carries the same fields a job read does, by the same names — including `result` and
the links inside it. The one difference is what happens to a field that does not apply: a
callback states every key and sets it `null`, where a job read leaves it out. So a subscriber
parses one shape and never has to ask which keys arrived.

The links expire like any others. A delivery normally arrives within seconds of the job
settling and they are good for an hour, but a subscriber that queues work for later should
read the job again rather than storing them.

### Rotating the secret

```python
new = cv.rotate_webhook_secret()
```

The old secret keeps being sent alongside the new one for a day, and `verify_webhook` accepts
either — so deploy the new one whenever suits rather than the moment you asked for it.

## Managing keys

```python
cv.keys()                    # every key on the account, by prefix; revoked ones stay listed
cv.create_key("staging")     # the value is in this response and nowhere else
cv.revoke_key("key_...")     # immediate, and not reversible
```

Several keys on one account is the ordinary arrangement — one per service or environment, so
revoking one leaves the others working. They share the account's credits and history.

To rotate without downtime: create the new key, move your clients onto it, then revoke the
old one. You cannot revoke the key you are calling with.

## Everything else

```python
cv.models()                       # models, what each takes and answers with, and which queue you are on
cv.jobs(limit=50)                 # your history, newest first, paging transparently
cv.job("job_...")                 # one job by id
cv.usage()                        # credit balance, next job's queue, spend and job counts
cv.quote("cv-enhance-v3", {"scale": 2}, input_width=1500, input_height=1000)   # a job's price and result size, run nothing
```

`jobs()` is a generator and pages for you. `limit` is how many jobs one request fetches, not
how many you get: it keeps going until your history runs out. 200 is the largest page the
API serves, and a bigger number is fetched as 200. A job from it carries no links, unless you
pass `include_thumbnails=True` for each job's preview; `job(id)` has the rest.

## Configuration

```python
CraterView(
    api_key=None,
    base_url="https://api.craterview.ai",
    timeout=60.0,                 # per-request, seconds
)
```

`base_url` is what you change to point at a local server.

## From Claude Code

This repository is also a Claude Code marketplace. Two plugins: `craterview` connects
CraterView.ai's hosted tools so the assistant enhances images in the conversation, and
`craterview-api` teaches an agent to call the API from code with this client. See
[`plugins/`](plugins/) for what each does and how it finds a key.

```
/plugin marketplace add craterviewai/craterview-python
/plugin install craterview@craterviewai
/plugin install craterview-api@craterviewai
```

## Versioning

Semver, from `0.1.0` on. A release that removes a public name, renames an attribute on `Job`
or changes the type of one gets a minor bump while this is `0.x` and a major bump after
`1.0.0`; anything purely additive gets a patch. Pin what you depend on.

The API this wraps adds fields to its responses without warning, so treat an unfamiliar key in
`result` or a `status` you do not recognize as something to ignore rather than to fail on.

## License

Apache-2.0. See [LICENSE](LICENSE).
