tempest_fastapi_sdk.pdf¶
Geração de PDF a partir de templates HTML.
PdfRenderer
¶
PdfRenderer(
*,
template_dir: str | Path | None = None,
assets: AssetPolicy | None = None,
strict_assets: bool = True,
max_concurrent: int = DEFAULT_MAX_CONCURRENT_RENDERS,
)
Renders HTML into PDF bytes.
The Jinja environment looks in the project's template_dir first
and falls back to the bundled templates, so a project overrides
receipt.html by dropping a file of that name next to its own —
the same shadowing rule
:class:~tempest_fastapi_sdk.utils.email.EmailUtils uses.
Attributes:
| Name | Type | Description |
|---|---|---|
template_dir |
Path | None
|
Project templates, searched first. |
assets |
AssetPolicy
|
What a template may load. The default
denies every fetch. Only its rules are shared between
renders: each render collects refusals in its own
:meth: |
strict_assets |
bool
|
Whether a refused asset fails the render. |
Initialize the renderer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template_dir
|
str | Path | None
|
Directory whose templates
shadow the bundled ones. |
None
|
assets
|
AssetPolicy | None
|
What templates may load.
|
None
|
strict_assets
|
bool
|
When |
True
|
max_concurrent
|
int
|
Renders allowed to run at once. |
DEFAULT_MAX_CONCURRENT_RENDERS
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
environment
property
¶
The Jinja environment, built on first use.
Autoescaping is on for every template: a customer name carrying
< would otherwise reshape the document, and the caller of a
PDF endpoint is frequently not the person the data came from.
Returns:
| Name | Type | Description |
|---|---|---|
Environment |
Environment
|
The configured environment. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When Jinja2 is missing — install the |
render_html_string
¶
Render a template to HTML, without producing a PDF.
Useful to preview a layout in a browser, and to test a template without paying for layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
Template file name. |
required |
context
|
Mapping[str, Any]
|
Values for the template. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The rendered HTML. |
Raises:
| Type | Description |
|---|---|
TemplateNotFound
|
When neither the project nor the SDK has a template by that name. |
render_html
async
¶
render_html(
html: str, *, base_url: str | None = None, metadata: Mapping[str, Any] | None = None
) -> bytes
Render an HTML string to PDF bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
html
|
str
|
The document source. |
required |
base_url
|
str | None
|
Base for resolving relative URLs. The asset policy still decides what may be fetched, so this widens nothing on its own. |
None
|
metadata
|
Mapping[str, Any] | None
|
Extra |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The PDF. |
Raises:
| Type | Description |
|---|---|
AssetRefused
|
When |
ImportError
|
When WeasyPrint is missing. |
render_template
async
¶
render_template(
template: str,
context: Mapping[str, Any],
*,
metadata: Mapping[str, Any] | None = None,
) -> bytes
Render a template to PDF bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
Template file name. |
required |
context
|
Mapping[str, Any]
|
Values for the template. |
required |
metadata
|
Mapping[str, Any] | None
|
Extra |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The PDF. |
Raises:
| Type | Description |
|---|---|
TemplateNotFound
|
When the template does not exist. |
render_document
async
¶
render_document(
document: PdfDocument, *, metadata: Mapping[str, Any] | None = None
) -> bytes
Render one of the bundled documents.
The template comes from the payload's own type, so there is no second argument to keep in sync with it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
PdfDocument
|
A validated bundled document. |
required |
metadata
|
Mapping[str, Any] | None
|
Extra |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
The PDF. |
Raises:
| Type | Description |
|---|---|
ValidationException
|
When |
TemplateNotFound
¶
bundled_document_names
¶
List the bundled documents by name.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Names accepted by |
list[str]
|
router, sorted. |
document_schema
¶
document_schema(name: str) -> type[PdfDocument]
Resolve a bundled document name to its schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A name from :func: |
required |
Returns:
| Type | Description |
|---|---|
type[PdfDocument]
|
type[PdfDocument]: The schema to validate a payload with. |
Raises:
| Type | Description |
|---|---|
TemplateNotFound
|
When no bundled document has that name. The message lists the ones that exist, so a typo is one read away from fixed. |
BUNDLED_TEMPLATE_DIR
module-attribute
¶
Directory holding the templates shipped with the SDK.
DEFAULT_MAX_CONCURRENT_RENDERS
module-attribute
¶
Renders allowed to run at once.
Layout is CPU-bound and single-threaded per document, so more workers
than cores turns latency into queueing without adding throughput. Four
matches the container sizes services here actually run on; raise it with
max_concurrent when the host is bigger.
AssetPolicy
dataclass
¶
AssetPolicy(
allow_dirs: tuple[Path, ...] = (),
allow_remote: bool = False,
remote_timeout: float = DEFAULT_REMOTE_TIMEOUT,
max_bytes: int = DEFAULT_MAX_ASSET_BYTES,
refusals: list[str] = list(),
)
Which URLs a template may resolve while rendering.
The default denies every fetch. That is deliberate: the bundled
templates need no fetching at all — their CSS is handed to the
renderer directly and images arrive as data: URIs — so the
permissive settings exist for templates that genuinely need a local
asset directory, and turning them on is a decision somebody makes on
purpose.
Attributes:
| Name | Type | Description |
|---|---|---|
allow_dirs |
tuple[Path, ...]
|
Directories whose files a
template may load through |
allow_remote |
bool
|
Whether |
remote_timeout |
float
|
Seconds a remote asset has to answer. |
max_bytes |
int
|
Ceiling for a single asset. |
refusals |
list[str]
|
Human-readable reasons collected by
:meth: |
refuse
¶
Record a refusal and raise, so the fetch does not succeed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL the template asked for. |
required |
reason
|
str
|
Why the policy denied it. |
required |
Raises:
| Type | Description |
|---|---|
AssetRefused
|
Always. The renderer catches it, notes the asset is missing, and continues; the collected reason is what turns that into a real error at the end. |
for_render
¶
for_render() -> AssetPolicy
Return a copy with the same rules and an empty refusal list.
A policy is configuration plus a collector, and only the configuration may be shared. One instance handed to several concurrent renders would let each read — and clear — the others' refusals, so one request's error could carry another request's URL, presigned token included. Each render fetches through its own copy instead.
The copy is shallow and skips __post_init__: allow_dirs
keeps the paths resolved when this policy was built, so a
symlink swapped since then still cannot widen it, and a
directory removed since then does not make the render raise
ValueError.
Returns:
| Name | Type | Description |
|---|---|---|
AssetPolicy |
AssetPolicy
|
A policy enforcing the same rules, whose |
AssetPolicy
|
|
take_refusals
¶
Return the refusals collected so far and reset the list.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: One entry per refused URL, in the order the |
list[str]
|
template referenced them. |
resolve_local_path
¶
Map a file:// URL to a path inside an allowed directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The resolved, allowed path. |
Raises:
| Type | Description |
|---|---|
AssetRefused
|
When no directory is allowed, or the resolved path escapes all of them. |
AssetRefused
¶
AssetRefused(
message: str | None = None,
*,
code: str | None = None,
status_code: int | None = None,
details: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
message_key: str | None = None,
message_params: dict[str, Any] | None = None,
field: str | None = None,
)
Bases: ValidationException
Raised when a template tried to load something the policy denies.
Carries every refusal from one render rather than the first, so a template with three blocked references is fixed in one pass.
UrlFetcher
¶
Bases: Protocol
Callable returned by :func:build_url_fetcher for WeasyPrint.
Attributes:
| Name | Type | Description |
|---|---|---|
_fail_on_errors |
bool
|
Read by WeasyPrint to decide whether a failed fetch aborts the render or is only logged. |
UrlFetcherResponse
¶
Bases: Protocol
Subset of weasyprint.urls.URLFetcherResponse returned by a fetcher.
WeasyPrint does not ship a py.typed marker, so callers receive this
protocol instead of Any and keep typed access to the response bytes
and media type.
build_url_fetcher
¶
build_url_fetcher(policy: AssetPolicy, *, fail_on_errors: bool = True) -> UrlFetcher
Build the fetch callable the renderer consults for every URL.
The returned callable carries _fail_on_errors, which WeasyPrint
reads off it to decide whether a failed fetch stops the render or is
only logged. Without it, a refused asset would silently become a
document with a hole in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
AssetPolicy
|
The policy to enforce. Every refusal is
appended to |
required |
fail_on_errors
|
bool
|
Sets |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
UrlFetcher |
UrlFetcher
|
A |
UrlFetcher
|
WeasyPrint's |
DEFAULT_MAX_ASSET_BYTES
module-attribute
¶
Ceiling for a single fetched asset, in bytes.
A template that pulls a 400 MB image does not fail — it renders, slowly, holding the whole thing in memory per concurrent request. 5 MiB fits any logo, signature or chart a document needs and turns the pathological case into an error instead of an outage.
DEFAULT_REMOTE_TIMEOUT
module-attribute
¶
Seconds a remote asset has to answer.
The default renderer timeout is 10 seconds per asset, which a page with twenty images turns into a request that outlives any sane gateway.
PdfDocument
¶
Bases: BaseSchema
Base for a bundled document.
A subclass names the template it renders through, which is how
:meth:~tempest_fastapi_sdk.pdf.renderer.PdfRenderer.render_document
resolves one from the payload alone.
Attributes:
| Name | Type | Description |
|---|---|---|
template |
ClassVar[str]
|
Bundled template file name. |
branding |
Branding
|
Shared appearance. |
title |
str | None
|
Overrides the document's default heading. |
ReceiptDocument
¶
Bases: PdfDocument
A recibo — proof that an amount was paid.
Carries the amount in words, which is the element that keeps a figure from being altered after signing.
Attributes:
| Name | Type | Description |
|---|---|---|
number |
str | None
|
Receipt number. |
issue_date |
date
|
Date printed and used in the closing line. |
issuer |
Party
|
Who received the money and signs. |
payer |
Party
|
Who paid. |
amount_cents |
int
|
Amount received. |
reference |
str
|
What the payment was for. |
place |
str | None
|
City printed before the date. |
QuoteDocument
¶
Bases: PdfDocument
A quote / commercial proposal with priced lines.
Attributes:
| Name | Type | Description |
|---|---|---|
number |
str | None
|
Quote number. |
issue_date |
date
|
When it was issued. |
valid_until |
date | None
|
Last day the prices hold. |
issuer |
Party
|
Who is quoting. |
customer |
Party
|
Who receives the quote. |
items |
list[LineItem]
|
The priced lines. At least one. |
discount_cents |
int
|
Discount applied to the subtotal. |
notes |
str | None
|
Free text under the table. |
payment_terms |
str | None
|
How payment is expected. |
ReportDocument
¶
Bases: PdfDocument
A paginated tabular report.
The header and footer repeat on every page and the page number reads
página X de Y, which is what makes a printed listing usable —
somebody has to be able to tell a page is missing.
Attributes:
| Name | Type | Description |
|---|---|---|
heading |
str
|
Report title. |
subtitle |
str | None
|
Line under the title. |
generated_at |
date | None
|
Date printed in the header. |
columns |
list[ReportColumn]
|
Column definitions. At least one. |
rows |
list[dict[str, object]]
|
Row mappings keyed by
|
totals |
dict[str, int]
|
Totals per column key, in cents for money columns. Printed in a final row. |
ContractDocument
¶
Bases: PdfDocument
A contract or written declaration.
Attributes:
| Name | Type | Description |
|---|---|---|
heading |
str
|
Document title. |
preamble |
str | None
|
Paragraph before the clauses, usually qualifying the parties. |
parties |
list[Party]
|
Who is bound. Printed in the header. |
clauses |
list[Clause]
|
Numbered clauses. At least one. |
place |
str | None
|
City in the closing line. |
signed_on |
date | None
|
Date in the closing line. |
signatories |
list[Signatory]
|
Signature blocks. |
VoucherDocument
¶
Bases: PdfDocument
A short receipt or label — half a page or less.
Attributes:
| Name | Type | Description |
|---|---|---|
heading |
str
|
Large text at the top. |
subtitle |
str | None
|
Line under it. |
fields |
dict[str, str]
|
Label/value pairs, printed in order. |
qr_content |
str | None
|
Text to encode as the QR code — a
verification URL, a Pix BR Code. Encoded by
:func: |
qr_data_uri |
str | None
|
QR code already encoded, as a |
note |
str | None
|
Small print at the foot. |
height |
str
|
CSS height of the printed area. |
qr_image
property
¶
Return the data: URI the template embeds, if any.
The encoding is cached together with the content it came from, and
reused only while qr_content still matches. model_copy(update=
{"qr_content": ...}) runs no validator, so a cache keyed on
nothing would keep printing the template's old QR on every copy —
the natural way to issue a batch of tickets from one document.
Returns:
| Type | Description |
|---|---|
str | None
|
str | None: The encoded |
Party
¶
Bases: BaseSchema
A person or company printed on a document.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Legal or trade name. |
document |
str | None
|
CPF or CNPJ. Rendered through
:func: |
address |
str | None
|
Free-form address, one line or several. |
email |
str | None
|
Contact email. |
phone |
str | None
|
Contact phone. |
extra |
dict[str, str]
|
Additional labelled lines, printed in
order — |
Branding
¶
Bases: BaseSchema
Appearance shared by every bundled document.
Attributes:
| Name | Type | Description |
|---|---|---|
logo_data_uri |
str | None
|
Logo as a |
accent_color |
str
|
Colour of rules, table headers and totals. |
footer_text |
str | None
|
Line printed at the foot of every page, next to the page number. |
page_size |
str
|
CSS |
margin |
str
|
CSS |
LineItem
¶
Bases: BaseSchema
One priced line of a quote.
Attributes:
| Name | Type | Description |
|---|---|---|
description |
str
|
What is being charged for. |
quantity |
float
|
How many. Fractional quantities are allowed (hours, kilos). |
unit_price_cents |
int
|
Price of one unit, in cents. |
unit |
str | None
|
Unit label shown next to the quantity. |
total_cents
property
¶
Line total, in cents.
Rounded half-up to the cent, because a fractional quantity times a cent price does not land on an integer and the printed line must add up to the printed total.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
|
Clause
¶
Bases: BaseSchema
One numbered clause of a contract.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str | None
|
Heading. Omit it for a plain paragraph. |
body |
str
|
Text. Blank lines separate paragraphs. |
Signatory
¶
Bases: BaseSchema
One signature block at the foot of a contract.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Who signs. |
role |
str | None
|
Their part — |
document |
str | None
|
CPF or CNPJ, printed under the line. |
ReportColumn
¶
Bases: BaseSchema
One column of a tabular report.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Key read from each row. |
header |
str
|
Column heading. |
align |
str
|
|
money |
bool
|
Render the value as currency. The row must then carry an integer number of cents. |
BUNDLED_DOCUMENTS
module-attribute
¶
BUNDLED_DOCUMENTS: dict[str, type[PdfDocument]] = {
"contract": ContractDocument,
"quote": QuoteDocument,
"receipt": ReceiptDocument,
"report": ReportDocument,
"voucher": VoucherDocument,
}
Bundled document name to its schema.
Drives tempest pdf list and the router's document endpoint, so a new
bundled template is registered in exactly one place.
qr_data_uri
¶
qr_data_uri(
content: str,
*,
error: QrErrorLevel = QR_ERROR_CORRECTION,
scale: int = QR_SCALE,
border: int = QR_BORDER,
) -> str
Encode content as a PNG QR code in a data: URI.
The result matches the pattern of
:attr:~tempest_fastapi_sdk.pdf.VoucherDocument.qr_data_uri, so it
can be passed there directly; :attr:VoucherDocument.qr_content
<tempest_fastapi_sdk.pdf.VoucherDocument.qr_content> calls this with
the defaults.
Example:
>>> from tempest_fastapi_sdk.pdf import qr_data_uri
>>> qr_data_uri("https://example.com/v/42").startswith(
... "data:image/png;base64,"
... )
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
content
|
str
|
The text to encode — a verification URL, a Pix BR Code. Encoded exactly as given, never "optimized" into a Micro QR. |
required |
error
|
QrErrorLevel
|
Error-correction level. See
:data: |
QR_ERROR_CORRECTION
|
scale
|
int
|
Pixels per module. See :data: |
QR_SCALE
|
border
|
int
|
Quiet zone in modules. See :data: |
QR_BORDER
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When |
ValueError
|
When |
QrErrorLevel
module-attribute
¶
ISO/IEC 18004 error-correction level: 7, 15, 25 or 30 % recovery.
QR_ERROR_CORRECTION
module-attribute
¶
QR_ERROR_CORRECTION: Final[QrErrorLevel] = 'h'
Default error correction: H, which recovers 30 % of the symbol.
A voucher is printed, folded, carried in a pocket and scanned off a
crease — damage is the normal case, not the edge case. The price is
density: H needs the most modules for a given payload, and the
voucher's box is a fixed 26mm square, so the modules get smaller.
With segno 1.6.6 and the default margin (deterministic, so exact):
========================= ===== ======= ======== Payload Level Version Module ========================= ===== ======= ======== 66-character URL H 8 0.49 mm 66-character URL M 5 0.63 mm 197-character Pix BR Code H 15 0.32 mm 197-character Pix BR Code M 10 0.43 mm ========================= ===== ======= ========
Both payloads at H, rendered through the voucher by WeasyPrint and
rasterized at 100 dpi, decode with zxing-cpp;
tests/pdf/test_qr.py repeats that at 150 dpi. A caller printing on a
low-resolution thermal printer can pass error="m" to trade recovery
for bigger modules.
QR_SCALE
module-attribute
¶
Default pixels per module in the PNG.
The template sizes the image to 26mm whatever its pixel count, so
the scale sets resolution, not size, and decoding did not change with
it: scales 1, 2, 4 and 8 decoded the same payloads at the same dpi. What
eight buys is margin against a viewer or print pipeline that smooths the
image — the template asks it not to (image-rendering: pixelated
makes WeasyPrint write /Interpolate false; without it, true),
and not every consumer honors the flag. It costs about 4 KiB per
document: the voucher with a Pix BR Code measured 13 KiB at scale 8
against 9 KiB at scale 1.
QR_BORDER
module-attribute
¶
Default quiet zone, in modules, drawn inside the PNG.
ISO/IEC 18004 asks for four. The voucher supplies the rest: the image
sits inside 6mm of white padding with a 5mm gap to the text, and
two modules are at most 2.08mm — version 1, the largest module the
box can hold (26mm over 25 modules). Drawing all four inside the
image shrinks every module to pay for white the page already has: the
66-character URL at version 8 spans 53 modules with two a side and 57
with four, so each module loses 7 %.
format_cents
¶
Format an integer number of cents as Brazilian currency.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cents
|
int
|
Amount in cents. Negative values keep the sign in
front of the symbol ( |
required |
symbol
|
bool
|
Whether to prefix |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted amount, e.g. |
format_date
¶
Format a date as dd/mm/aaaa.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
date | datetime
|
The date to format. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted date. |
format_date_long
¶
Format a date the way a signed document spells it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
date | datetime
|
The date to format. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
E.g. |
format_document
¶
Format a CPF or CNPJ for display, leaving anything else alone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
str
|
Digits, with or without punctuation. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
str
|
for 14, and the input unchanged otherwise — a foreign passport |
|
str
|
number in this field must not be mangled into a shape it is not. |
format_quantity
¶
Format a quantity the way an invoice line reads in Brazil.
A whole quantity prints without a decimal part (2, not
2,000); a fractional one uses a comma and drops trailing zeros
(2,5). Printing 2.5 on a Brazilian document reads as a
thousands separator to the person holding it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float
|
The quantity. |
required |
decimals
|
int
|
Maximum decimal places kept. |
3
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The formatted quantity. |
valor_por_extenso
¶
Spell an amount in cents as Brazilian currency, in words.
This is the line a recibo carries under the figure, and it exists because a figure alone can be altered after signing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cents
|
int
|
Amount in cents. Must be non-negative — a receipt for a negative amount is a different document. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
E.g. ``"mil duzentos e trinta e quatro reais e cinquenta e |
str
|
seis centavos"``. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
MAX_EXTENSO_CENTS
module-attribute
¶
Largest value :func:valor_por_extenso spells, in cents.
The scale table stops at trilhões; a value above it would silently lose its most significant group, so it raises instead.
MONTHS_PT_BR
module-attribute
¶
MONTHS_PT_BR: tuple[str, ...] = (
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro",
)
Month names used by :func:format_date_long, lowercase as in BR usage.
make_pdf_router
¶
make_pdf_router(
renderer: PdfRenderer,
*,
prefix: str = "/pdf",
tags: list[str] | None = None,
dependencies: Sequence[Any] | None = None,
inline: bool = False,
docs_locale: str | None = None,
) -> APIRouter
Build the router that renders the bundled documents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
renderer
|
PdfRenderer
|
The configured renderer. Its asset policy and template directory apply to every route here. |
required |
prefix
|
str
|
URL prefix. Defaults to |
'/pdf'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
dependencies
|
Sequence[Any] | None
|
FastAPI dependencies applied to every route — this is where auth and rate limiting go. The router adds none by itself. |
None
|
inline
|
bool
|
Serve with |
False
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
safe_filename
¶
Reduce a caller-supplied name to something safe in a header.
A filename reaches Content-Disposition, where a quote ends the
quoted string and a newline splits the response into two. Directory
separators matter less here — nothing writes the file server-side —
but a name carrying them is never what the caller meant either.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
The requested name. |
required |
default
|
str
|
Used when |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A name safe to interpolate, always ending in |
DocumentRequestSchema
¶
Bases: BaseSchema
Request body for rendering a bundled document.
Attributes:
| Name | Type | Description |
|---|---|---|
payload |
dict[str, Any]
|
The document's fields, validated
against the schema the |
filename |
str | None
|
Name suggested to the browser. |
DocumentListSchema
¶
Bases: BaseSchema
One entry of the bundled-document listing.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name to pass as the path parameter. |
schema_name |
str
|
Python class validating its payload. |
json_schema |
dict[str, Any]
|
The JSON Schema of that class, so a client can build a form without reading the SDK. |
PDF_MEDIA_TYPE
module-attribute
¶
Media type of every response this router produces.
extract_pdf_pages
¶
extract_pdf_pages(data: bytes) -> list[PageText]
Read every page's text layer, keeping page boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The PDF file contents. |
required |
Returns:
| Type | Description |
|---|---|
list[PageText]
|
list[PageText]: One entry per page, in document order. A page with |
list[PageText]
|
no text layer comes back with an empty string rather than being |
list[PageText]
|
dropped, so entry |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
PdfReadError
|
When the bytes are not a readable PDF. |
extract_pdf_text
¶
extract_pdf_text(
data: bytes,
*,
max_chars: int | None = None,
page_marker: str = DEFAULT_PAGE_MARKER,
truncation_notice: str = DEFAULT_TRUNCATION_NOTICE,
partial_page_notice: str = DEFAULT_PARTIAL_PAGE_NOTICE,
) -> str
Read a PDF into one string, annotated with page markers.
Truncation prefers page boundaries: whole pages are kept while they fit,
because a page that survives is a page the model can cite. When not even
the first page fits, the cut happens mid-page and
partial_page_notice says so — returning nothing but a notice would
hand the model an empty prompt, which is the failure this module exists
to prevent.
The result never exceeds max_chars. The notice is part of the
budget, not an addition to it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The PDF file contents. |
required |
max_chars
|
int | None
|
Ceiling on the returned length. |
None
|
page_marker
|
str
|
Template for the per-page separator. Receives
|
DEFAULT_PAGE_MARKER
|
truncation_notice
|
str
|
Template appended when the cut lands on a
page boundary. Receives |
DEFAULT_TRUNCATION_NOTICE
|
partial_page_notice
|
str
|
Template appended when the cut lands
inside page 1. Receives |
DEFAULT_PARTIAL_PAGE_NOTICE
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The document text, or an empty string when no page carries a |
str
|
text layer — the signature of a scanned document. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
PdfReadError
|
When the bytes are not a readable PDF. |
Notes
A budget too small to carry the notice beside a real slice of text
returns raw document text cut to max_chars — no notice, and no
page marker either. The marker is dropped for the same reason the
notice is: it costs 16 characters that this regime does not have.
Rendering it while it merely fit made the result shrink as the
budget grew — measured on a 239-character page, max_chars=16
returned 16 characters of document and max_chars=17 returned
one, the marker having eaten the rest. Paying more for less is not
a trade-off a caller asked for.
PageText
module-attribute
¶
A one-based page number paired with the text found on that page.
DEFAULT_PAGE_MARKER
module-attribute
¶
Separator written above each page's text.
Not decoration: it gives a model something to cite when asked where a value came from. Override it to match the language of the surrounding prompt — a marker in a different language than the instruction is one more thing for the model to reconcile.
DEFAULT_TRUNCATION_NOTICE
module-attribute
¶
Line appended when the text is cut at a page boundary.
A silent cut is the dangerous one: the model answers about the half it was shown, with no sign that a half is missing.
DEFAULT_PARTIAL_PAGE_NOTICE
module-attribute
¶
Line appended when even the first page did not fit max_chars.
Distinct from :data:DEFAULT_TRUNCATION_NOTICE on purpose: a reader (human
or model) that sees this knows the last sentence may stop in the middle, so a
value read near the end is not to be trusted the way a whole page is. Asking
for a budget smaller than one page used to return only the notice — no
document text at all, and 46 characters for a max_chars=40.
read_pdf_pages
async
¶
read_pdf_pages(
data: bytes, *, extractor: PdfExtractorEnum = TEXT, password: str | None = None
) -> PdfPagesResult
Read a PDF page by page, optionally recovering layout and tables.
Both backends are synchronous and CPU-bound, so the work runs in a worker thread. A large scanned document can occupy that thread for seconds — this is a call to bound with a timeout, not one to fan out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The PDF file contents. |
required |
extractor
|
PdfExtractorEnum
|
Which backend to use. Defaults to
:attr: |
TEXT
|
password
|
str | None
|
Password for an encrypted document. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
PdfPagesResult |
PdfPagesResult
|
The document's pages, in order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the extra the chosen backend needs is missing. |
PdfDecryptError
|
When the document is encrypted and the password does not open it. |
PdfExtractError
|
When parsing fails for any other reason. |
PdfExtractorEnum
¶
Bases: BaseStrEnum
Which extraction backend reads the document.
Attributes:
| Name | Type | Description |
|---|---|---|
TEXT |
|
|
LAYOUT |
|
PdfPage
¶
Bases: BaseSchema
One page's extracted contents.
Attributes:
| Name | Type | Description |
|---|---|---|
page_number |
int
|
One-based page index, matching the document. |
text |
str
|
Plain text found on the page. Empty for a page with no text layer — a scan — rather than absent. |
tables |
list[list[list[str]]]
|
Tables found on the page, only
populated by :attr: |
PdfPagesResult
¶
Bases: BaseSchema
A whole document, read page by page.
Attributes:
| Name | Type | Description |
|---|---|---|
extractor |
PdfExtractorEnum
|
Which backend produced this result. |
page_count |
int
|
Number of pages read. |
pages |
list[PdfPage]
|
One entry per page, in document order. |