Metadata-Version: 2.5
Name: wellfriend-document-sdk
Version: 1.0.0
Summary: Python SDK for the Wellfriend document API: PDF and image tools, pipelines, uploads, downloads and webhooks
Project-URL: Homepage, https://wellfriend.dev
Project-URL: Documentation, https://wellfriend.dev/docs/sdk-cli/python
Project-URL: Changelog, https://github.com/cybernew121/wellfriend-sdk/blob/main/python/CHANGELOG.md
Project-URL: Repository, https://github.com/cybernew121/wellfriend-sdk
Author: Wellfriend
License-Expression: MIT
License-File: LICENSE
Keywords: api,compress,document,ocr,pdf,sdk,wellfriend
Classifier: Development Status :: 5 - Production/Stable
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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 :: Office/Business
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Provides-Extra: ed25519
Requires-Dist: cryptography>=42; extra == 'ed25519'
Description-Content-Type: text/markdown

# Wellfriend Python SDK

The official Python client for the [Wellfriend](https://wellfriend.dev) document API: PDF and image tools,
pipelines, uploads, downloads and webhooks. Typed throughout, with a sync and an async client.

## Install

```sh
pip install wellfriend-document-sdk
```

Python 3.10 or later. The only dependency is [httpx](https://www.python-httpx.org/). To verify Ed25519-signed
webhooks, add the optional extra: `pip install "wellfriend-document-sdk[ed25519]"`.

## Quickstart

```python
from wellfriend import Wellfriend

wf = Wellfriend()                                      # reads WELLFRIEND_API_KEY
wf.tools.compress_pdf("in.pdf").save("out.pdf")
```

The async client has the same surface:

```python
from wellfriend import AsyncWellfriend

async with AsyncWellfriend() as wf:
    result = await wf.tools.compress_pdf("in.pdf")
    await result.save("out.pdf")
```

## Get an API key

Create a key at <https://wellfriend.dev/dashboard/developer-api/keys> and export it as `WELLFRIEND_API_KEY`, or
pass `Wellfriend(api_key=...)`. `WELLFRIEND_BASE_URL` overrides the API root (`https://wellfriend.dev/api/v2`).
A missing key fails at the first request with an `AuthenticationError` that says where to create one.

## Tools

Every tool of the catalog is a method of `wf.tools`, with typed, snake_case parameters:

```python
result = wf.tools.compress_pdf("report.pdf", profile="aggressive_max", fast_web_view=True)
result.save("small.pdf")                  # streams to disk; a directory keeps the output's own name
result.bytes()                            # or read it into memory
for chunk in result.stream(): ...         # or stream it

result.outputs[0].filename, result.outputs[0].size_bytes, result.operation.id, result.usage
```

- The input is a path, `bytes`, a binary stream, `File(stream, "scan.png")`, a stored document id (`"doc_..."`),
  a `Document`, or a previous result (which chains without downloading):
  `wf.tools.ocr_pdf(wf.tools.compress_pdf("in.pdf"))`.
- Tools that read several files take a list: `wf.tools.merge_pdf(["a.pdf", "b.pdf"])`.
- Asset files are parameters too: `wf.tools.add_watermark("in.pdf", type="image", watermark_image="logo.png")`.
- The media type comes from the file name's extension (or the content, for nameless bytes).
- `wf.tools.run("compress-pdf", "in.pdf", {"profile": "medium"})` runs any tool by id.

Each call uploads the input, starts the operation, waits for it (polling with backoff, up to the client's
`wait_timeout`, 15 minutes by default) and raises `OperationFailedError` if it fails. To start and wait later:

```python
operation = wf.tools.compress_pdf("in.pdf", wait=False)    # Python idiom: a keyword, not an options field
...
result = operation.wait()                                   # or wf.document_operations.wait(operation.id)
```

`wf.quote("ocr-pdf", pages=40)` returns what a run costs before you send it.

## Pipelines

Several tools on one file, chained on the server (at most 10 steps):

```python
pipeline = wf.pipeline(["compress-pdf", ("rotate-pdf", {"angle": 90})])
pipeline.run("scan.pdf").save("out.pdf")
```

The input is uploaded once. Every step starts at once and reads the previous step's output (`source`), so
nothing is downloaded or uploaded in between; the SDK waits for the last step only. If a step fails, the
following steps fail too (their request units are refunded) and `run()` raises `OperationFailedError`
naming the failed step. Steps are tool ids, `(tool, params)` pairs, `{"tool": ..., "params": ...}` or
`Step(tool, params)`. With `options={"idempotency_key": "k"}` each step uses `k:step-<n>`.

## Files

```python
doc = wf.documents.create("big-scan.pdf", title="Scan")    # returns a typed Document
wf.documents.download(doc).save("copy.pdf")                # current version, streamed
wf.document_versions.download(doc.id, version_id).save("downloads/")
```

Files up to 50 MiB go up in one streamed request. Larger files use the resumable upload: the SDK computes the
SHA-256 while reading, sends parts of the size the API chooses (8 MiB today), retries each part on its own and
never holds the whole file in memory. A file the workspace already stores completes at once. Downloads stream to
a temporary file, are checked against the checksum the API sends, and are moved into place.

## Errors

```
WellfriendError
├─ APIError              status, code, message, reference_id, details, headers
│  ├─ BadRequestError (400)
│  │  └─ ValidationError (422, or a 400 whose code ends in _INVALID/_REQUIRED/_UNSUPPORTED)
│  ├─ AuthenticationError (401)    PermissionDeniedError (403)
│  ├─ NotFoundError (404)          ConflictError (409)
│  ├─ RateLimitError (429, retry_after)
│  └─ ServerError (5xx)
├─ ConnectionError       (also a builtin ConnectionError)
├─ TimeoutError          (also a builtin TimeoutError)
├─ OperationFailedError  code, operation
├─ WaitTimeoutError      operation_id
└─ WebhookVerificationError
```

```python
from wellfriend import ValidationError, OperationFailedError

try:
    wf.tools.rotate_pdf("in.pdf", angle="45")
except ValidationError as error:
    print(error.code, error)       # OPERATION_INPUT_INVALID ... (reference ref_...)
```

`str(error)` is the API's message followed by `(reference <id>)`; quote the reference when you contact Support.

## Retries and timeouts

```python
wf = Wellfriend(timeout=60, max_retries=2, wait_timeout=900)
wf.documents.list(options={"timeout": 5, "max_retries": 0})
wf.tools.compress_pdf("in.pdf", options={"idempotency_key": "invoice-1234-compress"})
```

- Network errors and 408, 429, 500, 502, 503, 504 and 520-524 answers are retried with exponential backoff and full
  jitter (0.5 s base, 8 s cap), honouring `Retry-After`. Reads are retried, and so are writes that carry an
  idempotency key.
- Writes the API de-duplicates get a generated idempotency key, reused for each retry of that call. Pass your
  own with `options={"idempotency_key": ...}`; a tool call derives the keys of its uploads from it.
- `timeout` covers connecting, the response headers and each idle read. It never cuts off a long upload or
  download that is still moving.
- Every method takes the same `options` dict: `idempotency_key`, `timeout`, `max_retries`, `headers`.
- `Wellfriend(http_client=httpx.Client(...))` uses your own client (proxies, certificates).

## Webhooks

```python
from wellfriend import verify_webhook

event = verify_webhook(request.body, request.headers, "whsec_...")   # or wf.webhooks.verify(...)
if event.type == "com.wellfriend.document-operation.completed.v2":
    print(event.data.output_document_id)
```

It checks the Standard Webhooks signature (`v1,` HMAC-SHA256 with the `whsec_` secret, or `v1a,` Ed25519 with
the endpoint's public key) over the raw body, refuses timestamps more than 5 minutes away, and returns a typed
event. Pass a list of secrets during a rotation. `wf.webhooks.verify` defaults to `WELLFRIEND_WEBHOOK_SECRET`.

## All resources

Every API operation is a method named after its operation id: `<group>.<action>` becomes
`wf.<group>.<action>()` in snake_case.

```python
for doc in wf.documents.list(q="invoice"):          # pages automatically
    print(doc.id, doc.title)

link = wf.secure_links.create(document_id=doc.id, authentication_mode="PUBLIC_UNLISTED")
endpoint = wf.webhooks.endpoints.create(url="https://example.com/hooks", event_filters=["*"])
run = wf.workflow_runs.get("wfrun_...")
```

Arguments are snake_case and map to the API's camelCase names. Responses are typed models where the API
describes them (`Document`, `Operation`, `Upload`, `Quote`, ...) and `ApiObject` otherwise, which reads members
by snake_case attribute (`obj.next_cursor`) or by key (`obj["nextCursor"]`); `to_dict()` returns the raw JSON.
List methods return a page you can iterate across pages (`async for` with the async client). Use
`extra_body={...}` to send a field the SDK does not know yet. The server-side signature check of a delivery is
`wf.webhooks.verify_remote(...)`. A TOOL embed session (one tool workspace in your page) is
`wf.embed_sessions.create_tool(tool_id, parent_origin, preset=..., locked_parameters=...)`.
