Classify assets

Submit files, inline content or remote URLs for moderation, using multipart uploads for larger files. Authenticate with a project API key on your server; see the Assets API reference for fields and errors.

Upload with an SDK

For files, pass a file, buffer or stream to your SDK. It selects the upload mode and handles authentication. Each file must be within its type's size and duration limits.

How should the decision arrive?
import { readFile } from "node:fs/promises";
const asset = await client.assets.classify({
  name: "photo.jpg",
  content: { buffer: await readFile("./photo.jpg"), type: "image/jpeg" },
});
// Audio and video can still be pending; publish only allowed assets.
console.log(asset.classification.moderation.status);

Waiting for the decision

Choose either flow independently of the upload mode:

FlowSDKDirect HTTPResult
Moderate in placeclient.assets.classify()wait=true (the default)Wait for classification and read the decision from the response.
Queue moderationclient.assets.create()wait=falseReceive an asset ID while classification runs, then get the decision through a webhook; see Receive a queued moderation result.

Moderating in place usually takes several seconds for text and images. Long documents take longer, and so does content with links the first time link safety Preview checks their domain, which can add up to about 20 seconds. If a person is waiting on the request, show their post as pending to them until the decision arrives, or queue moderation and finish with the webhook.

Text and images support both flows. Audio, video and files over 20 MiB sent in parts are always queued, even with wait=true, and return with classification.moderation.status pending. A multipart upload uses the wait choice made when it starts: CalmLens saves it with the upload, so whichever client sends the final part gets the same behaviour. See Waiting for the decision.

For queued uploads, save the asset ID and configure a webhook for asset.allowed, asset.limited, asset.age-restricted, asset.blocked, asset.purged and asset.failed. Keep content unpublished while classification.moderation.status is pending, then show it as described in Using the decision; a successful upload alone is not a moderation decision.

Completed assets carry classification.moderation, described in Reading classification results. Check each category's status before reading score.

See Asset lifecycle for processing, moderation and content states, and Delivering assets to serve asset content, create signed URLs for private assets, and apply lenses (named image resizes and conversions).

Fallback when webhooks are unavailable

If your integration cannot receive webhooks, retrieve the asset periodically with client.assets.retrieve({ assetId }). Use client.assets.waitForDecision() for SDK polling with a timeout, or manage the polling loop yourself; a single retrieval call does not wait for classification.

Start with a short delay, increase it between checks using exponential backoff, and cap the interval. Set an overall timeout so checks cannot continue indefinitely. Stop once the asset is settled, when classification.status is completed or failed; keep content unpublished while classification.moderation.status is pending. If the timeout expires, treat the result as unresolved and keep the content unpublished. For a failed classification, follow Recover from processing failure.

client.assets.retrieve({ assetId })

Using the decision

The asset response contains the stored moderation decisions. The CDN applies each viewer's regional and age outcome when it serves the file; see Viewer region for the viewer claims it reads (the viewer's region and age confirmation) and what to do when you proxy or serve files yourself.

Store classification.moderation.status with your own record and show the content as follows. Regional rules can further restrict what viewers in particular jurisdictions receive.

StatusAuthorEveryone else
pendingShow it as pendingDo not show it
allowedShow itShow it
limitedShow itShow it, but leave it out of recommendations and notifications
age-restrictedShow it as age-restrictedShow it only to viewers your app allows, and the placeholder to everyone else
blockedExplain that it was blockedDo not show it
purgedExplain that it was removedDo not show it

Treat an asset whose classification.status is failed as not published, and retry it or ask the author to try again. classification.moderation keeps the automated assessment after a reviewer changes the status, and manualReviews holds the review history. To serve the content, see Delivering assets, including age-restricted assets.

Upload modes

Every upload mode uses POST /projects/:projectId/assets. The request body decides the mode:

You haveUseRequest body
A file, buffer or streamDirect binary uploadThe file's bytes, with X-CalmLens-Upload: content
Base64 content or bytes inside a JSON requestJSON uploadJSON with content.base64 or content.uint8Array
Text you have already extractedPlain text uploadJSON with content.plainText
A public web page or file URLRemote URL uploadJSON with url
A large file, or one you produce in chunksMultipart uploadThe first part's bytes, with X-CalmLens-Upload: part, then POST /assets/:assetId/part for the rest

