Python SDK

Use the Python SDK to moderate content, manage assets and handle events from your server, with thread-safe synchronous calls, streamed transfers and type hints for every method. It requires Python 3.10 or later and has no runtime dependencies. The Python SDK reference lists every client option and method in detail.

Install

python -m pip install calmlens

See Versioning and support for what each version change means and where to find the changelog.

Moderate content

Keep credentials on your server. Create an API key and copy your project ID as described in Authentication. Without arguments, the client reads CALMLENS_API_KEY and CALMLENS_PROJECT_ID from the environment. assets.create() returns without waiting for the decision; assets.classify() and text.classify() wait for it. Audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.

from calmlens import CalmLensServerClient

client = CalmLensServerClient()
asset = client.text.classify(text="Great photo!", external_id="comment-42")
if asset["classification"]["moderation"]["status"] == "allowed":
    print("Publish", asset["id"])

Methods take snake_case keyword arguments, or one options dict with the API's camelCase keys, such as client.assets.retrieve({"assetId": asset_id}). Dicts passed as values, such as processing_options, use the API's camelCase keys. In updates, pass None to clear a nullable field (or, for assets.move, to move to the project root), and omit a field to leave it unchanged.

Publish allowed content normally and limited content with reduced reach. Serve age-restricted content only to viewers your app allows, by passing viewer_claims={"ageConfirmed": True} to the CDN methods; a signed URL or your API key alone doesn't serve it. See Age-restricted assets. Treat a status you don't recognise as not allowed, and treat failed requests the same way. See Reading classification results and Policies and actions.

Classification results

Responses are dicts with the API's camelCase field names, typed with TypedDicts such as Asset and AssetClassification. id, upload, classification and content are always present, with the moderation status under classification.moderation. Moderation fields such as classification["moderation"]["categories"] are None until moderation decides, and feature results such as classification["ocr"] are None until they have run. metadata and tags are always lists, empty when there are none. Other optional fields, such as externalId and folderId, appear only when they apply. Status and other enum values are plain strings, so a value added in a newer API version doesn't break your code.

Waiting for a decision

assets.wait_for_decision(asset_id=..., timeout=60) retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks, until its classification.status is completed or failed, and returns it. If there is no decision within timeout seconds (default 60), it raises CalmLensError with code sdk/timeout, and details holds the assetId and the last classificationStatus and moderationStatus. To stop waiting sooner, pass a shorter timeout.

Uploads

with open("photo.jpg", "rb") as file:
    queued = client.assets.create(
        name="photo.jpg",
        content={"data": file, "type": "image/jpeg"},
        visibility="private",
        processing_options={"keepContentAfterProcessing": True},
    )

# Wait for the decision, retrieve it later, or respond to an asset.allowed or asset.blocked webhook.
asset = client.assets.wait_for_decision(asset_id=queued["id"], timeout=30)
if asset["classification"]["moderation"]["status"] == "allowed":
    signed = client.cdn.sign_asset_url(asset_id=asset["id"], original=True, expires_in=60)
    print(f"{signed['url']}/original")

data accepts bytes or a binary file object. Files are streamed in chunks rather than read into memory, and their size is measured automatically. A stream that can't seek, such as a pipe, is sent to its end in chunks; pass its sizeInBytes when you know it (multipart parts need it). The timeout applies to a silent connection, not to the whole transfer, so large uploads and downloads are not cut off.

To upload from a link, pass url= instead of content: CalmLens downloads the file, up to 10 MiB for images and 20 MiB for other files. For multipart limits and sequential uploads, see Multipart uploads. Retain content only when you need previews, transforms or CDN delivery.

Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.

Metadata is a list of {id, value} items, such as metadata=[{"id": "campaign.id", "value": "launch-2026"}]. The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.

Upload presets

Pass upload_preset_id= on assets.create and assets.classify to apply an upload preset's folder, visibility, file types and size limit. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.upload_tokens.sign(upload_preset_id=...). Signing happens locally with your API key and makes no request.

