Metadata-Version: 2.4
Name: docuapi
Version: 0.1.0
Summary: Python SDK for DocuAPI document conversion.
Author: DocuAPI
Project-URL: Homepage, https://www.docuapi.dev
Project-URL: Documentation, https://www.docuapi.dev/docs/api
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
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: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"

# DocuAPI Python SDK

Use DocuAPI directly from Python to parse documents and images, request OCR,
check usage, and manage asynchronous batches. Python 3.10 or newer is required.
The package calls the DocuAPI service.

## Installation

```bash
pip install --upgrade docuapi
```

Until it is published, install this SDK from the repository root:

```bash
python -m pip install ./sdks/python
```

Create an API key in your [DocuAPI dashboard](https://www.docuapi.dev/dashboard).
You can set `DOCUAPI_API_KEY` in your environment or pass credentials explicitly.

## Quick start

Your dictionary-style interface is supported:

```python
import os
import docuapi

docuapi.api_credentials = os.environ["DOCUAPI_API_KEY"]

result = docuapi.convert(
    {"File": "/path/to/my_file.pdf", "EnableOcr": "true"},
    output_format="json",
)

print(result["document"])
print(result["content"])
```

Python keyword arguments work too:

```python
result = docuapi.convert(file="report.pdf", enable_ocr=True, output_format="markdown")
print(result["content"])
```

The SDK accepts `File`/`file`, `Url`/`URL`/`url`, `EnableOcr`/`enable_ocr`, and
`OutputFormat`/`output_format` dictionary keys. OCR accepts Python booleans or the
strings `"true"` and `"false"`. Unknown or duplicate options raise `ValueError`
before an HTTP request is sent. File arguments are local paths, including
`pathlib.Path`; the SDK opens them in binary mode and closes them after the request.

## Reusable client

Use `Client` when making several calls, using multiple accounts, or configuring
an application. Each client keeps its own credentials and connection pool.
Module-level credentials are shared process state; avoid changing them between
concurrent requests for different users.

```python
from pathlib import Path
from docuapi import Client

# Reads DOCUAPI_API_KEY when api_key is omitted.
with Client() as client:
    result = client.convert(
        file=Path("report.pdf"),
        enable_ocr=True,
        output_format="json",
    )
    usage = client.get_usage()

print(result["document"]["page_count"])
print(usage["pages_remaining"])
```

Alternatively, use `Client(api_key="your_api_key")`. A context manager closes
connections automatically; otherwise call `client.close()`.

## Document URLs and output formats

```python
with Client() as client:
    result = client.convert(
        url="https://example.com/report.pdf",
        output_format="chunks",
    )
```

Provide exactly one of `file` or `url`. URLs must be public HTTP(S) document URLs;
the server enforces its network, size, and redirect restrictions.

| `output_format` | `result["content"]` |
| --- | --- |
| `json` (default), `document_json` | Ordered content blocks, including table rows |
| `markdown` | A Markdown string |
| `chunks` | A list of chunks with source/page/section metadata |

The result is the API's JSON dictionary with `document`, `content`, and `metadata`.
The SDK does not rewrite the conversion output or change server-side limits.

## Images and OCR

```python
with Client() as client:
    result = client.convert(file="scan.png", enable_ocr=True)
```

Supported documents include PDF, DOCX, PPTX, XLSX, HTML/HTM, Markdown, TXT, CSV,
and EPUB. Images `.jpg`, `.jpeg`, `.png`, `.bmp`, `.gif`, `.tif`, and `.tiff`
require OCR.

## Asynchronous batches

Batches require Developer, Pro, or Enterprise. They accept local paths, with one
OCR setting and one output format applying to every file.

```python
from docuapi import Client

with Client() as client:
    batch = client.create_batch(
        ["invoice.pdf", "report.docx", "scan.png"],
        enable_ocr=True,
        output_format="json",
        idempotency_key="my-import-001",
    )

    batch_id = batch["batch_id"]
    progress = client.get_batch(batch_id)
    finished = client.wait_for_batch(batch_id, poll_interval=2, timeout=3600)

    for item in finished["files"]:
        if item["status"] == "failed":
            print(item["filename"], item["error"])

    archive = client.download_batch_results(batch_id, "results.zip")
    print(f"Results saved to {archive}")
```

`wait_for_batch` returns for both `completed` and `completed_with_errors`.
Inspect the per-file status or the ZIP's `manifest.json` for partial failures.
It raises `BatchTimeoutError` if the local polling deadline expires; this does
not cancel server-side processing. Submit a batch once and retain its ID to
resume polling later.

The ZIP contains the normal conversion response for each successful document
and a manifest describing all files. Downloads stream to disk, follow redirects,
and validate ZIP integrity. The destination is replaced only after validation;
temporary download files are removed if the request or validation fails.
The SDK never extracts archives automatically.

Use the same optional `idempotency_key` only when retrying identical files,
filenames, ordering, and options. A different submission needs a new key.
Conversions and batch submissions are **not automatically retried**. A network
timeout does not establish whether the server accepted a request.

Results expire one hour after batch completion by default; unfinished batches
expire after 24 hours. The operator can change those limits. Expired requests
raise `APIError` with `status_code == 410`; downloads do not consume pages.

All client methods are also available as module functions, for example
`docuapi.get_usage()`, `docuapi.create_batch(...)`, and
`docuapi.download_batch_results(batch_id, "results.zip")`.

## Errors

```python
from docuapi import Client, APIError, APITimeoutError, RateLimitError

try:
    with Client() as client:
        result = client.convert(file="report.pdf")
except RateLimitError as error:
    print(error.code)         # e.g. monthly_page_limit_reached
    print(error.retry_after)  # Retry-After header, if present
except APITimeoutError:
    print("Timed out; the server may still be processing.")
except APIError as error:
    print(error.status_code, str(error))
```

| Exception | Meaning |
| --- | --- |
| `AuthenticationError` | HTTP 401: invalid or revoked key |
| `PermissionDeniedError` | HTTP 403: plan does not include the feature |
| `RateLimitError` | HTTP 429: quota, rate, queue, or storage limit |
| `APIError` | Other unsuccessful HTTP response; includes `status_code`, `body`, `code`, and `retry_after` |
| `APITimeoutError` | Network timeout |
| `APIConnectionError` | Other transport failure |
| `InvalidResponseError` | Invalid JSON, missing conversion fields, or invalid ZIP |
| `BatchTimeoutError` | Batch polling deadline expired |

API errors inherit from `APIError`; all SDK exceptions inherit from
`DocuAPIError`. Invalid local options raise `ValueError`/`TypeError`, and local
filesystem errors retain their normal Python exception types. API exceptions
do not retain raw HTTP requests or authorization headers.