The SDKs choose the mode for you: they stream files with direct binary or multipart uploads and send other inputs as JSON.

Direct binary upload

For direct HTTP integrations, send the unencoded file as the request body with the file's Content-Type and the X-CalmLens-Upload: content header. Asset fields go in query parameters. The header is what marks the body as a file, so a JSON file is uploaded as a file rather than read as a request. See POST /projects/:projectId/assets for the complete request.

JSON upload

Without the X-CalmLens-Upload header, the body is JSON: base64 content, plain text or a remote URL.

  • Each asset type has the same limit as in a direct binary upload; see Asset types and limits. Base64 adds about a third to the request size, so send large files as a direct binary or multipart upload.
  • The request body can contain content.base64, content.uint8Array (the bytes as an array of numbers from 0 to 255), content.plainText, or url.

JSON upload with base64 content

const response = await client.assets.create({
  "name": "cat.png",
  "description": "Homepage hero image",
  "visibility": "private",
  "processingOptions": {
    "keepContentAfterProcessing": true
  },
  "content": {
    "base64": "your-base64-file",
    "type": "image/png"
  }
});

Plain text upload

const response = await client.assets.create({
  "name": "notes.txt",
  "content": {
    "plainText": "This is the extracted text to moderate.",
    "type": "text/plain"
  }
});

Remote URL upload

Remote URLs must use HTTP or HTTPS. Private IP addresses, localhost names and URL credentials are rejected, and each redirect is checked against the same rules. The project's Accepted domains also applies to the URL and to every redirect; a refused URL returns 403 remote-url/not-allowed. Downloads time out after 30 seconds and are limited to 10 MiB for images and 20 MiB for other files. Use multipart upload for larger files.

const response = await client.assets.create({
  "name": "landing-page",
  "url": "https://example.com"
});

Multipart upload

The SDK chooses multipart uploads when needed. For manual chunks, ordering, finalisation and recovery, see Multipart uploads.

Retrying uploads

Use an Idempotency-Key when retrying uploads; SDKs generate one automatically. See Retrying requests safely for replay behaviour and the distinction from externalId.

Asset types and limits

Unsupported image formats return 415 upload/unsupported-type, corrupt images return 422 image/invalid, and images over the size limits below return 422 image/too-large. Multipage TIFF files are not supported; upload their pages as separate images. Camera RAW, compressed SVG (SVGZ), JPEG XR, EXR/HDR, GIMP XCF and DDS images must be exported to a supported format first. These failures require a different file rather than repeated retries.

Photoshop PSD/PSB files are processed from their stored merged image. Editable layers are not moderated separately. If your upload library does not identify the file type correctly, supply its MIME type explicitly: image/vnd.adobe.photoshop for PSD/PSB, image/jp2 for JP2/J2K, image/qoi for QOI, or image/x-portable-arbitrarymap for PAM.

CalmLens detects the asset type from the content's MIME type. A type that isn't listed below, such as an archive, font or application/octet-stream, is refused with 415 upload/unsupported-type before anything is stored. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS and ODS) and presentations (PPTX, PPTM, PPT and ODP); Keynote and Numbers files are refused, so export them to one of these first. CSV files are moderated as plain text. Plain text is read in the encoding a browser would use: a byte order mark, then the charset its MIME type declares, then UTF-8. Text that declares neither and isn't UTF-8 is read as windows-1252, as browsers read such legacy text, and its content.format gains charset=windows-1252. Text that isn't valid in the encoding it declares, or that names an encoding browsers don't support, is refused with 400 upload-payload/invalid. The original resource serves text as UTF-8. A document's content.format and content.extension stay those of the file you uploaded.