CDN methods

Fetch retained content directly from your backend with client.cdn.serve():

with client.cdn.serve({"assetId": "asset_5Gm2Rk8XqT3wLp9VbN4c", "resource": "original"}) as response:
    if not 200 <= response.status < 300:
        raise RuntimeError(f"CDN returned HTTP {response.status}")
    content = response.read()
print(len(content))

The response contains raw content bytes, not the asset report. Check the response status before using the body; for text assets (such as comments sent with text.classify), decode the body as text. The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with client.cdn.sign_asset_url() (see Signed asset URLs).

Upload with processing_options={"keepContentAfterProcessing": True} to retain content. The CDN delivers by the current classification.moderation.status, and still requires available content and authorised access. See Delivery while moderation runs.

Methods

See the reference for each method's options and examples.

MethodPurpose
text.classify(text=..., ...)Classify text and wait for the decision.
assets.create(...)Upload content and return without waiting for the decision.
assets.classify(...)Upload content and wait for the decision where supported.
assets.upload_part(...)Send the next part of a multipart upload.
assets.retrieve(asset_id=...)Fetch one asset.
assets.wait_for_decision(asset_id=..., timeout=...)Retrieve an asset until it is completed or failed; see Waiting for a decision.
assets.list_timeline(asset_id=..., cursor=..., page_size=...) / assets.iter_timeline(asset_id=...)Page through an audio or video asset's findings timeline Preview, in time order.
assets.list(...) / assets.iter(...)List one page of assets, or iterate over every matching asset.
assets.search(query=..., ...)Search assets by keyword or meaning; see Asset search.
assets.list_children(asset_id=...) / assets.iter_children(asset_id=...)List an asset's extracted children.
assets.update(asset_id=..., ...)Update asset fields.
assets.move(asset_id=..., folder_id=...)Move an asset to a folder, or to the project root with None.
assets.retry(asset_id=...)Retry an eligible processing failure.
assets.decide(asset_id=..., decision=..., note=...)Record a reviewer's decision (allowed, limited, age-restricted, blocked or purged) with a required note. An asset pending moderation can only be blocked or purged, and purging needs confirm_purge=True; see POST /assets/:assetId/decision.
assets.explain(asset_id=..., rerun=...)Fetch the full policy evidence for a decision (which rules and findings produced it), or with rerun=True moderate the asset again under the current policy.
assets.remove_content(asset_id=...)Remove stored content and keep the asset record and report.
assets.delete(asset_id=...)Delete the asset record and its content.
assets.batch(asset_ids=..., operation=...)Delete up to 500 assets ("delete") or remove their stored content ("remove-content") in one queued request; see POST /projects/:projectId/assets/batch.
folders.list(), folders.iter(), folders.retrieve(), folders.create(), folders.update(), folders.move(), folders.delete()Manage folders. folders.list() returns a page of up to 50 root folders by name by default, with the ancestors needed to show their paths. Only empty folders can be deleted.
hash_lists.list(), hash_lists.iter(), hash_lists.retrieve(), hash_lists.create(), hash_lists.update(), hash_lists.delete()Manage hash lists that image uploads are compared with.
hash_lists.list_entries(), hash_lists.iter_entries(), hash_lists.add_entry(), hash_lists.remove_entry()Manage the hashes in a hash list.
policies.list(), policies.iter(), policies.retrieve(), policies.create(), policies.update(), policies.reset(), policies.upgrade(), policies.set_automatic_updates(), policies.delete()Manage the organisation's moderation policies; see Policies.
policies.retrieve_assigned() / policies.assign(policy_id=...)Read or choose the policy the project moderates with.
events.list(...) / events.iter_pages(...) / events.iter(...)Read one page of the project event feed, follow its cursor page by page, or iterate over its events.
lenses.list(), lenses.iter(), lenses.create(), lenses.retrieve(), lenses.update(), lenses.delete()Manage the project's lenses.
ensure_lens(...) / ensure_lenses(...)Create lenses, or change them to the definitions sent, by identifier.
cdn.get_asset_url(...) / cdn.serve(...)Build a CDN URL, or stream content.
cdn.sign_asset_url(asset_id=..., ...)Sign a private asset's URL.
cdn.get_asset_info(url)Read an asset URL's display info.
upload_tokens.sign(upload_preset_id=..., expires_in=...)Sign an upload token locally, without a request.

