Skip to Content

Python SDK

Call Papyrus from Python with typed sync and async clients

papyrus-sdk is the Python client of Papyrus, with one method per operation and typed responses. It comes as a sync and an async client and requires Python 3.11 or later. SDK X.Y is made for server X.Y.

pip install papyrus-sdk
from pathlib import Path

from papyrus_sdk import ChunkingOptions, Papyrus

with Papyrus(base_url='http://127.0.0.1:8000', api_key='dev') as client:
    doc = client.markdown(Path('pricing.html'), chunking=ChunkingOptions(max_tokens=64))

print(doc.source.title)
for chunk in doc.chunks or []:
    print(chunk.index, chunk.kind, chunk.headings, chunk.tokens)
Service levels
0 text ['Service levels'] 16
1 text ['Service levels', 'Response times'] 4
2 table ['Service levels', 'Response times'] 51
3 text ['Service levels', 'Escalation'] 28

Configure the client

ArgumentDefault
base_urlThe PAPYRUS_BASE_URL variable; required
api_keyThe PAPYRUS_API_KEY variable; without it requests carry no Authorization header
timeout310 seconds to wait for a response and 5 to connect; every operation also accepts its own timeout
max_retries2; 0 turns retries off
http_clientYour own httpx.Client or httpx.AsyncClient, for proxies and private certificate authorities

The server reads a comma-separated list of keys from its own PAPYRUS_API_KEY. The client takes a single key and rejects a value with a comma.

Keep timeout above the server's limits.deadline, 300 seconds by default. The server answers only when it is done, so with a shorter timeout you get a client timeout instead of deadline_exceeded.

Choose how you send the document

markdown, render, thumbnail and inspect take the document in one of three forms:

FormWhat the client sends
client.markdown('https://axelered.com')A string with :// is a URI. Any other string is the path of a local file to upload. Path, bytes and binary files are uploads
client.markdown(source='s3://prod/docs/report.pdf')The URI as is
client.markdown(file='sample.pdf')An upload, from a path, bytes or a binary file

Pass strings that come from users or models as source=. In the positional form, a string that names a local file uploads that file. source= never reads the local disk.

Give an upload sent as bytes a name, for example filename='prices.csv', because the extension refines format detection.

screenshot takes the URL of a page.

Set options

Options are keyword arguments in snake_case. Papyrus applies its defaults to the ones you leave out and returns the resolved values in options:

page = client.render(Path('sample.pdf'), page=1, width=800, format='webp')

print(page.source.page_count, page.result.width, page.result.height)
print(page.options)
page.result.save('page.webp')
1 800 1133
page=1 width=800 height=None dpi=None format=<ImageFormat.WEBP: 'webp'>

Read scans and images

By default, read_mode is auto: the server reads scans, images and presentations from their page images when your operator has configured a vision model, and everything else from its text. Set read_mode='ocr' to read every page from its image, or 'text' to never use the model. OCR covers how auto decides, the formats, the backends and the limits.

doc = client.markdown(Path('scan.pdf'), read_mode='ocr', chunking=ChunkingOptions())

print(doc.options.read_mode, doc.source.page_count)
for chunk in doc.chunks or []:
    print(chunk.page, chunk.headings)

options.read_mode is the mode the server used, text or ocr: formats without pages, and spreadsheets, are read as text. Raise the client timeout together with limits.deadline for long documents.

Read the result

AccessorReturns
result.textMarkdown as str; raises ValueError on an image
result.dataThe artifact as bytes
result.save(path)Writes the artifact to a local file and returns its path

With destination, Papyrus writes the result to remote storage and the response has no content or chunks. result.uri is set, and the three accessors raise ValueError.

stored = client.markdown(source='s3://prod/docs/report.pdf', destination='s3://prod/md/report.md')
print(stored.result.uri)

Use the async client

AsyncPapyrus has the same methods and runs on asyncio. It uploads bytes only and never reads the local disk: paths and file objects raise NotImplementedError.

import asyncio

from papyrus_sdk import AsyncPapyrus


async def main() -> None:
    async with AsyncPapyrus(base_url='http://127.0.0.1:8000', api_key='dev') as client:
        page, upload = await asyncio.gather(
            client.markdown(source='https://axelered.com'),
            client.markdown(b'name,amount\nalpha,1\n', filename='prices.csv'),
        )
    print(page.source.title)
    print(upload.result.text)


asyncio.run(main())
Axelered · Intelligent process automation
| name | amount |
| --- | --- |
| alpha | 1 |

Handle errors

Every error derives from PapyrusError.

ErrorMeaning
APIErrorThe server answered with an error; branch on code, listed in error codes. code is None when the answer comes from a proxy
ConnectionFailedThe server is unreachable or the connection was lost
TimedOutA ConnectionFailed caused by the client timeout
InvalidResponseThe answer is not a response this SDK version knows, for example an enum value added by a newer server
from papyrus_sdk import APIError

try:
    client.render(Path('sample.pdf'), page=5)
except APIError as e:
    print(e.status, e.code, e.detail)
422 page_out_of_range page 5 is out of range, the document has 1

Use e.request_id to find the request in the server logs; e.errors lists the invalid fields of a validation_error.

The client retries only requests the server did not process: queue_full, refused connections, and 502 or 503 answers from a proxy. Before each retry it waits for Retry-After or an exponential backoff, at most 30 seconds. Timeouts, lost connections and every other error, ocr_rate_limited included, raise at once.

Check the server

health() raises unless the server is up. ready() returns False when the server is at capacity and raises when it is unreachable. Both use public routes, so neither verifies the API key.

On this page