Asset typeHow it is detectedTypical inputUpload limitGuide
imageSupported image/* MIME typesPNG, JPEG, SVG, WebP, GIF, AVIF, HEIC/HEIF, TIFF, BMP, ICO, APNG, JPEG XL, Photoshop PSD/PSB, JPEG 2000 (JP2/J2K), TGA, PCX, QOI and portable bitmap formats (PBM/PGM/PPM/PAM)20 MiB; over 10 MiB needs a multipart uploadOCR and image reports
video Previewvideo/* MIME typesMP4, MOV, WebM50 MiB and 120 seconds; with billing set up, 30 minutes, and 2 GiB in a multipart uploadAudio and video
audio Previewaudio/* MIME typesMP3, WAV, M4A50 MiB and 120 seconds; with billing set up, 30 minutes, and 2 GiB in a multipart uploadAudio and video
plaintext-documentPlain text MIME typesTXT, JSON, CSV, YAML5,000 MiBReading classification results
multimedia-documentSupported document MIME typesPDF, DOCX, DOC, RTF, ODT, XLSX, XLSM, XLS, ODS, PPTX, PPTM, PPT, ODP5,000 MiBSpreadsheets and presentations
website Previewtext/html MIME type or URL uploadHTML or remote website URL5,000 MiBWebsite moderation

Images can be at most 12,000 × 12,000 pixels. TIFF, BMP, ICO, APNG, JPEG XL, Photoshop, JPEG 2000, TGA, PCX, QOI and portable bitmap images can be at most 10,000 pixels on each side and 16 million pixels in total.

Every image an ICO file holds is moderated, since browsers show whichever size fits where they draw it. Images repeated in the file count once; the first is moderated as the image, and each group of up to eight others is billed as one more image moderation. An icon with more than 32 distinct images fails with too-many-items.

Before billing is set up, text and document uploads have lower limits. See Free uploads.

Word documents and PDFs

A document's text becomes one text child and every embedded image becomes an image child, like other child assets. A Word (DOCX) or OpenDocument text (ODT) file is read as written: its body and tables, each header and footer once, footnotes and endnotes, text boxes and shapes, both the content Word shows and the fallback older programs show, WordArt, embedded documents, alt text, comments and tracked changes, with deleted text marked as deleted, and its SVG pictures as well as their fallback images. When it holds content that reading the file can't fully show, such as drawings and shapes, charts, embedded objects, WordArt, vector, cropped or adjusted pictures, fields, text over a picture, shading and backgrounds, list labels with words, or symbol or embedded fonts, its rendered PDF and its preview are made with its decision, and what they show beyond that read is moderated too: text the read didn't find, pictures unlike its images, and pages with drawings, charts or other content beyond text and images, as images of those pages. Any other Word or ODT document is decided from its read alone, sooner, and its rendered PDF and preview follow shortly after the decision. If they would show anything beyond that read, they aren't made, and the document keeps its decision without a rendered PDF or preview. A PDF is read page by page, and DOC and RTF files are converted to PDF first; their first page is the preview. Its annotation text and form-field values join its text, its images are moderated wherever they are drawn and with their transparency, and a page that shows more than its text and images is rendered and moderated as an image: drawings and shading, annotations and form fields that draw themselves, and text whose letters don't extract as they are shown, which CalmLens finds by reading the page's visible text.

Spreadsheets and presentations

Spreadsheets and presentations are moderated through child assets, like other documents, and the parent's status follows them. Hidden sheets, rows, columns and slides are moderated and billed like visible ones.

  • Spreadsheets. Every sheet's cells become one text child, read sheet by sheet and row by row, with cell comments, text boxes and shapes, and chart titles and series names. A cell whose number format adds text shows that text beside its value. A formula is included beside its value when its text says something the value doesn't. Links in cells, including HYPERLINK() targets, go to link safety Preview with the rest of the text. Every embedded image becomes an image child, in legacy Excel (XLS) workbooks too. Sheets aren't rendered as pictures.
  • Presentations. The slides' text, alt text, speaker notes and comments become one text child, read slide by slide, and the images on every slide become image children, each distinct image once. A slide that shows something its text and images don't is also rendered as an image child, so it is moderated as it appears: drawings and shapes, filled boxes without text, tables with filled empty cells or picture fills, charts, SmartArt and embedded objects, WordArt and other styled or rotated text, vector pictures, and text placed over a picture or a picture-filled shape, such as a caption on a photo. The images on a rendered slide are moderated through its render, so every slide's pictures and drawings are moderated one way or the other. A slide that looks the same as one already rendered, in colour, isn't rendered again. The first slide is the document's preview.

Embedded audio and video files in presentations, DOCX and ODT documents and XLSX and ODS spreadsheets become audio and video children, each moderated as an upload of that file would be, with the same limits and billing: a clip longer than your plan allows fails, and the document with it. Identical clips are each moderated. Media a slide only links to is never fetched; its address is moderated with the slide's text, and checked by link safety Preview when your policy uses it.

Nothing in a document is left out: a document, spreadsheet or presentation can hold up to 500 distinct embedded images and 50 audio and video files, every one of them moderated and billed. An upload with more is refused with 422 document/too-many-items, and one whose count is only known once it is read, such as a PDF's images, fails with too-many-items. A document is never decided from part of its content.

Macros are never run, and linked files, external data and embedded objects are never fetched. A spreadsheet can have up to 1,000,000 non-empty cells and 200 sheets, and a presentation up to 300 slides. A file over a limit, or one that is encrypted or can't be read, fails with file-too-large or undecodable-content. Text is billed as text-moderation tokens, each embedded image and rendered slide as an image, and each embedded clip as audio or video.

Processing features

Optional analyses are chosen per upload in processingOptions.features, keyed by feature, or set on an upload preset for every upload through it. Each feature takes an object with enabled and any options of its own. Link detection runs unless you send enabled: false, and streaming follows the project's streaming setting unless you set it; the other features have no project setting and run only when you send enabled: true.

FeatureWhat it doesOptionsBilling
ocrStores extracted text on the image and adds a text moderation pass.enabledOCR per image, plus text-moderation tokens for the extracted text
linkDetectionOn by default. Decodes QR codes, moderates what they say as text, and lists the web links in them and in OCR text.enabledFree; QR code text bills text-moderation tokens
streaming PreviewPrepares an adaptive (HLS) stream of audio or video once it is decided, and needs keepContentAfterProcessing: true. Follows Prepare streams for new uploads unless set.enabledStream encoding per started minute of video; audio-only streams are free
FeatureWhat it doesOptionsBilling
personDetection PreviewLocates people in images.enabledPerson detection per image
faceDetection PreviewLocates faces, with an estimated age range for each when ageEstimation is true.enabled, ageEstimationFace detection per image
import { readFile } from "node:fs/promises";

const asset = await client.assets.classify({
  name: "photo.jpg",
  content: { buffer: await readFile("./photo.jpg"), type: "image/jpeg" },
  processingOptions: {
    features: {
      personDetection: { enabled: true },
      faceDetection: { enabled: true, ageEstimation: true },
    },
  },
});

const faces = asset.classification.faceDetection;
if (faces?.status === "evaluated") {
  for (const face of faces.faces) console.log(face.box, face.ageRange);
}

Person and face detection results are returned in classification.personDetection and classification.faceDetection and never change the moderation decision.

For example, this processingOptions value turns on OCR and turns off link detection:

{
  "features": {
    "ocr": { "enabled": true },
    "linkDetection": { "enabled": false }
  }
}
  • Unknown features and unknown options are rejected, so a typo fails the request instead of being ignored.
  • Features apply to images, including images extracted from multimedia documents and websites, which inherit the parent's processing options. Other asset types ignore them.
  • Processing options are not returned on the asset: each feature's results, such as classification.ocr or classification.linkDetection, show what ran (each is null when its feature didn't run), and content.status shows whether the content was kept. Retrying the asset runs the same features again.

Replies in a conversation

For a comment, message or image posted as a reply, send authorId and context, the earlier posts of its thread, with the upload. CalmLens still moderates only the upload, and uses the earlier posts to tell who it addresses and whether it quotes, reports or counters something. See Threaded moderation.

Asset metadata

Attach custom fields to your uploads. See Asset metadata for field definitions and examples.

Folders

Pass a folderId to organise an upload. See Folders for creating, moving and managing a folder tree.

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