Pagination

Every list returns a cursor page: items, hasMore and nextCursor. Omit cursor for the first page, then pass the response's nextCursor as cursor, with the same filters, until it is None; set the page size with page_size. Lists of assets, hash lists, hash list entries, policies and lenses take sort: a comma-separated list of createdAt and id, each descending when prefixed with -, such as sort="-createdAt,id". Folders sort by name (the default) or createdAt. Each list has an iterator that fetches the pages for you: assets.iter, assets.iter_children, assets.iter_timeline, folders.iter, hash_lists.iter, hash_lists.iter_entries, policies.iter and lenses.iter.

page = client.folders.list(parent_id=folder_id, page_size=50)
while page["nextCursor"]:
    page = client.folders.list(parent_id=folder_id, page_size=50, cursor=page["nextCursor"])

for asset in client.assets.iter(filter=f"folderId=={folder_id}", sort="createdAt"):
    print(asset["name"])

The event feed's nextCursor is never None. events.list() without a cursor returns no events and a nextCursor for the current time; later calls return the events after it. Use events.iter_pages to read pending pages and save the last nextCursor. See Reading the feed for cursor semantics.

cursor = client.events.list()["nextCursor"]  # no events; starts from now
for page in client.events.iter_pages(cursor=cursor, page_size=50):
    for event in page["items"]:
        print(event["type"], event["facts"])
    cursor = page["nextCursor"]

The iterators, including events.iter_pages and events.iter, raise sdk/invalid-response, with the cursor in details["cursor"], rather than loop when a page that says more follow repeats a cursor they already sent.

Concurrency and async code

One client is safe to share between threads, and reusing it keeps connections open between calls. In a forked worker process, such as a gunicorn or Celery worker, the client opens new connections rather than sharing the parent's. Calls are synchronous; from async code, run them in a thread:

asset = await asyncio.to_thread(client.text.classify, text=body, external_id=comment_id)

Errors and retries

Every failure raises CalmLensError or one of its subclasses, except that passing the webhook helpers anything other than the raw str or bytes body, such as a parsed dict, raises TypeError:

ClassRaised for
CalmLensAPIErrorAPI error responses
CalmLensTimeoutError, CalmLensTransportErrorTimeouts and other network failures
CalmLensValidationErrorInvalid arguments or configuration, detected before anything is sent
WebhookVerificationErrorWebhook deliveries that fail verification or aren't CalmLens events

Each error has a stable code (constants in calmlens.error_codes), the HTTP status, the request_id to quote to support (the response's X-Request-Id header, or the error body's requestId), the API's details object, retry_after, headers, and the is_not_found and is_retryable helpers. assets.wait_for_decision raises a plain CalmLensError with sdk/timeout, not a CalmLensTimeoutError, so check code rather than the class. is_retryable is True for network failures and timeouts (including assets.wait_for_decision's sdk/timeout), 409 idempotency/request-in-progress, and HTTP 429, 500, 502, 503 and 504, whatever the error's class.

from calmlens import CalmLensAPIError, error_codes

try:
    asset = client.assets.retrieve(asset_id="asset_5Gm2Rk8XqT3wLp9VbN4c")
except CalmLensAPIError as error:
    if error.code != error_codes.ASSET_NOT_FOUND:
        print(error.code, error.status, error.request_id)
        raise
    asset = None
FailureWhat the SDK doesWhat you do
Network failure or timeoutRetries reads and uploads up to max_retries times (default 2), each time waiting between half and all of a delay that starts at 0.5 seconds and doubles up to 8 secondsOnce retries run out, retry later: is_retryable is True
429, 500, 502, 503, 504 or 409 idempotency/request-in-progressRetries the same requests, waiting for Retry-After (seconds or a date; 0 retries at once) when the API sends oneA Retry-After over 60 seconds is raised to you instead: wait, then retry
assets.wait_for_decision runs out of timeRaises a CalmLensError with sdk/timeoutWait again, or rely on a webhook
Failure of another write, such as assets.update or assets.deleteNot retriedRetry only when repeating the change is safe
Upload from a stream that can't seek, such as a pipeSent onceUpload again from the start
Upload retried from another processEach call sends a new Idempotency-Key, reused for its own retriesPass the same idempotency_key=
RedirectNot followed; raises sdk/http-error with its statusCheck base_url and cdn_base_url
cdn.serve failureRetries the same failures. Once retries run out, returns the last error response instead of raising; a network failure or timeout still raisesCheck the response status
SettingDefaultLimits
timeout120 secondsInactivity on a connection, not the whole transfer
upload_timeouttimeoutInactivity while sending file content and multipart parts
connect_timeout10 secondsOpening a connection
max_response_bytes32 MiBThe API response body the client reads
part_size_bytes8 MiBContent larger than this is uploaded in parts of this size, from 5 to 64 MiB

Set them, and max_retries, on the client. client.with_options(timeout=300) returns a client sharing the same connections with another timeout, upload_timeout, max_retries or max_response_bytes. See Retries and idempotency for which requests are retried, and Retrying requests safely.

Webhooks

Verify the exact raw request body, then parse it, with parse_webhook_event. It accepts only the raw str or bytes body: a body that was parsed and serialised again rarely has the same bytes, so the signature would not match.

import os
from calmlens import WebhookVerificationError, parse_webhook_event

def handle_webhook(raw_body: bytes, headers) -> int:
    try:
        event = parse_webhook_event(raw_body, headers=headers, secret=os.environ["CALMLENS_WEBHOOK_SECRET"])
    except WebhookVerificationError:
        return 401
    # Queue the work, keyed by event["id"], then respond quickly.
    return 204

Pass the raw body your framework received:

FrameworkRaw bodyHeaders
Flaskrequest.get_data()request.headers
Djangorequest.body (exempt the view from CSRF)request.headers
FastAPI or Starletteawait request.body() (don't declare a body model)request.headers

verify_webhook_signature takes the same arguments and returns True or False. Both read the x-calmlens-signature and x-calmlens-timestamp headers from headers, by name in any case, joining a header repeated in the request with ,, or take them as signature= and timestamp=. Timestamps more than 5 minutes from the current time are rejected; tolerance_seconds= changes that.

parse_webhook_event raises WebhookVerificationError with sdk/invalid-webhook-signature for a missing, wrong or stale signature, and with sdk/invalid-webhook-payload for a verified body that isn't a CalmLens event. The parsed event has the same fields as an event from events.list: id, projectId, type, severity, title, description, assetId, asset, facts and createdAt. It keeps fields, event types and fact keys it doesn't know. get_event_fact(event, key) returns one fact's value, or None when the event doesn't carry it, and get_event_facts(event) returns every fact's value by key, such as {"flagged-categories": ["hate"]}; a key repeated in the event keeps its first value. is_test_webhook_event(event) tells a test send from the portal or the CLI from a real event. Deliveries also carry x-calmlens-delivery, which stays the same across a delivery's retries; a redelivery gets a new one, so deduplicate on the event id. See Webhooks.

Command-line tool

See Local development to install the CLI, forward signed events and trigger test uploads.

Testing

Use MockCalmLensServerClient from calmlens.testing for offline tests. See Python testing.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies