# Diffio API docs for coding agents > Diffio restores speech in audio and video recordings: it removes background noise, echo, reverb and distortion while keeping the voice natural. This file holds every page of the Diffio API docs as Markdown, in reading order, for coding agents. Human-readable version: https://diffio.ai/docs/ ## Read this first - Base URL `https://api.diffio.ai/v2`. Send the key as `Authorization: Bearer ` and read it from the `DIFFIO_API_KEY` environment variable. Never ship the key to a browser or mobile app. - Prefer the SDKs: `pip install diffio` (Python) or `npm install diffio` (Node.js), version 1.0 or later. Earlier versions use an older API that these docs do not describe. - Request and response fields are snake_case (`file_name`, `latest_generation`, `upload_token`), and the objects both SDKs return keep those names. - The flow is: create a project, upload the file by following `upload.requests`, create a generation with `model` `diffio-flash` or `diffio-pro`, wait for `status` `complete`, then get media URLs. Pass `generation` when you create the project to queue the restore in the same call. - Let browsers upload straight to Diffio: hand them the project's `upload` (its `upload_token` covers that one upload for 24 hours) and keep the API key on your server. - Wait with webhooks in production; poll `GET /projects/{project_id}/generations/{generation_id}` every few seconds otherwise. - Media URLs from `GET .../media` need no API key and expire after 6 hours (`expires_at`); request a new grant instead of storing them. - Building for many users? Send `Diffio-End-User: ` so each user sees only their own projects and usage. - Send an `Idempotency-Key` on project, generation and edit creates when your own code may retry them; the SDKs add one for their own retries. - Branch on `error.code`, not the HTTP status: one status can mean several things with different fixes. Every code and its retry rule is listed at https://diffio.ai/docs/api-reference/errors/. ## Other plain-text sources - OpenAPI 3.1 document: https://api.diffio.ai/v2/openapi.json (Machine-readable schema for every /v2 route, for code generators and typed clients.) - Docs MCP server: https://diffio.ai/docs/mcp (Streamable HTTP, read-only, no key: search_docs, get_page and get_api_operation.) - Docs index: https://diffio.ai/llms.txt (One line per page with its Markdown URL, so an agent can fetch only the pages it needs.) - Any single page: https://diffio.ai/docs/developers/quick-start.md (Add .md to a docs URL, or request the HTML URL with Accept: text/markdown.) --- Source: https://diffio.ai/docs/overview/introduction/ # Diffio API documentation Guides and references for restoring speech audio, reviewing transcripts and integrating Diffio. - Speech focused restoration - Audio and video - Transcripts and A/B review [Developer quickstart](https://diffio.ai/docs/developers/quick-start/) [Models](https://diffio.ai/docs/overview/models/) [API reference](https://diffio.ai/docs/api-reference/introduction/) Choosing a provider? See the [speech enhancement API comparison](https://diffio.ai/speech-enhancement-api-comparison/) (ElevenLabs, Krisp, Auphonic and others). **The finished project view in the Diffio app, drawn here; the API returns the same restored audio, video and transcript.** Coding with an agent? One URL holds every guide and endpoint as plain text. Paste it, or the prompt, into Claude Code, Codex, Cursor or any coding agent. [https://diffio.ai/docs/llms-full.txt](https://diffio.ai/docs/llms-full.txt) ## Start here 1. [Get an API key](https://diffio.ai/developers/api-keys/) and export it as `DIFFIO_API_KEY` 2. Install `pip install diffio` or `npm install diffio` 3. Restore a file in one call: [Quickstart](https://diffio.ai/docs/developers/quick-start/) ## What you can build Short recipes on the API, each one complete file in Python and Node. [All use-case guides](https://diffio.ai/docs/developers/guides/) - [Podcast cleanup in a SaaS app: Browser upload → webhook → player](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) - [Edit a transcript: Transcript → estimate → edit](https://diffio.ai/docs/developers/guides/edit-transcript/) - [Let users edit by asking: Ask → proposals → edit](https://diffio.ai/docs/developers/guides/edit-by-asking/) - [Separate speech and background: Stems → mix → export](https://diffio.ai/docs/developers/guides/separate-speech-and-background/) - [Share a restored result: Publish → public read → revoke](https://diffio.ai/docs/developers/guides/share-a-result/) - [Restore a video and stream it: Video upload → HLS stream](https://diffio.ai/docs/developers/guides/restore-video-and-stream/) - [Compare Flash and Pro: One project → two generations](https://diffio.ai/docs/developers/guides/compare-flash-and-pro/) - [Clean up a back catalogue: Folder → restores → usage](https://diffio.ai/docs/developers/guides/clean-up-a-back-catalogue/) - [Bill your users from usage: Usage per end user → invoice](https://diffio.ai/docs/developers/guides/bill-users-from-usage/) ## Models - [**Diffio 4.7 Flash**, `diffio-flash`, $5/hour](https://diffio.ai/docs/overview/models/) - [**Diffio 4.7 Pro**, `diffio-pro`, $10/hour](https://diffio.ai/docs/overview/models/) Start with Flash, then compare Pro on your file. [Compare models](https://diffio.ai/docs/overview/models/) ## How the API works A project, then one or more generations. The Python and Node SDKs run all four steps in one call; the [Diffio API overview](https://diffio.ai/api-overview/) shows the whole batch workflow. 1. **Create a project** [`POST /projects`](https://diffio.ai/docs/api-reference/create-project/) Project `id` and `upload` instructions 2. **Start a generation** [`POST /projects/{project_id}/generations`](https://diffio.ai/docs/api-reference/create-generation/) Pass `diffio-flash` or `diffio-pro`; run both to compare 3. **Follow progress** [`GET /projects/{project_id}/generations/{generation_id}`](https://diffio.ai/docs/api-reference/get-generation/) Poll until `complete`, or use a [webhook](https://diffio.ai/docs/developers/webhooks/) 4. **Download the result** [`GET /projects/{project_id}/generations/{generation_id}/media`](https://diffio.ai/docs/api-reference/get-generation-media/) `files` URLs for audio, video, HLS and transcript **All 30 endpoints by category** ### Models - [List models](https://diffio.ai/docs/api-reference/list-models/) `GET /models` ### Projects - [Create a project](https://diffio.ai/docs/api-reference/create-project/) `POST /projects` - [List projects](https://diffio.ai/docs/api-reference/list-projects/) `GET /projects` - [Get a project](https://diffio.ai/docs/api-reference/get-project/) `GET /projects/{project_id}` - [Delete a project](https://diffio.ai/docs/api-reference/delete-project/) `DELETE /projects/{project_id}` - [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/) `POST /projects/{project_id}/upload` - [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/) `POST /projects/{project_id}/upload/complete` ### Generations - [Create a generation](https://diffio.ai/docs/api-reference/create-generation/) `POST /projects/{project_id}/generations` - [List a project's generations](https://diffio.ai/docs/api-reference/list-project-generations/) `GET /projects/{project_id}/generations` - [Get a generation](https://diffio.ai/docs/api-reference/get-generation/) `GET /projects/{project_id}/generations/{generation_id}` - [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) `GET /projects/{project_id}/generations/{generation_id}/media` - [Estimate a transcript edit](https://diffio.ai/docs/api-reference/estimate-transcript-edit/) `POST /projects/{project_id}/generations/{generation_id}/edits/estimate` - [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/) `POST /projects/{project_id}/generations/{generation_id}/edits` ### Separated tracks - [Get the saved mix](https://diffio.ai/docs/api-reference/get-generation-mix/) `GET /projects/{project_id}/generations/{generation_id}/mix` - [Save the mix](https://diffio.ai/docs/api-reference/save-generation-mix/) `PUT /projects/{project_id}/generations/{generation_id}/mix` - [Create an export](https://diffio.ai/docs/api-reference/create-generation-export/) `POST /projects/{project_id}/generations/{generation_id}/exports` - [Get an export](https://diffio.ai/docs/api-reference/get-generation-export/) `GET /projects/{project_id}/generations/{generation_id}/exports/{export_id}` ### Transcripts - [Get a generation's transcript](https://diffio.ai/docs/api-reference/get-transcript/) `GET /projects/{project_id}/generations/{generation_id}/transcript` - [Get the transcript draft](https://diffio.ai/docs/api-reference/get-transcript-draft/) `GET /projects/{project_id}/generations/{generation_id}/transcript/draft` - [Save the transcript draft](https://diffio.ai/docs/api-reference/save-transcript-draft/) `PUT /projects/{project_id}/generations/{generation_id}/transcript/draft` - [Delete the transcript draft](https://diffio.ai/docs/api-reference/delete-transcript-draft/) `DELETE /projects/{project_id}/generations/{generation_id}/transcript/draft` - [Ask the edit assistant](https://diffio.ai/docs/api-reference/create-transcript-assistant-turn/) `POST /projects/{project_id}/generations/{generation_id}/transcript/assistant/turns` - [Get an edit assistant turn](https://diffio.ai/docs/api-reference/get-transcript-assistant-turn/) `GET /projects/{project_id}/generations/{generation_id}/transcript/assistant/turns/{turn_id}` - [Send assistant feedback](https://diffio.ai/docs/api-reference/create-transcript-assistant-feedback/) `POST /projects/{project_id}/generations/{generation_id}/transcript/assistant/feedback` ### Shares - [Publish a project's share](https://diffio.ai/docs/api-reference/publish-project-share/) `PUT /projects/{project_id}/share` - [Get a project's share](https://diffio.ai/docs/api-reference/get-project-share/) `GET /projects/{project_id}/share` - [Revoke a project's share](https://diffio.ai/docs/api-reference/revoke-project-share/) `DELETE /projects/{project_id}/share` - [Get a share](https://diffio.ai/docs/api-reference/get-share/) `GET /shares/{share_id}` ### Usage - [Get usage](https://diffio.ai/docs/api-reference/usage-summary/) `GET /usage` ### Webhooks - [Open the webhook portal](https://diffio.ai/docs/api-reference/open-webhook-portal/) `POST /webhooks/portal` --- Source: https://diffio.ai/docs/overview/models/ # Models: Diffio 4.7 Flash vs Pro Diffio offers 2 speech restoration models: Diffio 4.7 Flash and Diffio 4.7 Pro. Pick one per generation, and run both on the same project to compare. ## Model lineup Pass the model id in `model` on [create a generation](https://diffio.ai/docs/api-reference/create-generation/) or in `generation.model` on [create a project](https://diffio.ai/docs/api-reference/create-project/). Tier aliases `diffio-flash` and `diffio-pro` always point to the current hosted model of each tier ([list models](https://diffio.ai/docs/api-reference/list-models/)). ### Diffio 4.7 Flash Fast, high quality speech restoration for everyday work. About 30× faster than real time Web app plans Every plan, including Free (the Free default) Best for Everyday restoration and quick turnaround. Model id `diffio-4.7-flash` ### Diffio 4.7 Pro More model work per step; worth comparing with Flash on difficult recordings. About 10× faster than real time Web app plans Paid plans, starting with Basic (the paid default) Best for Difficult recordings you want to hear beside Flash. Model id `diffio-4.7-pro` ## Choosing a model Start with `diffio-4.7-flash`, then try `diffio-4.7-pro` on recordings where you want a second take. Keep the same project and run a new restoration each time you change models. **Hear both models on one clip** **An archival lecture, used with permission. Source & method** The first 60 seconds of an archival David Gooding lecture, used with the owner’s permission. The Flash and Pro versions were rendered on November 3, 2026 from the released Diffio 4.7 weights on Diffio’s own GPU, with the same processing as the app around the model, not through the public API. All three play at matched loudness as 160 kbps MP3, with no other enhancement. [Source and render record](https://diffio.ai/media/recording-rescue/manifest.json). ## What both models share - **Same outputs** Restored audio, comparison playback, MP3, video and transcript - **Billed per second** API usage of either model; [rates](https://diffio.ai/api-pricing/) - **Best in English** Other languages may work, with varying quality **Outputs and languages in detail** Both return restored audio, original and restored comparison playback that starts while restoration runs, MP3 downloads, restored video for video projects, and transcript data. API usage of either model is billed per second; [API pricing](https://diffio.ai/api-pricing/) lists the rates. Diffio 4.7 works best in English; other languages may work, with varying quality. Transcription failure is reported instead of silently proceeding without text guidance. ## Retired models 1. Tier alias (`diffio-flash`, `diffio-pro`) Runs `diffio-4.7-flash` or `diffio-4.7-pro`, `substituted: false` 2. Retired model id Runs current tier model, `substituted: true` 3. Unrecognized model name `HTTP 400` `unknown_model` **Retired model behavior in detail** - **Substitution** Retired model ids (`diffio-2`, `diffio-2-flash`, `diffio-2.0`, `diffio-2.0-flash`, `diffio-3.0`, `diffio-3.2`, `diffio-3.4`, `diffio-3.5`, `diffio-4.0`, `diffio-4.0-flash`, `diffio-4.0-pro`, `diffio-4.5-flash`, `diffio-4.5-pro`, `diffio-4.6-flash`, `diffio-4.6-pro`) are accepted, not refused. They run on the current hosted model of the same tier (`served_by` in [list models](https://diffio.ai/docs/api-reference/list-models/)), with `model` set to the hosted model that ran, `requested_model` set to the requested id, and `substituted` set to `true`. - **Billing** A substituted generation is billed at the lower of the retired model's last list price and the serving model's price (or the serving model's price when the retired model had no last list price). - **Unknown names** Model names are matched case-insensitively after trimming whitespace. Any unrecognized name returns HTTP `400` with code `unknown_model` and `details.models` listing the current hosted and tier alias ids. ## Next steps [Quickstart Restore speech audio in a single request.](https://diffio.ai/docs/developers/quick-start/) [Full API guide Projects, results and downloads end to end.](https://diffio.ai/docs/developers/full-api-guide/) [API reference Endpoints, headers and error responses.](https://diffio.ai/docs/api-reference/introduction/) [API model cards Each model's card, side by side.](https://diffio.ai/api-model-cards/) [API pricing Per-second rates for each model.](https://diffio.ai/api-pricing/) [Plan access and billing Starter credit, charges and invoices.](https://diffio.ai/docs/overview/administration/billing/) --- Source: https://diffio.ai/docs/overview/concepts/projects-and-uploads/ # Projects and uploads A project is one recording: create it, upload the file to Diffio's media host with its `upload_token`, then run generations on it. The upload goes in parts of `part_size_bytes`; the project checks the file and becomes `ready`. ## How it works 1. `awaiting_upload`: created; `upload` holds the token and requests 2. `preparing`: the file arrived and is being checked 3. `ready`: generations run; `project.ready` webhook - from `preparing`: `failed`, the file could not be read; `project.failed` webhook **Project `status`. A generation requested with the project waits in `queued` until `ready`.** Webhooks `project.ready`, `project.failed` ([Webhooks](https://diffio.ai/docs/developers/webhooks/)) ## Limits | Limit | Value | | --- | --- | | File size | up to 2 GB (2,147,483,648 bytes); larger is `413 upload_too_large` | | Media length | no limit | | Part size | 32 MiB (`33554432` bytes); every part but the last | | Upload token | 24 hours (`upload.expires_at`); `POST …/upload` gives a new one | | Ready without `upload/complete` | about 30 seconds after the media host has the file | | `upload/complete` check | up to 180 seconds inside the request | | metadata | 50 keys; keys up to 40 characters, values up to 500 | | Idempotency-Key | up to 255 characters, per account and end user | | List page | `limit` 1 to 100, default 20, newest first | ## Build with it - Guide [Podcast cleanup in a SaaS app](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) - [`POST /projects`](https://diffio.ai/docs/api-reference/create-project/) - [`POST /projects/{project_id}/upload`](https://diffio.ai/docs/api-reference/reopen-project-upload/) - [`POST /projects/{project_id}/upload/complete`](https://diffio.ai/docs/api-reference/complete-project-upload/) - [`GET /projects/{project_id}`](https://diffio.ai/docs/api-reference/get-project/) - [`GET /projects`](https://diffio.ai/docs/api-reference/list-projects/) - [`DELETE /projects/{project_id}`](https://diffio.ai/docs/api-reference/delete-project/) ## Related pages - Previous: [End users](https://diffio.ai/docs/overview/concepts/end-users/): Send Diffio-End-User with each request to keep every customer's projects, usage and events apart under one API key. - Next: [Generations](https://diffio.ai/docs/overview/concepts/generations/): A generation is one restore of a project with one model; follow its status and stage, then read its media. --- Source: https://diffio.ai/docs/overview/concepts/generations/ # Generations: status, stages and results A generation is one restore of a project's recording with one model (`diffio-flash` or `diffio-pro`); a project can have many. It reports `status` and, while it runs, `stage`, `stage_progress` and `queue`. When `complete`, `GET …/media` hands out its files. ## How it works 1. `queued`: waits for the project to be `ready` (`stage: "pending"`) 2. `processing`: `stage`: preparing, transcribing, queued, starting, downloading, decoding, restoring, finalizing, uploading 3. `complete`: media, transcript and separated tracks; `generation.completed` - from `processing`: `failed`, `error.code`; `generation.failed` **Generation `status`. `transcription_status` and `stems_status` can still be `preparing` just after `complete`.** Webhooks `generation.completed`, `generation.failed` ([Webhooks](https://diffio.ai/docs/developers/webhooks/)) ## Limits | Limit | Value | | --- | --- | | Billing | whole seconds, 60 second minimum per restore | | Media URLs | 6 hours (`expires_at`); ask again for new ones | | `preview_seconds` | 4 to 3600, rounded up to whole 4 second segments | | label | up to 120 characters | | SDK `wait` | polls every 2 seconds, gives up after 3600 seconds by default | | List page | `limit` 1 to 100, default 20, newest first | ## Build with it - Guide [Quickstart](https://diffio.ai/docs/developers/quick-start/) - Guide [Podcast cleanup in a SaaS app](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) - [`POST /projects/{project_id}/generations`](https://diffio.ai/docs/api-reference/create-generation/) - [`GET /projects/{project_id}/generations/{generation_id}`](https://diffio.ai/docs/api-reference/get-generation/) - [`GET /projects/{project_id}/generations`](https://diffio.ai/docs/api-reference/list-project-generations/) - [`GET /projects/{project_id}/generations/{generation_id}/media`](https://diffio.ai/docs/api-reference/get-generation-media/) - [`GET /models`](https://diffio.ai/docs/api-reference/list-models/) ## Related pages - Previous: [Projects and uploads](https://diffio.ai/docs/overview/concepts/projects-and-uploads/): A project holds one uploaded recording; its status moves from awaiting_upload to ready as the file arrives. - Next: [Transcripts and edits](https://diffio.ai/docs/overview/concepts/transcripts-and-edits/): Every generation has a word-timed transcript; change its words on a Pro result and Diffio restores the changed parts again. --- Source: https://diffio.ai/docs/overview/concepts/transcripts-and-edits/ # Transcripts and edits A generation's transcript is its words in order, each with an `id`, `text`, `start` and `end`. On a finished `diffio-pro` result, send the words back with changes: only the windows around them are restored, as a new generation of `kind` `edit`. ## How it works 1. `transcript ready`: `transcription_status: "ready"` on a complete Pro generation 2. `estimate`: `POST …/edits/estimate`: the most it can bill; creates nothing 3. `edit`: `POST …/edits`: a new generation, `kind: "edit"` 4. `complete`: the whole recording with the changes; its own transcript - from `transcript ready`: `not editable`, not Pro, or the transcript failed: `409` **From a transcript to an edited recording.** ## Limits | Limit | Value | | --- | --- | | Who can edit | finished `diffio-pro` results (`transcript_editable: true`) | | Edit billing | 30 seconds per restored window, no minimum; an edit that only cuts bills nothing | | `request_id` | up to 64 characters, `A-Z a-z 0-9 _ -` | | `tighten` | audio projects only | | Edit assistant | up to 30 turns per 10 minutes, plus a daily cap | | Drafts | one per generation; a stale `revision` is `409 revision_conflict` | ## Build with it - Guide [Edit a transcript](https://diffio.ai/docs/developers/guides/edit-transcript/) - Guide [Let users edit by asking](https://diffio.ai/docs/developers/guides/edit-by-asking/) - [`GET /projects/{project_id}/generations/{generation_id}/transcript`](https://diffio.ai/docs/api-reference/get-transcript/) - [`POST /projects/{project_id}/generations/{generation_id}/edits/estimate`](https://diffio.ai/docs/api-reference/estimate-transcript-edit/) - [`POST /projects/{project_id}/generations/{generation_id}/edits`](https://diffio.ai/docs/api-reference/create-transcript-edit/) - [`GET /projects/{project_id}/generations/{generation_id}/transcript/draft`](https://diffio.ai/docs/api-reference/get-transcript-draft/) - [`POST /projects/{project_id}/generations/{generation_id}/transcript/assistant/turns`](https://diffio.ai/docs/api-reference/create-transcript-assistant-turn/) ## Related pages - Previous: [Generations](https://diffio.ai/docs/overview/concepts/generations/): A generation is one restore of a project with one model; follow its status and stage, then read its media. - Next: [Separated tracks](https://diffio.ai/docs/overview/concepts/separated-tracks/): Each restore separates speech from background; save a balance of the two and render it as a downloadable export. --- Source: https://diffio.ai/docs/overview/concepts/separated-tracks/ # Separated tracks: mix and exports A restore keeps the speech and the background as two separated tracks (`stems_status`). A mix is a saved balance of the two (`background_gain`); an export renders speech, background, a mix or both as a file. ## How it works 1. `stems ready`: `stems_status: "ready"`; `generation.stems_ready` 2. `mix saved`: `PUT …/mix` with `background_gain` and the `revision` you read 3. `export queued`: `POST …/exports`; the same recipe returns the same export 4. `export ready`: `url` to download; `export.ready` - from `stems ready`: `stems failed`, `generation.stems_failed`; mix and exports answer `409 not_available` - from `export queued`: `export failed`, `export.failed`; asking again renders it again **From separated tracks to a file.** Webhooks `generation.stems_ready`, `generation.stems_failed`, `export.ready`, `export.failed` ([Webhooks](https://diffio.ai/docs/developers/webhooks/)) ## Limits | Limit | Value | | --- | --- | | `background_gain` | 0 (speech only) to 1 (all of the background) | | speech, background, mix | `wav`, `mp3`, `m4a` or `mp4` | | both | `zip` of the two tracks | | original | inline only, `mp3` or `mp4` | | Inline exports | `mp3` or `mp4`, to play in a page | | Exports rendering | 4 per generation at once; more is `409 too_many_exports` | | `file_name` | up to 200 characters, without the extension | ## Build with it - Guide [Separate speech and background](https://diffio.ai/docs/developers/guides/separate-speech-and-background/) - [`GET /projects/{project_id}/generations/{generation_id}/mix`](https://diffio.ai/docs/api-reference/get-generation-mix/) - [`PUT /projects/{project_id}/generations/{generation_id}/mix`](https://diffio.ai/docs/api-reference/save-generation-mix/) - [`POST /projects/{project_id}/generations/{generation_id}/exports`](https://diffio.ai/docs/api-reference/create-generation-export/) - [`GET /projects/{project_id}/generations/{generation_id}/exports/{export_id}`](https://diffio.ai/docs/api-reference/get-generation-export/) ## Related pages - Previous: [Transcripts and edits](https://diffio.ai/docs/overview/concepts/transcripts-and-edits/): Every generation has a word-timed transcript; change its words on a Pro result and Diffio restores the changed parts again. - Next: [Shares](https://diffio.ai/docs/overview/concepts/shares/): A share is a revocable public link to one project's result that anyone with its id can play without an API key. --- Source: https://diffio.ai/docs/overview/concepts/shares/ # Shares: public links to a result A share gives a project a public `id`; `GET /shares/{share_id}` answers anyone holding it, with no API key. It plays one finished generation (the newest, or one you pin) and never the uploaded original. Revoke it to turn it off. ## How it works 1. `not shared`: a new project 2. `published`: `PUT …/share`; the `id` stays the same when you publish again 3. `revoked`: `DELETE …/share`; the id answers `404 share_not_found` - from `published`: `new version`, a changed `generation_id` or `preview_seconds`: earlier URLs stop **A project's share. Deleting the project revokes it too.** ## Limits | Limit | Value | | --- | --- | | Share id | 17 characters | | `preview_seconds` | 4 to 3600, rounded up to whole 4 second segments | | Old URLs after a revoke or change | stop within about a minute | | API key | not needed for `GET /shares/{share_id}`; any origin may call it | | Files | the shared generation's playback files; never `original` | ## Build with it - Guide [Share a restored result](https://diffio.ai/docs/developers/guides/share-a-result/) - [`PUT /projects/{project_id}/share`](https://diffio.ai/docs/api-reference/publish-project-share/) - [`GET /projects/{project_id}/share`](https://diffio.ai/docs/api-reference/get-project-share/) - [`DELETE /projects/{project_id}/share`](https://diffio.ai/docs/api-reference/revoke-project-share/) - [`GET /shares/{share_id}`](https://diffio.ai/docs/api-reference/get-share/) ## Related pages - Previous: [Separated tracks](https://diffio.ai/docs/overview/concepts/separated-tracks/): Each restore separates speech from background; save a balance of the two and render it as a downloadable export. - Next: [End users](https://diffio.ai/docs/overview/concepts/end-users/): Send Diffio-End-User with each request to keep every customer's projects, usage and events apart under one API key. --- Source: https://diffio.ai/docs/overview/concepts/end-users/ # End users: one key, many customers An end user is one of your customers, named by the `Diffio-End-User` header your server sends; Diffio keeps their projects apart. A request with the header reaches only that end user's projects; one without it acts for the whole account. ## How it works 1. Your server → Diffio API: `POST /projects`, Diffio-End-User: customer-42 2. Diffio API → Your server: `project`, end_user: "customer-42" 3. Your server → Diffio API: `GET /projects/{id}`, Diffio-End-User: customer-7 4. Diffio API → Your server: `404 project_not_found`, another customer's project 5. Your server → Diffio API: `GET /usage`, Diffio-End-User: customer-42 6. Diffio API → Your server: `usage`, that customer's generations only 7. Diffio API → Your server: `webhook`, data.end_user on every event **One API key, two customers. Without the header, a request sees every project on the account.** ## Limits | Limit | Value | | --- | --- | | `Diffio-End-User` | up to 128 characters; longer is `400 invalid_header` | | `end_user` in a body | refused (`400 invalid_field`); send the header | | `POST /webhooks/portal` | account-wide; the header is refused (`403 permission_denied`) | | Idempotency-Key on `POST /projects` | scoped to the account and the end user | ## Build with it - Guide [Podcast cleanup in a SaaS app](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) - Guide [Bill your users from usage](https://diffio.ai/docs/developers/guides/bill-users-from-usage/) - [`POST /projects`](https://diffio.ai/docs/api-reference/create-project/) - [`GET /projects`](https://diffio.ai/docs/api-reference/list-projects/) - [`GET /usage`](https://diffio.ai/docs/api-reference/usage-summary/) - [`POST /webhooks/portal`](https://diffio.ai/docs/api-reference/open-webhook-portal/) ## Related pages - Previous: [Shares](https://diffio.ai/docs/overview/concepts/shares/): A share is a revocable public link to one project's result that anyone with its id can play without an API key. - Next: [Projects and uploads](https://diffio.ai/docs/overview/concepts/projects-and-uploads/): A project holds one uploaded recording; its status moves from awaiting_upload to ready as the file arrives. --- Source: https://diffio.ai/docs/overview/capabilities/audio-restoration/ # Audio restoration API: what Diffio fixes Diffio restores speech recordings that are hard to hear because of background noise, echo, reverb, distortion, low bandwidth capture, or low sample rate audio. ## Hear restored speech Hear restored speech Real noisy recordings, restored November 3, 2026 with Diffio 4.7 at matched loudness. **Downtown Denver at night** Press play, then switch between Original, 4.7 Flash and 4.7 Pro. Your place stays the same. **Read what's said** “Right now I'm just walking down Market, just past 33rd. We're on our way to the jazz club to see a couple guys perform tonight. It's pretty chilly again, like yesterday, but not as bad. Snow's lit up by all the neons down here, down on this street. Traffic's pretty low so far.” Source: A student narrating a walk down a city street for the Kerouac's America project. Recording by kerouacsamerica on Freesound, CC BY 3.0. **Source & method** Restored November 3, 2026 with Diffio 4.7 Flash and Diffio 4.7 Pro; the Flash version is the same excerpt from our [speech enhancer test](https://diffio.ai/speech-enhancer-benchmark/). Every version plays at matched loudness. [Source and license](https://diffio.ai/remove-background-noise/#sample-sources). Hear more: [A full before-and-after example](https://diffio.ai/recording-rescue/) [Restoring old speech recordings](https://diffio.ai/restore-old-recordings/) [How Diffio works](https://diffio.ai/how-it-works/) ## Restoration scope - Restored audio for playback, and downloads on plans that include them - Original and restored comparison with waveforms; the upload stays in the project - Transcript and restoration metadata Spoken audio it suits - [Interviews](https://diffio.ai/interview-audio-cleanup/) - [Lectures](https://diffio.ai/lecture-audio-enhancer/) - [Podcasts](https://diffio.ai/podcast-audio-enhancer/) - [Video soundtracks](https://diffio.ai/remove-background-noise-from-video/) ## Problems it fixes - [Background noise](https://diffio.ai/remove-background-noise/): traffic, wind, crowds, hum, hiss - [Echo and reverb](https://diffio.ai/remove-echo-from-audio/): far microphones, hard empty rooms - [Distortion and clipping](https://diffio.ai/fix-distorted-audio/): too loud, peaks cut off - [Poor microphones and low bandwidth](https://diffio.ai/fix-bad-mic-audio/): calls, laptop mics, low sample rates ## Inputs and limits Audio formats MP3 · WAV · M4A · AAC · FLAC · OGG File size Up to 2 GB Length No length limit in the API Metering Per second, 60 s minimum **Limits in detail** | Audio formats | MP3, WAV, M4A, AAC, FLAC and OGG. Video uploads are covered in [video support](https://diffio.ai/docs/overview/capabilities/video-support/). | | --- | --- | | File size | Up to 2 GB (2,147,483,648 bytes) per file. Larger files are refused by [create a project](https://diffio.ai/docs/api-reference/create-project/) or [complete upload](https://diffio.ai/docs/api-reference/complete-project-upload/) with `413` and code `upload_too_large`. | | Length | The API enforces no media duration limit. | | Metering | API usage is metered on the source duration of each generation, rounded up to the next whole second, with a 60 second minimum. See [billing](https://diffio.ai/docs/overview/administration/billing/). | ## Model fit - [Diffio 4.7 Flash](https://diffio.ai/docs/api-reference/create-generation/) About 30× real time · every plan · high volume work - [Diffio 4.7 Pro](https://diffio.ai/docs/api-reference/create-generation/) About 10× real time · paid plans · difficult recordings **Which model to choose** - **Diffio 4.7 Flash**: (`diffio-4.7-flash` or `diffio-flash`): fast, high quality speech restoration and high volume work where turnaround time matters. - **Diffio 4.7 Pro**: (`diffio-4.7-pro` or `diffio-pro`): more model work at every restoration step, so it runs slower than Flash. In Diffio's 59-clip test its scores were within Flash's confidence interval, so compare both on difficult recordings. Run both on the same project to compare them; each generation is billed separately. The [models page](https://diffio.ai/docs/overview/models/) compares them in detail. ## API example: start a restoration After the upload is ready (see the [quickstart](https://diffio.ai/docs/developers/quick-start/)), one request starts a Flash restoration; pass `diffio-pro` or `diffio-4.7-pro` for Pro. 1. Request `POST /v2/projects/{project_id}/generations` `model · Idempotency-Key` 2. Response `status: "processing"` `id · project_id · model` The `Idempotency-Key` header makes a retried request return HTTP `201` with the same generation `id` instead of starting a second one. **Full request and response** **Python** ```python from diffio import DiffioClient client = DiffioClient() generation = client.generations.create( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", model="diffio-flash", label="Take 1", idempotency_key="take-1-flash", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio"; const client = new DiffioClient(); const generation = await client.generations.create( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", { model: "diffio-flash", label: "Take 1" }, { idempotencyKey: "take-1-flash" }, ); ``` **cURL** ```bash curl -X POST "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/generations" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Idempotency-Key: v2docs-g-mwe8tm1g" \ -H "Content-Type: application/json" \ -d '{ "model": "diffio-flash", "label": "Take 1" }' ``` **Response** ```json { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "status": "processing", "stage": "preparing", "stage_progress": null, "queue": null, "warnings": [], "label": "Take 1", "kind": "restore", "source_generation_id": null, "edit": null, "transcript_editable": false, "duration_seconds": null, "quality_score": null, "transcription_status": null, "files_available": [], "error": null, "model": "diffio-4.7-flash", "requested_model": "diffio-flash", "substituted": false, "price_per_hour_usd": 5, "stems_status": null, "created_at": "2026-11-13T00:33:27.117344Z", "updated_at": "2026-11-13T00:33:27.999000Z" } ``` ## Review outputs [![Completed Diffio project: the project title, the restored waveform, the play control, the Restored toggle and the Background amount slider](https://diffio.ai/media/recording-rescue/flash-result-mobile-stack.jpg) Play, switch Original and Restored, set the background](https://diffio.ai/media/recording-rescue/flash-result.jpg) [![Diffio download dialog: Restored speech or Background noise, the file format menu and the Download restored speech button](https://diffio.ai/media/app-captures/download-dialog-choice-crop.jpg) Download restored speech or the background](https://diffio.ai/media/app-captures/download-dialog-choice-crop.jpg) **A finished project in the Diffio app. Select a screenshot to open it full size.** 1. [Poll generation](https://diffio.ai/docs/api-reference/get-generation/) until `complete` 2. [Get playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) `files.audio`, valid 6 hours 3. [Get transcript](https://diffio.ai/docs/api-reference/get-transcript/) word-timed JSON **Project pages and API results in detail** Project pages let you compare original and restored playback, seek through the waveform, view transcript data when available, and reopen prior results from project history. Through the API, poll [get a generation](https://diffio.ai/docs/api-reference/get-generation/) until `status` is `complete`, then request URLs from [get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) and download `files.audio`. Media URLs need no `Authorization` header and remain valid for 6 hours (`expires_at`). Once `transcription_status` is `ready` on the generation, call [get a generation's transcript](https://diffio.ai/docs/api-reference/get-transcript/) for normalized word-timed JSON, or fetch raw `files.transcript` from the playback grant. ## Audio restoration questions ### Which audio files can I upload? MP3, WAV, M4A, AAC, FLAC and OGG files, up to 2 GB each, with no length limit through the API. Video files are covered in [video support](https://diffio.ai/docs/overview/capabilities/video-support/). ### Does Diffio restore music? No. Diffio restores speech. Music and other non-speech sound are not restored; separated tracks keep background sound on its own track. Both models are best in English. ### Should I use Diffio 4.7 Flash or Pro? Start with Flash (`diffio-4.7-flash` or `diffio-flash`) for fast, high quality restoration. Pro (`diffio-4.7-pro` or `diffio-pro`) does more model work at every step and runs slower; on a difficult recording, run both on the same project and compare. Each generation is billed separately. ### Does a restoration include a transcript? Yes. Once `transcription_status` is `ready` on the generation, read the normalized word-timed JSON from [get transcript](https://diffio.ai/docs/api-reference/get-transcript/), or fetch the raw `files.transcript` URL from [get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/). ### How long do download URLs last? Six hours (until `expires_at`). Each media URL from [get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) needs no Authorization header; request a new grant after it expires. --- Source: https://diffio.ai/docs/overview/capabilities/video-support/ # Video support: restore audio in MP4, MOV, WebM and more Diffio restores the soundtrack of a video and returns an MP4 with the original picture and the restored audio. ## Watch a restored soundtrack Watch a restored soundtrack Real noisy videos, restored November 3, 2026 with Diffio 4.7. Switch soundtracks while the picture plays. **Fish hatchery, Colorado** Press play, then switch between Original, 4.7 Flash and 4.7 Pro. The picture and your place stay the same. **Read what's said** “As the filter panels clog up in the center of the filter panel, the water rises up. As the filter clogs, eventually it kicks on a float switch to where then it rotates the drum while spraying off the panels.” Source: A staff member explaining the filtration building at Leadville National Fish Hatchery, July 2010. Video by Stephanie Raine, USFWS, public domain. **Source & method** Restored November 3, 2026 with Diffio 4.7 Flash and Diffio 4.7 Pro; the Flash soundtrack is the same excerpt from our [speech enhancer test](https://diffio.ai/speech-enhancer-benchmark/). Every version plays at matched loudness. [Source and license](https://diffio.ai/remove-background-noise-from-video/#sample-sources). More footage, and how it works for [removing background noise from video](https://diffio.ai/remove-background-noise-from-video/) and [fixing Zoom recordings](https://diffio.ai/fix-zoom-audio/). ## Video workflow 1. **Upload a video** MP4, MOV, WebM and more, with an audio track 2. **Restore the soundtrack**: the picture is left untouched 3. **Download the MP4**: original picture, restored audio > **Each step in detail** > > - Upload a supported video container with an audio track. Diffio detects video inputs from metadata and file type, then prepares the audio for restoration. > - Diffio restores the audio track and creates preview assets so the result can be reviewed in the project workspace. > - Paid plans can download a video output with restored audio when the restored video artifact is ready. The download is an MP4 file with the original picture. ## Supported containers and limits - MP4 - MOV - WebM - AVI - MKV - 3GP - 3G2 File size Up to 2 GB Length No length limit in the API Metering Source duration, 60 s minimum Diffio restores audio from video uploads. It does not upscale, denoise, color grade, or repair video frames. **Extensions, media types and limits in detail** The app and the API support MP4, MOV, WebM, AVI, MKV, 3GP and 3G2 video containers when they include an audio track and are detected as video. | Container | File extensions | Media type | | --- | --- | --- | | MP4 | `.mp4` | `video/mp4` | | MOV | `.mov` | `video/quicktime` | | WebM | `.webm` | `video/webm` | | AVI | `.avi` | `video/x-msvideo` | | MKV | `.mkv` | `video/x-matroska` | | 3GP | `.3gp` `.3gpp` | `video/3gpp` | | 3G2 | `.3g2` | `video/3gpp2` | - File size: up to 2 GB (2,147,483,648 bytes) per file, the same limit as audio uploads. - Length: the API enforces no duration limit on video uploads. - API usage is metered on the source video's duration, rounded up to whole seconds, with a 60 second minimum per generation. ## API downloads For a completed video project, [get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) returns signed URLs in `files`, and [get transcript](https://diffio.ai/docs/api-reference/get-transcript/) returns the normalized word-timed transcript: Video project - `files.video` MP4 with the original picture and restored audio - `files.audio` The restored MP3 soundtrack on its own - `transcript` Word-timed JSON from `GET .../transcript` (or raw `files.transcript`) - URLs in `files` need no `Authorization` header and expire after 6 hours (`expires_at`); append `?download=interview.mp4` to set a file name - `GET .../media` returns `200` even while `status` is `processing`, naming only files that exist so far; poll [get a generation](https://diffio.ai/docs/api-reference/get-generation/) until `complete` first > **Readiness and playback rules** > > - Poll [get a generation](https://diffio.ai/docs/api-reference/get-generation/) until overall `status` is `complete` before downloading `files.video`. > - Audio-only projects (`has_video: false`) never include `files.video` or `files.video_hls`. > - For adaptive streaming, `files.hls_master` carries the picture (`files.video_hls`) with the restored and original audio once `video_preview_status` on the project is `ready`. > - Preview grants (`?preview_seconds=N`) omit full downloads including `video`, `audio`, `audio_mixed` and `transcript`. 1. Request `GET /v2/projects/{project_id}/generations/{generation_id}/media` `Authorization: Bearer` 2. Response `files.video · files.audio` `status: "complete" · expires_at` **Download the restored MP4 in Python, Node.js or cURL** **Python** ```python from diffio import DiffioClient client = DiffioClient() path = client.generations.download( project_id, generation_id, file="video", path="interview-restored.mp4", ) print(path) ``` **Node.js** ```javascript import { DiffioClient } from "diffio"; const client = new DiffioClient(); const file = await client.generations.download(project.id, generation.id, { file: "video", path: "interview-restored.mp4", }); console.log(file.path, file.size_bytes); ``` **cURL** ```bash VIDEO_URL=$(curl -sS "https://api.diffio.ai/v2/projects/$PROJECT_ID/generations/$GEN_ID/media" \ -H "Authorization: Bearer $DIFFIO_API_KEY" | jq -r .files.video) curl -sS -o interview-restored.mp4 "$VIDEO_URL" ``` ## Video support questions ### Does Diffio change the picture? No. Diffio restores the soundtrack and attaches it to the original picture. It does not upscale, denoise, color grade or repair video frames. ### Can I download only the restored audio from a video project? Yes. Call [get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) and fetch `files.audio` for the restored MP3 soundtrack, `files.video` for the MP4 with the original picture, or call [get transcript](https://diffio.ai/docs/api-reference/get-transcript/) for the word-timed transcript. ### How is a video generation billed through the API? Like audio: on the source video's duration, rounded up to the next whole second, with a 60 second minimum per generation. [Billing](https://diffio.ai/docs/overview/administration/billing/) has the details and [API pricing](https://diffio.ai/api-pricing/) the current rates. ### Which video files can I upload? MP4, MOV, WebM, AVI, MKV, 3GP and 3G2 files with an audio track, up to 2 GB each, with no length limit through the API. A video without an audio track has nothing to restore. --- Source: https://diffio.ai/docs/overview/administration/billing/ # API billing: credits, charges and invoices Every API account starts with a one time $5 credit. After that you add credit, $5 to $100 at a time, and usage is paid from it. Credit does not expire. 1. $5 Starter credit no payment method needed 2. $25 Add credit $5 to $100 at a time 3. $15 Usage deducted per second 4. $10 Credit left does not expire **Add $25 after the starter credit and use $15 of it: $10 of credit is left. At $0 the API returns 402 until you add credit.** ## Starter credit and adding credit | Media length | Billed | Rule | | --- | --- | --- | | 30 s | **60 s** | 60 second minimum | | 80 s | **80 s** | whole seconds | | 80.2 s | **81 s** | rounded up | ### How does API billing start? Every API account starts with a one time $5 usage credit, so you can create a key and run generations without a payment method. Usage is based on the source audio or video duration for each result, rounded up to the next whole second, with a minimum billable duration of 60 seconds per result. Example: restoring 30 seconds of media bills 60 seconds. From 80 seconds, it bills 80 seconds; from 80.2 seconds, it bills 81 seconds. Each additional result from the same media is metered separately. The model rate is applied to the billable seconds. See the [API pricing page](https://diffio.ai/api-pricing/) for current model rates. ### What happens when my $5 credit runs out? When your credit is used up, new API generations return HTTP 402 with the code `insufficient_credit` until you add credit. A generation is also refused when your remaining credit cannot cover it. Add credit on the [Billing page](https://diffio.ai/developers/billing/), $5 to $100 at a time. Checkout accepts credit and debit cards and shows any other payment method available in your country. API access resumes as soon as the payment completes. ### What are the benefits of the Developer tier? The Developer tier is prepaid, usage based pricing for developers and teams. - A $5 starter credit - Credit that does not expire - Optional automatic top-up - Audit logs with 7 day retention ### How do I downgrade or cancel? App and API billing are separate. For your app subscription, open [Profile](https://diffio.ai/profile/) and select **Manage app billing**. Review the available changes and their effective dates in the billing portal before confirming. API credit has no subscription to cancel: you pay only for the credit you add. To stop automatic top-up, turn it off on the [Billing page](https://diffio.ai/developers/billing/). ## Understanding the Diffio billing model ### How does the billing cycle work? There is no billing cycle. Each generation is deducted from your credit when it is billed, and you add credit when you need it, $5 to $100 per purchase. Credit does not expire. Example - You add $25 of credit. - You use $15 of it. - $10 of credit is left for later. ### When is payment withdrawn from my account? Only when you add credit, or when automatic top-up adds it for you. Automatic top-up is off until you turn it on. When it is on and your balance falls below your threshold ($25 unless you change it), your saved payment method is charged your top-up amount ($25 unless you change it, $5 to $100). ## Invoices, billing info, and credits - [Usage](https://diffio.ai/developers/usage/) credit left and recent usage - [API billing](https://diffio.ai/developers/billing/) add credit, automatic top-up, receipts - [Profile](https://diffio.ai/profile/) app subscription billing ### How can I view my current usage and spending in near real time? Open the [Usage page](https://diffio.ai/developers/usage/) to see your remaining credit and your recent usage, one line per generation. ### Where can I find my past invoices and payment history? Receipts for credit purchases and automatic top-ups are in the billing portal: open the [Billing page](https://diffio.ai/developers/billing/) and select **Invoices and receipts**. The Billing page also lists your recent credit activity. For app subscription billing, open [Profile](https://diffio.ai/profile/) and select **Manage app billing**. ### Can I change my billing info and payment method? For API billing, open [Billing](https://diffio.ai/developers/billing/) and select **Invoices and receipts**: the billing portal is where you update or remove the payment method saved for automatic top-up. For app subscription billing, select **Manage app billing** on [Profile](https://diffio.ai/profile/). ### What payment methods do you accept? Checkout accepts credit and debit cards (Visa, MasterCard, American Express, Discover) and shows any other payment method available in your country. ### Who charges my card, and is tax added? API credit and new app subscriptions are sold through Link, Stripe's merchant of record. Link appears with Diffio AI on your card statement and emails your receipts and invoices. Where your location requires sales tax, VAT, or GST, Link adds it at checkout, on top of the credit or the listed price. Subscriptions and API payment methods set up before November 10, 2026 are billed by Diffio AI directly, as before. ### Are there promotional credits or trial offers? Every new API account receives a one time $5 usage credit. No payment method is needed to use it. ## Common billing questions and troubleshooting ### What do the 402 billing errors mean? 1. 402 `insufficient_credit` Your credit is used up, or cannot cover the file. Add credit on the [Billing page](https://diffio.ai/developers/billing/); access resumes as soon as the payment completes. ### Accounts with card billing: three other 402 codes 1. 402 `needs_payment_method` The credit is used up, or cannot cover the file, and no payment method is saved. Add a payment method on the [Billing page](https://diffio.ai/developers/billing/); access resumes once it is saved. 2. 402 `payment_failed` A charge failed. Open the billing portal from the [Billing page](https://diffio.ai/developers/billing/), select **Update payment method** under Current subscription and choose a card: the open invoice is paid and access resumes. Adding a card under Payment methods alone does not change the card that is charged. 3. 402 `usage_limit_reached` $100 of usage is waiting to be billed. Nothing to do: it is charged to your payment method within minutes, and the API continues once that payment completes. ### How are refunds handled? Fees are non-refundable except where the law requires otherwise or where we agree in writing (section 7.4 of the [terms of service](https://diffio.ai/terms/#fees-billing-and-refunds)). If something went wrong with a generation or a charge, contact [support@diffio.ai](mailto:support@diffio.ai). ### What if I believe there is an error in my bill? Check your Usage and Billing pages first. If you still believe there is an issue, contact support at [support@diffio.ai](mailto:support@diffio.ai). ### What happens if my payment fails? A credit purchase that fails at checkout adds no credit. If an automatic top-up payment fails, automatic top-up stops and the [Billing page](https://diffio.ai/developers/billing/) says why; the credit you have left keeps working. Update the payment method in the billing portal, then turn automatic top-up back on. ### How is an account with card billing charged? Accounts that added a card before prepaid credit keep card billing until it is cancelled. After the starter credit, the saved payment method is charged each time unpaid usage reaches $10, and usage below $10 is invoiced at the end of the billing month. API invoices and receipts, including the charges made each time your usage reached $10, are in the billing portal: open the [Billing page](https://diffio.ai/developers/billing/) and select **Manage billing**. Accounts with a payment method saved before November 10, 2026 see their invoices on the Billing page itself. To cancel API card billing, open [Billing](https://diffio.ai/developers/billing/) and select **Manage billing**, then select **Cancel subscription** in the billing portal. Billing ends at the end of your billing month, and the account goes back to having no payment method. If the portal shows no Cancel subscription (payment methods saved before November 10, 2026), contact [support@diffio.ai](mailto:support@diffio.ai). If a charge fails, new API generations return HTTP 402 with the code `payment_failed`. Open the billing portal from the [Billing page](https://diffio.ai/developers/billing/), select **Update payment method** under Current subscription and choose a card: the open invoice is paid and API access resumes. Adding a card under Payment methods alone does not change the card that is charged. If card billing has already ended and its last invoice is unpaid, select **Pay invoice** on the Billing page instead. We will email you if an invoice is unpaid. ### What should I do if my billing question is not answered here? Contact our support team at [support@diffio.ai](mailto:support@diffio.ai). --- Source: https://diffio.ai/docs/overview/changelog/ # Changelog and versioning What changed in the Diffio API and SDKs, newest first, and what the `/v2` API promises. **Current versions** 1. API `/v2`, Python `diffio` 1.0.0, Node.js `diffio` 1.0.19: Documented 2. API older versions, Python 0.x, Node.js 0.x: Still running, not described here ## Changelog 1. November 15, 2026 ### SDK releases - Node.js diffio 1.0.1 to 1.0.19: version number only, the same code as 1.0.0. 2. November 13, 2026 ### API v2 docs and SDK 1.0 - [Python diffio 1.0.0 and Node.js diffio 1.0.0 released: /v2 only, snake_case fields like the wire.](https://diffio.ai/docs/developers/quick-start/) - These docs describe /v2 only; older versions keep running. 3. November 12, 2026 ### Webhooks, one error catalogue - [Ten webhook events: generation, separated tracks, export, assistant turn and project.](https://diffio.ai/docs/developers/webhooks/) - [Dashboard keys with write access can open the webhook portal.](https://diffio.ai/docs/api-reference/open-webhook-portal/) - [One error catalogue: every code with its status and retry rule, also in OpenAPI x-error-codes.](https://diffio.ai/docs/api-reference/errors/) - Every status resource carries error with a stable code when it fails. - Every answer carries a Server-Timing header. 4. November 11, 2026 ### The /v2 resource API - [Projects, generations and models as resources; model is a body field.](https://diffio.ai/docs/api-reference/create-generation/) - [Playback grants with ready media URLs, and project deletion.](https://diffio.ai/docs/api-reference/get-generation-media/) - [Separated tracks: saved mixes and exports.](https://diffio.ai/docs/api-reference/create-generation-export/) - [Share links.](https://diffio.ai/docs/api-reference/publish-project-share/) - [Usage per account and per end user, and the Diffio-End-User header.](https://diffio.ai/docs/api-reference/usage-summary/) - [Transcripts, drafts, transcript edits and the edit assistant.](https://diffio.ai/docs/api-reference/get-transcript/) - [Account-wide Idempotency-Key with conflict detection.](https://diffio.ai/docs/api-reference/create-project/) ## Versioning The version is in the path: `https://api.diffio.ai/v2`. Within `/v2`, changes only add. | Change | Within `/v2` | | --- | --- | | New endpoints, optional request fields, response fields, error codes, webhook events | Any time. Ignore fields and codes you do not know. | | Removing or renaming a field, endpoint, error code or event | Never. Only in a new version path; the old one keeps running. | | Retiring a model | Kept working. A retired model name runs on the current model of its tier, at the lower price ([Models](https://diffio.ai/docs/overview/models/)). | | `error.code` values | Stable. Branch on the code, not the message ([Errors](https://diffio.ai/docs/api-reference/errors/)). | - **Announcements:**: every change is listed on this page with its date; a deprecation is listed here before it takes effect. - **SDKs:**: semantic versions. 1.x talks to `/v2`; a minor release adds methods, a patch fixes; a new major follows a new API version. - **Machine-readable:**: the OpenAPI document at `GET https://api.diffio.ai/v2/openapi.json` always matches the running API. ## Support and status - **Email:** [support@diffio.ai](mailto:support@diffio.ai). Include the `request_id` from the error (also the `X-Request-Id` header). - **Status page:** Diffio has no public status page. If calls keep failing with `5xx` after the SDK retries, email support with a `request_id`. --- Source: https://diffio.ai/docs/developers/quick-start/ # Quickstart: restore audio in Python or Node Create an API key, install the SDK and restore a speech recording in one call with Python, Node.js or cURL. ## Prerequisites - A Diffio API key with Write permission enabled - A speech audio or video file up to 2 GB, such as `interview.mp3` - Python 3.8+, Node 18+, or `curl` and `jq` ## Restore your first file ### 1. Create an API key [Create an API key in the developer dashboard](https://diffio.ai/developers/api-keys/) with Write permission enabled, then copy it right away (the secret is shown once). Pass it as `Authorization: Bearer ` on API requests, or set `DIFFIO_API_KEY` so the SDK reads it automatically. **Terminal** ```bash export DIFFIO_API_KEY="diffio_live_..." ``` ### 2. Install the SDK Install the Diffio SDK for Python or Node.js, or use `curl` and `jq` directly. **Python** ```bash pip install diffio ``` **Node.js** ```bash npm install diffio ``` **cURL** ```bash # Uses curl and jq (no SDK install needed) curl --version && jq --version ``` > **SDK source code** > > Browse the SDK repositories on GitHub: [diffio-python](https://github.com/Diffio-AI/diffio-python) and [diffio-js](https://github.com/Diffio-AI/diffio-js). ### 3. Restore a file in one call Run a restore on `interview.mp3` with `diffio-flash` (the alias for `diffio-4.7-flash`). The SDK helper creates the project with a queued generation, uploads the file via `upload.requests`, marks the upload complete, polls until `status` is `complete` and saves the restored MP3. **Python** ```python from diffio import DiffioClient client = DiffioClient() # reads DIFFIO_API_KEY result = client.restore_audio( "interview.mp3", model="diffio-flash", output_path="interview-restored.mp3", on_progress=lambda generation: print(generation.status, generation.stage), ) print(result.project.id, result.generation.id, result.output_path) ``` **Node.js** ```javascript import { DiffioClient } from "diffio"; const client = new DiffioClient(); // reads DIFFIO_API_KEY const result = await client.restoreAudio({ file: "interview.mp3", model: "diffio-flash", outputPath: "interview-restored.mp3", onProgress: (generation) => console.log(generation.status, generation.stage), }); console.log(result.project.id, result.generation.id, result.output_path); ``` **cURL** ```bash set -euo pipefail API="https://api.diffio.ai/v2" FILE="interview.mp3" AUTH="Authorization: Bearer $DIFFIO_API_KEY" # Every request gets a time limit: 60 s for API calls, 15 min per upload part or download API_CURL=(curl -fsS --connect-timeout 10 --max-time 60) BULK_CURL=(curl -fsS --connect-timeout 10 --max-time 900) WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT # 1) Create the project and queue a Flash restore in one call "${API_CURL[@]}" -X POST "$API/projects" -H "$AUTH" -H "Content-Type: application/json" \ -d "{\"file_name\": \"$FILE\", \"content_type\": \"audio/mpeg\", \"size_bytes\": $(wc -c < "$FILE"), \"generation\": {\"model\": \"diffio-flash\"}}" \ > "$WORK/project.json" PROJECT_ID=$(jq -er .id "$WORK/project.json") GEN_ID=$(jq -er .latest_generation.id "$WORK/project.json") UPLOAD_TOKEN=$(jq -er .upload.upload_token "$WORK/project.json") START_URL=$(jq -er .upload.requests.start.url "$WORK/project.json") PART_URL_TEMPLATE=$(jq -er .upload.requests.part.url "$WORK/project.json") COMPLETE_URL=$(jq -er .upload.requests.complete.url "$WORK/project.json") PART_SIZE=$(jq -er .upload.part_size_bytes "$WORK/project.json") # 2) Upload the bytes by following upload.requests, then mark complete UPLOAD_ID=$("${API_CURL[@]}" -X POST "$START_URL" -H "Authorization: Bearer $UPLOAD_TOKEN" | jq -er .uploadId) split -b "$PART_SIZE" -d -a 5 "$FILE" "$WORK/part." N=1; PARTS="[]" for P in "$WORK"/part.*; do PART_URL="${PART_URL_TEMPLATE/\{part_number\}/$N}" PART_URL="${PART_URL/\{upload_id\}/$UPLOAD_ID}" ETAG=$("${BULK_CURL[@]}" -X PUT "$PART_URL" -H "Authorization: Bearer $UPLOAD_TOKEN" --data-binary @"$P" | jq -er .etag) PARTS=$(jq -c --argjson n "$N" --arg e "$ETAG" '. + [{partNumber: $n, etag: $e}]' <<<"$PARTS") N=$((N + 1)) done "${API_CURL[@]}" -X POST "$COMPLETE_URL" -H "Authorization: Bearer $UPLOAD_TOKEN" \ -H "Content-Type: application/json" -d "{\"uploadId\": \"$UPLOAD_ID\", \"parts\": $PARTS}" > /dev/null "${API_CURL[@]}" -X POST "$API/projects/$PROJECT_ID/upload/complete" -H "$AUTH" > /dev/null # 3) Poll for up to 30 minutes, stop on failure, then download the restored MP3 DEADLINE=$((SECONDS + 1800)) while :; do LEFT=$((DEADLINE - SECONDS)) [ "$LEFT" -gt 0 ] || { echo "timed out waiting for the restore" >&2; exit 1; } # Each status call gets at most 60 s, and never more than the time left curl -fsS --connect-timeout 10 --max-time $((LEFT < 60 ? LEFT : 60)) \ "$API/projects/$PROJECT_ID/generations/$GEN_ID" -H "$AUTH" > "$WORK/generation.json" STATUS=$(jq -er .status "$WORK/generation.json") [ "$STATUS" = "complete" ] && break if [ "$STATUS" = "failed" ]; then jq .error "$WORK/generation.json" >&2; exit 1; fi sleep $((LEFT < 3 ? LEFT : 3)) done MEDIA_URL=$("${API_CURL[@]}" "$API/projects/$PROJECT_ID/generations/$GEN_ID/media" -H "$AUTH" | jq -er .files.audio) "${BULK_CURL[@]}" -o interview-restored.mp3 "$MEDIA_URL" echo "$PROJECT_ID $GEN_ID interview-restored.mp3" ``` Expected result The generation reaches `status: "complete"` on `diffio-4.7-flash` and writes the restored recording to `interview-restored.mp3`; each tab prints the project id, the generation id and the file. To fetch the word-timed transcript too, call [Get a generation's transcript](https://diffio.ai/docs/api-reference/get-transcript/) with the returned project and generation ids. ## How it fits together [Projects](https://diffio.ai/docs/api-reference/create-project/) hold your uploaded audio or video. Each project can run one or more [generations](https://diffio.ai/docs/api-reference/create-generation/) across [Diffio models](https://diffio.ai/docs/overview/models/), and you fetch temporary URLs from [generation media](https://diffio.ai/docs/api-reference/get-generation-media/) to stream or download restored files. Create a project with a media file, run multiple generations with different models, then download the results. 1. **Create project**: with your audio or video file 2. **Generations** `diffio-4.7-flash` `diffio-4.7-pro` 3. **Download results**: restored audio, video or transcript ## Troubleshooting - **`401` `403` Pass `Authorization: Bearer ` with an active key that has Write permission.** The key is missing (`missing_api_key`), invalid (`invalid_api_key`), inactive, or lacks Write permission (`permission_denied`). - **`402` `insufficient_credit` Add credit on the Billing page of the developer dashboard.** Your API credit is used up, or cannot cover the file. - **`409` `not_ready` Poll the generation until `status` is `complete`, or finish uploading first.** The generation, transcript, or separated tracks are still processing (`not_ready`), or `upload/complete` ran before the upload arrived (`upload_missing`). Every error response includes `error.code`, `error.message` and `error.request_id`. Full error handling and retry rules are in the [Full API guide](https://diffio.ai/docs/developers/full-api-guide/#errors). ## Next steps [**Full API guide** Create projects, follow upload descriptors, poll stages, paginate lists and scope end users.](https://diffio.ai/docs/developers/full-api-guide/) [**Webhooks guide** Open the webhook portal, subscribe to events and verify Svix signatures.](https://diffio.ai/docs/developers/webhooks/) [**Podcast cleanup in a SaaS app** A complete build: browser uploads, one project list per user and signed webhooks.](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) [**API reference** Every endpoint, parameter, request field and response schema.](https://diffio.ai/docs/api-reference/introduction/) Working with a coding agent? [Build with AI agents](https://diffio.ai/docs/developers/ai-agents/) gives it every docs page as plain text, with a ready prompt. New releases, and which SDK version talks to which API version, are listed in the [Changelog](https://diffio.ai/docs/overview/changelog/). --- Source: https://diffio.ai/docs/developers/ai-agents/ # Build with AI agents: give your agent the docs Hand your coding agent the whole Diffio API in one URL. Every docs page is also plain Markdown, so Claude Code, Codex, Cursor or any other agent reads exactly what you would. ## Give your agent the docs One URL holds every guide and endpoint as plain text. Paste it, or the prompt, into Claude Code, Codex, Cursor or any coding agent. [https://diffio.ai/docs/llms-full.txt](https://diffio.ai/docs/llms-full.txt) ## Paste this prompt Copy it, replace the first line with what you want built, and paste it into your agent. It points the agent at the docs and the SDK before it writes any code. **Prompt** ```text I want to build this with the Diffio speech restoration API: Before writing code, read the Diffio API docs: https://diffio.ai/docs/llms-full.txt (plain text, every guide and endpoint). The OpenAPI document is at https://api.diffio.ai/v2/openapi.json. Use the official SDK, version 1.0 or later (`pip install diffio` or `npm install diffio`), and read the API key from the DIFFIO_API_KEY environment variable. Follow the docs exactly: field names, the upload flow and error codes. If the docs do not cover something, say so instead of guessing. ``` ## Connect the docs MCP server Agents that speak MCP can search the docs, read one page and read one API operation instead of loading every page. It is read-only and needs no key: `search_docs`, `get_page`, `get_api_operation`. **Claude Code: Terminal** ```bash claude mcp add --transport http diffio-docs https://diffio.ai/docs/mcp ``` **Cursor: .cursor/mcp.json** ```json { "mcpServers": { "diffio-docs": { "url": "https://diffio.ai/docs/mcp" } } } ``` **VS Code: .vscode/mcp.json** ```json { "servers": { "diffio-docs": { "type": "http", "url": "https://diffio.ai/docs/mcp" } } } ``` **Codex: ~/.codex/config.toml** ```toml [mcp_servers.diffio-docs] url = "https://diffio.ai/docs/mcp" ``` ## Every way to read the docs None of these needs an API key. - ### All API docs in one file [`https://diffio.ai/docs/llms-full.txt`](https://diffio.ai/docs/llms-full.txt) Every guide and endpoint page as Markdown, in reading order. Give an agent this one. - ### OpenAPI 3.1 document [`https://api.diffio.ai/v2/openapi.json`](https://api.diffio.ai/v2/openapi.json) Machine-readable schema for every /v2 route, for code generators and typed clients. - ### Docs MCP server `https://diffio.ai/docs/mcp` Streamable HTTP, read-only, no key: search_docs, get_page and get_api_operation. - ### Docs index [`https://diffio.ai/llms.txt`](https://diffio.ai/llms.txt) One line per page with its Markdown URL, so an agent can fetch only the pages it needs. - ### Any single page [`https://diffio.ai/docs/developers/quick-start.md`](https://diffio.ai/docs/developers/quick-start.md) Add .md to a docs URL, or request the HTML URL with Accept: text/markdown. **Fetch any page as Markdown** ```bash # Add .md to any docs URL curl https://diffio.ai/docs/api-reference/create-project.md # Or ask for Markdown at the normal URL curl -H "Accept: text/markdown" https://diffio.ai/docs/api-reference/create-project/ ``` ## What your agent must get right The prompt points the agent at these, and the docs bundle opens with them: the details agents most often get wrong. 1. Base URL `https://api.diffio.ai/v2`. Send the key as `Authorization: Bearer ` and read it from the `DIFFIO_API_KEY` environment variable. Never ship the key to a browser or mobile app. 2. Prefer the SDKs: `pip install diffio` (Python) or `npm install diffio` (Node.js), version 1.0 or later. Earlier versions use an older API that these docs do not describe. 3. Request and response fields are snake_case (`file_name`, `latest_generation`, `upload_token`), and the objects both SDKs return keep those names. 4. The flow is: create a project, upload the file by following `upload.requests`, create a generation with `model` `diffio-flash` or `diffio-pro`, wait for `status` `complete`, then get media URLs. Pass `generation` when you create the project to queue the restore in the same call. 5. Let browsers upload straight to Diffio: hand them the project's `upload` (its `upload_token` covers that one upload for 24 hours) and keep the API key on your server. 6. Wait with webhooks in production; poll `GET /projects/{project_id}/generations/{generation_id}` every few seconds otherwise. 7. Media URLs from `GET .../media` need no API key and expire after 6 hours (`expires_at`); request a new grant instead of storing them. 8. Building for many users? Send `Diffio-End-User: ` so each user sees only their own projects and usage. 9. Send an `Idempotency-Key` on project, generation and edit creates when your own code may retry them; the SDKs add one for their own retries. 10. Branch on `error.code`, not the HTTP status: one status can mean several things with different fixes. Every code and its retry rule is listed at https://diffio.ai/docs/api-reference/errors/. ## Keep the docs in your repo For an agent that works offline or keeps losing context, save the docs into the repository and point its instructions file (`AGENTS.md`, `CLAUDE.md` or `.cursor/rules`) at them. **Save the docs** ```bash mkdir -p docs && curl -sSf https://diffio.ai/docs/llms-full.txt -o docs/diffio-api.md ``` **AGENTS.md** ```markdown ## Diffio API - Read docs/diffio-api.md before changing code that calls Diffio (refresh it with: curl -sSf https://diffio.ai/docs/llms-full.txt -o docs/diffio-api.md). - Base URL `https://api.diffio.ai/v2`. Send the key as `Authorization: Bearer ` and read it from the `DIFFIO_API_KEY` environment variable. Never ship the key to a browser or mobile app. - Prefer the SDKs: `pip install diffio` (Python) or `npm install diffio` (Node.js), version 1.0 or later. Earlier versions use an older API that these docs do not describe. - Request and response fields are snake_case (`file_name`, `latest_generation`, `upload_token`), and the objects both SDKs return keep those names. - The flow is: create a project, upload the file by following `upload.requests`, create a generation with `model` `diffio-flash` or `diffio-pro`, wait for `status` `complete`, then get media URLs. Pass `generation` when you create the project to queue the restore in the same call. - Let browsers upload straight to Diffio: hand them the project's `upload` (its `upload_token` covers that one upload for 24 hours) and keep the API key on your server. - Wait with webhooks in production; poll `GET /projects/{project_id}/generations/{generation_id}` every few seconds otherwise. - Media URLs from `GET .../media` need no API key and expire after 6 hours (`expires_at`); request a new grant instead of storing them. - Building for many users? Send `Diffio-End-User: ` so each user sees only their own projects and usage. - Send an `Idempotency-Key` on project, generation and edit creates when your own code may retry them; the SDKs add one for their own retries. - Branch on `error.code`, not the HTTP status: one status can mean several things with different fixes. Every code and its retry rule is listed at https://diffio.ai/docs/api-reference/errors/. ``` The file is rebuilt on every docs release; fetch it again before new work. ## Give your agent a key [Create a key with Write permission](https://diffio.ai/developers/api-keys/) and set it as `DIFFIO_API_KEY` in the shell your agent runs in. Every API account starts with a one-time $5 credit, enough for an agent to run real restores while it builds and tests. Keep the key in the environment, never in code the agent commits. ## Related pages - [Podcast cleanup in a SaaS app](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/): A complete server, browser upload and webhook build to hand an agent. - [Errors](https://diffio.ai/docs/api-reference/errors/): Every error code with its retry rule. - [Quickstart](https://diffio.ai/docs/developers/quick-start/): Restore a first file in one call, by hand. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [API reference](https://diffio.ai/docs/api-reference/introduction/): Base URL, authentication, errors and every endpoint. --- Source: https://diffio.ai/docs/developers/full-api-guide/ # Full API guide: workflow, topics and limits The Diffio API on one page: the workflow, where each topic lives, and the rules and limits that apply to every call. ## Workflow Create a project with a media file, run one or more generations with different models, then download the results. 1. **Create project**: with your audio or video file 2. **Generations** `diffio-4.7-flash` `diffio-4.7-pro` 3. **Download results**: restored audio, video or transcript Create a project, upload the file, run one or more generations, then read their media. A [webhook](https://diffio.ai/docs/developers/webhooks/) tells your server when each one finishes. ## Topics ### Start and build - [Quickstart: Key, install and a restore in one call, Python or Node.](https://diffio.ai/docs/developers/quick-start/) - [Podcast cleanup in a SaaS app: Browser uploads, one end user per customer, signed webhooks.](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) - [All use-case guides: Video streaming, Flash vs Pro, bulk restores, transcript edits, tracks, shares and billing.](https://diffio.ai/docs/developers/guides/) - [Webhooks: Events, signatures, retries and the webhook portal.](https://diffio.ai/docs/developers/webhooks/) ### Concepts - [Projects and uploads: A project holds one uploaded recording; its status moves from awaiting_upload to ready as the file arrives.](https://diffio.ai/docs/overview/concepts/projects-and-uploads/) - [Generations: A generation is one restore of a project with one model; follow its status and stage, then read its media.](https://diffio.ai/docs/overview/concepts/generations/) - [Transcripts and edits: Every generation has a word-timed transcript; change its words on a Pro result and Diffio restores the changed parts again.](https://diffio.ai/docs/overview/concepts/transcripts-and-edits/) - [Separated tracks: Each restore separates speech from background; save a balance of the two and render it as a downloadable export.](https://diffio.ai/docs/overview/concepts/separated-tracks/) - [Shares: A share is a revocable public link to one project's result that anyone with its id can play without an API key.](https://diffio.ai/docs/overview/concepts/shares/) - [End users: Send Diffio-End-User with each request to keep every customer's projects, usage and events apart under one API key.](https://diffio.ai/docs/overview/concepts/end-users/) ### Reference - [Errors: Every error code, its status and what to do.](https://diffio.ai/docs/api-reference/errors/) - [API reference: Base URL, authentication and every endpoint.](https://diffio.ai/docs/api-reference/introduction/) ## Limits | Limit | Value | | --- | --- | | File size | up to 2 GB (2,147,483,648 bytes); larger is `413 upload_too_large` | | Media length | no limit | | Upload part size | 32 MiB (33,554,432 bytes) | | Upload token | 24 hours (`upload.expires_at`) | | Media URLs | 6 hours (`expires_at`); call `GET …/media` again | | Share URLs | until the share is revoked or changed, then stop within about a minute | | Webhook timestamp tolerance | 300 seconds | | Restore billing | whole seconds, 60 second minimum per restore | | Transcript edit billing | 30 seconds per restored window, no minimum | | Idempotency-Key | up to 255 characters | | Diffio-End-User | up to 128 characters | | Generation label | up to 120 characters | | metadata | 50 keys; keys up to 40 characters, values up to 500 | | List page | `limit` 1 to 100, default 20 | | Usage period | up to 366 days and 20,000 generations | | Rate limits | no general per-key quota; the edit assistant allows 30 turns per 10 minutes plus a daily cap, assistant feedback 10 per hour; `429 rate_limited` means retry with backoff | | SDK defaults | 60 second timeout; 2 retries on 408, 429, 5xx and network errors, honouring `Retry-After` | ## Pagination [GET /projects](https://diffio.ai/docs/api-reference/list-projects/) and [GET /projects/{project_id}/generations](https://diffio.ai/docs/api-reference/list-project-generations/) answer newest first with `{ object: "list", data, next_cursor }`. Pass `next_cursor` as `cursor` until it is `null`; the SDKs can walk every page for you. 1. GET `/projects?limit=20` `data[]` newest first, `next_cursor` 2. GET `/projects?cursor={next_cursor}` until `next_cursor` is `null` 3. Next [/projects/{project_id}/generations](https://diffio.ai/docs/api-reference/list-project-generations/) with a project's `id` **Python** ```python from diffio import DiffioClient client = DiffioClient() # reads DIFFIO_API_KEY page = client.projects.list(limit=20) print([project.id for project in page.data], page.next_cursor) for project in client.projects.iter(limit=50): # fetches every page as needed latest = project.latest_generation print(project.id, project.file_name, latest.status if latest else "no generation") ``` **Node.js** ```javascript import { DiffioClient } from "diffio"; const client = new DiffioClient(); // reads DIFFIO_API_KEY // One page: data and next_cursor exactly as the API sends them. const page = await client.projects.list({ limit: 20 }); console.log(page.data.map((p) => p.id), page.next_cursor); // Every project, newest first; the SDK fetches the next page when it needs it. for await (const project of client.projects.list({ limit: 50 })) { console.log(project.id, project.file_name, project.latest_generation?.status); } ``` **cURL** ```bash API="https://api.diffio.ai/v2" PAGE=$(curl -sS --connect-timeout 10 --max-time 60 "$API/projects?limit=20" \ -H "Authorization: Bearer $DIFFIO_API_KEY") NEXT_CURSOR=$(jq -r '.next_cursor // empty' <<<"$PAGE") if [ -n "$NEXT_CURSOR" ]; then curl -sS --connect-timeout 10 --max-time 60 "$API/projects?limit=20&cursor=$NEXT_CURSOR" \ -H "Authorization: Bearer $DIFFIO_API_KEY" fi ``` ## Idempotency [POST /projects](https://diffio.ai/docs/api-reference/create-project/) (per account and end user), [POST …/generations](https://diffio.ai/docs/api-reference/create-generation/) (per project) and [POST …/edits](https://diffio.ai/docs/api-reference/create-transcript-edit/) (per edited generation) honour `Idempotency-Key`. The SDKs send a fresh key when you pass none, so their own retries never create twice; pass your own (an order or job id) when your queue may retry from a new process. 1. POST [/projects](https://diffio.ai/docs/api-reference/create-project/) `id` 2. POST `/projects/{project_id}/generations` `id` 3. GET [/projects/{project_id}/generations/{generation_id}](https://diffio.ai/docs/api-reference/get-generation/) `status` 4. GET [/projects/{project_id}/generations/{generation_id}/media](https://diffio.ai/docs/api-reference/get-generation-media/) `files` **Replays and conflicts, case by case** - First request `201` new generation - Same `Idempotency-Key`, same body `201` the same generation `id` - Same `Idempotency-Key`, other `model`, `sampling` or `label` `409` `idempotency_key_conflict` - Same `Idempotency-Key` + same body `201` with the existing resource, never billed twice - Same `Idempotency-Key` + different body `409` `idempotency_key_conflict` **Python** ```python # The same key on a retry returns the same generation and bills it once. generation = client.generations.create( project_id, model="diffio-pro", idempotency_key="order-1042-restore", ) ``` **Node.js** ```javascript // The same key on a retry returns the same generation and bills it once. const generation = await client.generations.create( projectId, { model: "diffio-pro" }, { idempotencyKey: "order-1042-restore" }, ); ``` **cURL** ```bash curl -sS --connect-timeout 10 --max-time 60 -X POST "$API/projects/$PROJECT_ID/generations" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Idempotency-Key: order-1042-restore" \ -H "Content-Type: application/json" \ -d '{"model": "diffio-pro"}' ``` ## End users Send `Diffio-End-User` to act for one of your customers: their projects, usage and events stay apart under one API key. How it works and its limits: [End users](https://diffio.ai/docs/overview/concepts/end-users/). **Python** ```python customer_client = DiffioClient(end_user="customer-42") # every call acts for this end user customer_projects = customer_client.projects.list() # Or scope a single call on an account-wide client: customer_usage = client.usage.get(end_user="customer-42") ``` **Node.js** ```javascript const customerClient = new DiffioClient({ endUser: "customer-42" }); const customerProjects = await customerClient.projects.list(); // Or scope a single call on an account-wide client: const customerUsage = await client.usage.get({}, { endUser: "customer-42" }); ``` **cURL** ```bash curl -sS --connect-timeout 10 --max-time 60 "$API/projects" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Diffio-End-User: customer-42" ``` ## Errors Every failure answers `{ "error": { "code", "message", "request_id", "details" } }`. The common ones and their fixes are below; every code is on [Errors](https://diffio.ai/docs/api-reference/errors/). - **`401` `403` Pass `Authorization: Bearer ` with an active key that has Write permission.** The key is missing (`missing_api_key`), invalid (`invalid_api_key`), inactive, or lacks Write permission (`permission_denied`). - **`402` `insufficient_credit` Add credit on the Billing page of the developer dashboard.** Your API credit is used up, or cannot cover the file. - **`402` `needs_payment_method` Add a payment method in the developer dashboard.** Accounts with card billing only: the credit is used up, or cannot cover the file, and no payment method is saved. - **`402` `payment_failed` On the Billing page, select Update payment method and choose a card for your subscription, or Pay invoice once card billing has ended.** A payment for API usage failed, or the last invoice of ended card billing is unpaid. API usage is blocked until that invoice is paid. Accounts with card billing only. - **`402` `usage_limit_reached` Wait for the charge to complete; the API continues as soon as it does.** Unbilled usage reached $100; it is being charged now. Accounts with card billing only. - **`409` `not_ready` Poll the generation until `status` is `complete`, or finish uploading first.** The generation, transcript, or separated tracks are still processing (`not_ready`), or `upload/complete` ran before the upload arrived (`upload_missing`). - **`404` `transcript_not_found` Check `error.code` and confirm any `Diffio-End-User` header matches the project.** This generation has no transcript, or the project or generation id does not exist for this end user (`project_not_found`, `generation_not_found`). --- Source: https://diffio.ai/docs/developers/webhooks/ # Webhooks: events, signatures and retries Webhooks notify your server with signed HTTP POST events whenever a project, generation, separated-track stem, export or transcript assistant turn finishes or fails, so your application does not need to poll. ## How webhooks work 1. Diffio: **State transition**. A generation, project, stem, export or turn completes or fails 2. Signed POST: **JSON event**. `svix-id`, `svix-timestamp`, `svix-signature` headers 3. Your endpoint: **Verify, then answer `200`**. Answer fast; any non-2xx response is retried with backoff 4. Background job: **Fetch media or details**. Call generation media or get generation, then update records **Account scope and portal model** Webhooks belong to your whole Diffio account rather than a single API key. Once enabled, events fire across all API keys and all end users on the account; every event payload carries `data.end_user` (`null` when created without `Diffio-End-User`). Development and production use separate webhook portals and applications. Disable CSRF middleware on your webhook route so incoming signed POST requests reach your signature check untouched. ## Add an endpoint ### 1. Open the webhook portal Call [POST /webhooks/portal](https://diffio.ai/docs/api-reference/open-webhook-portal/) with an API key that has Write permission (a read-only key gets `403`). The first call creates your account's webhook application and turns event delivery on. Open the returned `url` right away: portal links are short-lived, so request a fresh link each time you visit. Do not send the `Diffio-End-User` header on `POST /webhooks/portal`; the endpoint is account-wide and refuses that header with `403` (`permission_denied`). Both SDKs leave it off this call, even on a client created for an end user. **Python** ```python from diffio import DiffioClient client = DiffioClient() # reads DIFFIO_API_KEY portal = client.webhooks.portal() print(portal.url, portal.event_types) ``` **Node.js** ```javascript import { DiffioClient } from "diffio"; const client = new DiffioClient(); // reads DIFFIO_API_KEY const portal = await client.webhooks.portal(); console.log(portal.url, portal.event_types); ``` **cURL** ```bash curl -sS -X POST "https://api.diffio.ai/v2/webhooks/portal" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ![Webhook portal endpoints list with the Add Endpoint button.](https://diffio.ai/images/docs/webhooks/WebhookPortal1AddEndpointCrop.png) **Select Add Endpoint in the webhook portal. [Full-size screenshot](https://diffio.ai/images/docs/webhooks/WebhookPortal1AddEndpoint.png)** > **No server yet** > > If you do not have an HTTPS receiver deployed yet, use the portal to create a temporary test receiver URL so you can inspect real deliveries while building your handler. ### 2. Add your endpoint URL and events Paste your HTTPS endpoint URL and tick the events you handle. Leaving every box clear subscribes the endpoint to all of them. - **Generations** `generation.completed` `generation.failed` `generation.stems_ready` `generation.stems_failed` - **Projects** `project.ready` `project.failed` - **Exports** `export.ready` `export.failed` - **Assistant turns** `transcript_assistant_turn.completed` `transcript_assistant_turn.failed` > **About the portal's event list** > > - It also lists `generation.queued` and `generation.processing`, kept for an older API. This API never sends them; follow progress with [Get a generation](https://diffio.ai/docs/api-reference/get-generation/). > - Its sample payloads for `generation.completed` and `generation.failed` show that older schema. Real deliveries use the `{ type, id, created_at, data }` envelope under [Events and payloads](#events). ### 3. Save the signing secret Open the new endpoint's details page, reveal its `whsec_...` signing secret and store it as `DIFFIO_WEBHOOK_SECRET` in your secret manager. Each endpoint has its own unique secret. ![The Signing Secret row of the endpoint details, with the hidden secret and its reveal button.](https://diffio.ai/images/docs/webhooks/WebhookPortal3SigningSecretRowCrop.png) **Copy the Signing Secret from the endpoint details. [Full-size screenshot](https://diffio.ai/images/docs/webhooks/WebhookPortal3Endpoint.png)** ## Test endpoints 1. Trigger: **Run a short restore**. Upload a short clip and restore it; there is no test-event API endpoint 2. Inspect: **Portal message log**. View each delivery's payload and your endpoint's response in the portal 3. Confirm: **Signature + `200`**. Your receiver verifies `svix-signature` and returns a `2xx` status ## Events and payloads Every delivery is `{ type, id, created_at, data }`. `id` is `"evt_"` plus 32 hex characters, the same on every retry, so dedupe on it. Only finished or failed states send events, never progress. Every `data` has `id`, `project_id`, `end_user` and `status`. The table lists what each event adds. | Event `type` | `data.object` | `status` | Also in `data` | | --- | --- | --- | --- | | `generation.completed` | object `generation` | status `"complete"` | also `kind` (`"restore"` or `"edit"`) | | `generation.failed` | object `generation` | status `"failed"` | also `kind`, `error_code` | | `generation.stems_ready` | object `generation` | status the generation's | also `kind`, `stems_status: "ready"` | | `generation.stems_failed` | object `generation` | status the generation's | also `kind`, `stems_status: "failed"` | | `export.ready` | object `generation_export` | status `"ready"` | also `generation_id`; `id` ends `-inline` for inline exports | | `export.failed` | object `generation_export` | status `"failed"` | also `generation_id` | | `transcript_assistant_turn.completed` | object `transcript_assistant_turn` | status `"complete"` | also `generation_id` | | `transcript_assistant_turn.failed` | object `transcript_assistant_turn` | status `"failed"` | also `generation_id` | | `project.ready` | object `project` | status `"ready"` | also none (`project_id` equals `id`) | | `project.failed` | object `project` | status `"failed"` | also none (`project_id` equals `id`) | **generation.completed** ```json { "type": "generation.completed", "id": "evt_4b8c1d0e9f2a3b4c5d6e7f8091a2b3c4", "created_at": "2026-11-13T00:33:41Z", "data": { "object": "generation", "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "end_user": "customer-42", "status": "complete", "kind": "restore" } } ``` **generation.failed** ```json { "type": "generation.failed", "id": "evt_9a7e6f5d4c3b2a1098f7e6d5c4b3a210", "created_at": "2026-11-13T00:35:12Z", "data": { "object": "generation", "id": "80cb25c0-31b4-5e9a-9c71-04d2a1b8e3f9", "project_id": "2f8ee512-71a0-5c4d-8e12-91f3b4c5d6e7", "end_user": "customer-42", "status": "failed", "kind": "restore", "error_code": "no_speech_detected" } } ``` > **Reading generation and failure details** > > - **Generation id location:**: on all four `generation.*` events, the generation id is `data.id` (there is no `generation_id` field on generation payloads). On `export.*` and `transcript_assistant_turn.*` events, `data.id` is the export or turn id and `data.generation_id` names the generation. > - **Fetching media and errors:**: webhook payloads intentionally stay compact and never embed media URLs or human-readable error messages. On `generation.completed`, call [GET /projects/{project_id}/generations/{generation_id}/media](https://diffio.ai/docs/api-reference/get-generation-media/) (or [GET .../transcript](https://diffio.ai/docs/api-reference/get-transcript/)). On `generation.failed`, `data.error_code` gives the machine-readable code; call [GET /projects/{project_id}/generations/{generation_id}](https://diffio.ai/docs/api-reference/get-generation/) to inspect the full `error` object and `warnings`. ## Verify signatures Every webhook delivery is signed with Svix headers so you can verify authenticity and reject replay attacks. Always verify against the exact raw request body bytes (or string) before parsing JSON. Required delivery headers `svix-id` `svix-timestamp` `svix-signature` ### Verify with the Diffio SDK Both SDKs verify signatures locally with zero external dependencies (default timestamp tolerance: `300` seconds) and return the parsed `{ type, id, created_at, data }` event. In WebCrypto runtimes (Cloudflare Workers, Deno, Bun or browsers), call `client.webhooks.verifySignatureAsync` (or standalone `verifyWebhookSignatureAsync`). Python also exports standalone `diffio.verify_webhook_signature`. **Python** ```python import os from diffio import DiffioClient, WebhookVerificationError client = DiffioClient() secret = os.environ["DIFFIO_WEBHOOK_SECRET"] # the endpoint's whsec_... signing secret from the webhook portal def handle_webhook(raw_body, headers): """raw_body: the request body bytes as received; headers: the request headers (any mapping).""" try: event = client.webhooks.verify_signature(raw_body, headers, secret) except WebhookVerificationError: return 400 if event.type == "generation.completed": print("restored", event.data.project_id, event.data.id, event.data.end_user) elif event.type == "generation.failed": print("failed", event.data.id, event.data.error_code) return 200 ``` **Node.js** ```javascript import http from "node:http"; import { DiffioClient, DiffioWebhookVerificationError } from "diffio"; const client = new DiffioClient(); const secret = process.env.DIFFIO_WEBHOOK_SECRET; // whsec_... from the webhook portal http .createServer((req, res) => { const chunks = []; req.on("data", (chunk) => chunks.push(chunk)); req.on("end", () => { try { // Pass the raw body exactly as received. const event = client.webhooks.verifySignature(Buffer.concat(chunks), req.headers, secret); console.log("verified", event.type, event.id, event.data.id); res.writeHead(204).end(); } catch (error) { if (!(error instanceof DiffioWebhookVerificationError)) throw error; console.log("rejected", error.message); res.writeHead(400).end(); } }); }) .listen(Number(process.env.PORT ?? 3000)); ``` ### Drop-in handlers Each framework hides the raw body differently, and a parsed body never verifies. These read it the way the signature needs. **Next.js: app/api/webhooks/diffio/route.ts** ```typescript import { DiffioWebhookVerificationError, verifyWebhookSignatureAsync } from "diffio"; export async function POST(request: Request) { const rawBody = await request.text(); // read once, never request.json() try { const event = await verifyWebhookSignatureAsync(rawBody, request.headers, process.env.DIFFIO_WEBHOOK_SECRET!); // Record event.id and queue the work, then answer quickly. console.log(event.type, event.id, event.data.id); return new Response(null, { status: 204 }); } catch (error) { if (error instanceof DiffioWebhookVerificationError) return new Response(null, { status: 400 }); throw error; } } ``` **Express: server.mjs** ```javascript import express from "express"; import { DiffioWebhookVerificationError, verifyWebhookSignature } from "diffio"; const app = express(); // express.raw keeps the body as a Buffer; register it before any express.json() for this route. app.post("/webhooks/diffio", express.raw({ type: "application/json" }), (req, res) => { try { const event = verifyWebhookSignature(req.body, req.headers, process.env.DIFFIO_WEBHOOK_SECRET); console.log(event.type, event.id, event.data.id); res.sendStatus(204); } catch (error) { if (!(error instanceof DiffioWebhookVerificationError)) throw error; res.sendStatus(400); } }); app.listen(3000); ``` **FastAPI: main.py** ```python import os from fastapi import FastAPI, Request, Response from diffio import WebhookVerificationError, verify_webhook_signature app = FastAPI() SECRET = os.environ["DIFFIO_WEBHOOK_SECRET"] @app.post("/webhooks/diffio") async def diffio_webhook(request: Request): raw_body = await request.body() # the exact bytes that were signed try: event = verify_webhook_signature(raw_body, request.headers, SECRET) except WebhookVerificationError: return Response(status_code=400) print(event.type, event.id, event.data.id) return Response(status_code=204) ``` **Cloudflare Workers: src/index.ts** ```typescript import { DiffioWebhookVerificationError, verifyWebhookSignatureAsync } from "diffio"; export default { async fetch(request: Request, env: { DIFFIO_WEBHOOK_SECRET: string }): Promise { if (request.method !== "POST") return new Response(null, { status: 405 }); const rawBody = await request.text(); try { // WebCrypto: the async helper works in Workers, Deno, Bun and browsers. const event = await verifyWebhookSignatureAsync(rawBody, request.headers, env.DIFFIO_WEBHOOK_SECRET); console.log(event.type, event.id, event.data.id); return new Response(null, { status: 204 }); } catch (error) { if (error instanceof DiffioWebhookVerificationError) return new Response(null, { status: 400 }); throw error; } }, }; ``` ### Verify by hand If you do not use a Diffio SDK (or an official Svix library), verify the HMAC-SHA256 signature directly: 1. Read `svix-id`, `svix-timestamp` (Unix seconds) and `svix-signature` from the headers, plus the raw body bytes. 2. Reject the delivery if `svix-timestamp` is not an integer or differs from the current Unix time by more than `300` seconds. 3. Strip the `whsec_` prefix from your endpoint's signing secret and base64-decode the remaining string into raw key bytes. 4. Compute HMAC-SHA256 over `{svix-id}.{svix-timestamp}.{raw_body}` using those key bytes, then base64-encode the digest. 5. Split `svix-signature` on spaces; each entry has the form `,`. Compare your digest in constant time against every `v1,` entry and accept if any matches. **Python** ```python import base64 import hashlib import hmac import json import time def verify_svix_webhook(raw_body: bytes, headers: dict, secret: str, tolerance_seconds: int = 300) -> dict: lower = {k.lower(): v for k, v in headers.items()} msg_id = lower.get("svix-id") or "" msg_timestamp = lower.get("svix-timestamp") or "" msg_signature = lower.get("svix-signature") or "" if not msg_id or not msg_timestamp or not msg_signature: raise ValueError("Missing Svix signature headers") ts = int(msg_timestamp) if abs(time.time() - ts) > tolerance_seconds: raise ValueError("Webhook timestamp outside tolerance") key = base64.b64decode(secret[len("whsec_"):] if secret.startswith("whsec_") else secret) signed_content = f"{msg_id}.{msg_timestamp}.".encode("utf-8") + raw_body expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest()).decode("ascii") for entry in msg_signature.split(): version, _, digest = entry.partition(",") if version == "v1" and hmac.compare_digest(expected, digest): return json.loads(raw_body.decode("utf-8")) raise ValueError("Webhook signature does not match") ``` **Node.js** ```javascript import crypto from "node:crypto"; export function verifySvixWebhook(rawBody, headers, secret, toleranceSeconds = 300) { const msgId = headers["svix-id"]; const msgTimestamp = headers["svix-timestamp"]; const msgSignature = headers["svix-signature"]; if (!msgId || !msgTimestamp || !msgSignature) { throw new Error("Missing Svix signature headers"); } const ts = Number(msgTimestamp); if (!Number.isInteger(ts) || Math.abs(Math.floor(Date.now() / 1000) - ts) > toleranceSeconds) { throw new Error("Webhook timestamp outside tolerance"); } const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64"); const prefix = Buffer.from(`${msgId}.${msgTimestamp}.`, "utf8"); const bodyBytes = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8"); const expected = crypto.createHmac("sha256", key).update(prefix).update(bodyBytes).digest(); for (const entry of String(msgSignature).split(/\s+/)) { const [version, b64] = entry.split(",", 2); if (version !== "v1" || !b64) continue; const candidate = Buffer.from(b64, "base64"); if (candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected)) { return JSON.parse(bodyBytes.toString("utf8")); } } throw new Error("Webhook signature does not match"); } ``` **cURL / OpenSSL: OpenSSL** ```bash # Compute the expected Svix signature from raw_body.json, SVIX_ID, SVIX_TIMESTAMP and DIFFIO_WEBHOOK_SECRET KEY_HEX=$(printf "%s" "${DIFFIO_WEBHOOK_SECRET#whsec_}" | base64 -d | xxd -p -c 256) EXPECTED_SIG=$( (printf "%s.%s." "$SVIX_ID" "$SVIX_TIMESTAMP"; cat raw_body.json) \ | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$KEY_HEX" -binary | base64 ) echo "v1,$EXPECTED_SIG" ``` ## Retries and recovery Return any `2xx` HTTP status code (such as `200` or `204`) as soon as signature verification succeeds, and hand downloads or database updates off to a background worker. Any non-`2xx` response or connection failure is retried automatically by Svix with backoff. - Deduplicate: **Record `event.id` (`evt_...`) before running side effects.** The event `id` is derived from the event type, resource and transition, so it stays identical across every automatic retry and manual redelivery. - Signature fails: **Verify the raw body with the endpoint's own secret.** Never pass `JSON.stringify(req.body)`: re-serialized JSON changes bytes and breaks the HMAC (see [drop-in handlers](#framework-handlers)). Each endpoint has its own `whsec_...` secret, and timestamps more than 300 seconds from your clock are rejected. - Missed events: **Inspect and resend deliveries in the webhook portal.** Open a fresh portal link via `POST /webhooks/portal` to review attempt responses and trigger manual redeliveries. ## Next steps [Open the webhook portal Endpoint reference for `POST /webhooks/portal` and its response schema.](https://diffio.ai/docs/api-reference/open-webhook-portal/) [Get a generation Read full generation status, quality score, warnings and failure details.](https://diffio.ai/docs/api-reference/get-generation/) [Full API guide Projects, upload descriptors, media grants, transcripts and idempotency.](https://diffio.ai/docs/developers/full-api-guide/) --- Source: https://diffio.ai/docs/developers/guides/ # Use-case guides Short recipes on the Diffio API. Each one is a diagram, a few steps and one complete file in Python and Node. ## Guides - [Podcast cleanup in a SaaS app: Your users upload episodes from the browser straight to Diffio, your server keeps the API key and each user's projects apart, and a signed webhook tells you when the cleaned audio is ready to play. You get: Restored episodes for each customer, ready to play. Calls: Browser upload → webhook → player](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) - [Edit a transcript: Change a word in a Pro result's transcript and get back the whole recording with the new word said in the same voice. You get: The whole recording with one word replaced. Calls: Transcript → estimate → edit](https://diffio.ai/docs/developers/guides/edit-transcript/) - [Let users edit by asking: Let people ask for changes in plain words, show the assistant's proposals, and turn the one they accept into an edit. You get: Proposed edits from a plain request, one applied. Calls: Ask → proposals → edit](https://diffio.ai/docs/developers/guides/edit-by-asking/) - [Separate speech and background: Turn the background down under the restored speech, save that balance, and download it as an MP3. You get: An MP3 with the background turned down. Calls: Stems → mix → export](https://diffio.ai/docs/developers/guides/separate-speech-and-background/) - [Share a restored result: Give anyone a link that plays a restored recording, read it from a public page without an API key, and turn it off when you are done. You get: A public link that plays the restored audio. Calls: Publish → public read → revoke](https://diffio.ai/docs/developers/guides/share-a-result/) - [Restore a video and stream it: Restore the speech in a video, download the restored MP4, and stream the result in a browser with hls.js. You get: A restored MP4 and an HLS stream with the picture. Calls: Video upload → HLS stream](https://diffio.ai/docs/developers/guides/restore-video-and-stream/) - [Compare Flash and Pro: Restore one recording with both models, listen to them side by side, and see what each one cost. You get: Original, Flash and Pro side by side, with their cost. Calls: One project → two generations](https://diffio.ai/docs/developers/guides/compare-flash-and-pro/) - [Clean up a back catalogue: Restore every recording in a folder, a few at a time, pick up where a stopped run left off, and total what it used. You get: A restored copy of every file, and the run's usage. Calls: Folder → restores → usage](https://diffio.ai/docs/developers/guides/clean-up-a-back-catalogue/) - [Bill your users from usage: Read each customer's Diffio usage for a billing period and turn it into one line on their invoice. You get: One invoice line per customer. Calls: Usage per end user → invoice](https://diffio.ai/docs/developers/guides/bill-users-from-usage/) ## Before you start An API key in `DIFFIO_API_KEY` and the SDK (`pip install diffio` or `npm install diffio`): the [Quickstart](https://diffio.ai/docs/developers/quick-start/) covers both. The ideas behind the calls are in [Concepts](https://diffio.ai/docs/overview/concepts/projects-and-uploads/). --- Source: https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/ # Podcast cleanup in a SaaS app Your users upload episodes from the browser straight to Diffio, your server keeps the API key and each user's projects apart, and a signed webhook tells you when the cleaned audio is ready to play. ## How it works 1. Browser → Your server: `POST /api/uploads`, file name and size 2. Your server → Diffio API: `POST /projects`, Diffio-End-User from your session 3. Diffio API → Your server: `upload`, upload_token, upload.requests 4. Your server → Browser: `upload`, never the API key 5. Browser → Media host: `start, parts, complete`, Bearer upload_token 6. Browser → Your server: `POST …/{id}/complete`, your route 7. Your server → Diffio API: `POST …/upload/complete`, the restore starts 8. Diffio API → Your server: `generation.completed`, signed; matched to one job 9. Browser → Your server: `GET /api/uploads/{id}`, your route 10. Your server → Diffio API: `GET …/media`, as the signed-in user, 6 hour URLs **Solid arrows are requests and webhook deliveries; dashed arrows are answers.** ## Build it ### 1. Set up Install the SDK and a web framework. Set the API key, the endpoint's `whsec_` signing secret (step 4) and a session secret, on the server only. **Terminal** ```bash pip install diffio flask # Python npm install diffio express express-session # or Node.js export DIFFIO_API_KEY="diffio_..." export DIFFIO_WEBHOOK_SECRET="whsec_..." export SESSION_SECRET="..." ``` ### 2. Create the project for the signed-in user `create_upload` takes the user id from your session, never from the request body, and sends it as `Diffio-End-User`. `generation` queues the restore now; it starts once the file lands. The browser's `upload_key` becomes the `Idempotency-Key`, so a retried request returns the same project. The job row keeps the project, its first `generation_id` and the user. ### 3. Upload from the browser The server returns only `upload`. The browser follows `upload.requests` (start, parts, complete) with the `upload_token` as a bearer token; the media host accepts these four requests from any origin. The token is scoped to this one project's file and works for 24 hours (`upload.expires_at`); [POST .../upload](https://diffio.ai/docs/api-reference/reopen-project-upload/) gives a new one. Keep the `uploadKey` with the file: a retry with the same key gets the same project, and `upload: null` when its file already arrived. **upload.js (browser)** ```javascript // Runs in the browser: the file goes straight to Diffio's media host with the upload token. // Pass the same uploadKey when you retry the same file (keep it with the file, for example in sessionStorage), so a // retry after a lost answer reuses its project instead of creating another. export async function uploadEpisode(file, uploadKey) { const created = await fetch("/api/uploads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ upload_key: uploadKey, file_name: file.name, size_bytes: file.size }), }); if (!created.ok) throw new Error(`Could not start the upload (${created.status})`); const { project_id, upload } = await created.json(); if (upload) { // null: the file already arrived on an earlier try const { start, part, complete } = upload.requests; const send = async (request, url, body, headers = request.headers) => { const response = await fetch(url, { method: request.method, headers, body }); if (!response.ok) throw new Error(`Upload failed (${response.status})`); return response.json(); }; const { uploadId, partSizeBytes } = await send(start, start.url); const parts = []; for (let number = 1, offset = 0; offset < file.size; number += 1, offset += partSizeBytes) { const url = part.url.replace("{part_number}", number).replace("{upload_id}", encodeURIComponent(uploadId)); // The browser sets Content-Length itself; only the Authorization header is copied. const chunk = file.slice(offset, offset + partSizeBytes); const { etag } = await send(part, url, chunk, { Authorization: part.headers.Authorization }); parts.push({ partNumber: number, etag }); } await send(complete, complete.url, JSON.stringify({ uploadId, parts })); } const completed = await fetch(`/api/uploads/${project_id}/complete`, { method: "POST" }); // safe to repeat if (!completed.ok) throw new Error(`Could not finish the upload (${completed.status})`); return project_id; // poll GET /api/uploads/ until status is "complete" } ``` ### 4. Verify and record the webhook Open the portal with `python app.py portal` or `node app.mjs portal` (an account-wide client, no end user) and add `https://your-app.example/webhooks/diffio` for `generation.completed` and `generation.failed`. - **Verify**: the signature with the SDK, on the raw body. - **One transaction:**: record `event.id` (a repeat changes nothing) and update the job. - **Match the job**: on `data.id` = its `generation_id` and `data.end_user` = its user. A second restore or an edit of the same project, or another user's event, changes nothing. - **Answer `204` after the commit**, with no API calls in the delivery; an error answers 500 and the delivery is retried. Payloads and retries: [Webhooks](https://diffio.ai/docs/developers/webhooks/). ### 5. Fetch media on read `GET /api/uploads/` asks Diffio for media as the signed-in user once the job is complete, and again when the stored URL has less than 5 minutes of its 6 hours left. ### The complete server **Run it locally:** the [example folder](https://diffio.ai/docs/examples/saas-podcast-cleanup/README.md) adds a development sign-in for two users, a page with a file input and player, and a signed sample webhook, with the commands and results to expect. **app.py** ```python """Podcast cleanup in a SaaS app: browser uploads, one Diffio end user per customer, signed webhooks. python app.py serves on http://localhost:3000 python app.py portal prints a link to the webhook portal """ import os import sqlite3 import sys from datetime import datetime, timedelta, timezone from diffio import DiffioClient, WebhookVerificationError, verify_webhook_signature from flask import Flask, abort, g, jsonify, request, session DB_PATH = "podcasts.db" app = Flask(__name__) app.secret_key = os.environ["SESSION_SECRET"] # signs the session cookie your sign-in sets with sqlite3.connect(DB_PATH) as setup: setup.executescript(""" create table if not exists jobs ( project_id text primary key, user_id text not null, generation_id text not null, status text not null, error_code text, audio_url text, expires_at text); create table if not exists webhook_events (id text primary key, type text, created_at text); """) def db(): """One connection per request, so each delivery runs its own transaction.""" if "db" not in g: g.db = sqlite3.connect(DB_PATH, timeout=10) return g.db @app.teardown_appcontext def close_db(_error): if "db" in g: g.pop("db").close() def diffio_for(user_id): """A client that acts for one of your users: every call sends Diffio-End-User.""" return DiffioClient(end_user=user_id) def signed_in_user(): user_id = session.get("user_id") # set by your own sign-in, never by the request body if not user_id: abort(401) return user_id @app.post("/api/uploads") def create_upload(): user_id = signed_in_user() body = request.get_json() with diffio_for(user_id) as diffio: project = diffio.projects.create( file_name=body["file_name"], size_bytes=body["size_bytes"], generation={"model": "diffio-flash"}, # starts by itself once the file lands idempotency_key=f"upload-{body['upload_key']}", # a retried request gets the same project ) with db() as conn: conn.execute("insert or ignore into jobs (project_id, user_id, generation_id, status) values (?, ?, ?, ?)", (project.id, user_id, project.latest_generation.id, "processing")) # Only the upload descriptors go to the browser; the API key stays here. return jsonify(project_id=project.id, upload=project.upload.to_dict() if project.upload else None) @app.post("/api/uploads//complete") def complete_upload(project_id): with diffio_for(signed_in_user()) as diffio: project = diffio.projects.complete_upload(project_id) # 404 unless it is this user's project return jsonify(status=project.status) @app.get("/api/uploads/") def get_upload(project_id): user_id = signed_in_user() conn = db() job = conn.execute("select generation_id, status, error_code, audio_url, expires_at from jobs" " where project_id = ? and user_id = ?", (project_id, user_id)).fetchone() if job is None: abort(404) generation_id, status, error_code, audio_url, expires_at = job soon = datetime.now(timezone.utc) + timedelta(minutes=5) if status == "complete" and (not expires_at or datetime.fromisoformat(expires_at.replace("Z", "+00:00")) < soon): # Media is fetched here, on read: media URLs last 6 hours. with diffio_for(user_id) as diffio: media = diffio.generations.media(project_id, generation_id) audio_url, expires_at = media.files["audio"], media.expires_at with conn: conn.execute("update jobs set audio_url = ?, expires_at = ? where project_id = ?", (audio_url, expires_at, project_id)) return jsonify(status=status, error_code=error_code, audio_url=audio_url, expires_at=expires_at) @app.post("/webhooks/diffio") def diffio_webhook(): try: event = verify_webhook_signature(request.get_data(), request.headers, os.environ["DIFFIO_WEBHOOK_SECRET"]) except WebhookVerificationError: return "", 400 data = event.data with db() as conn: # one transaction: the receipt and the job update commit together, or neither does first = conn.execute("insert or ignore into webhook_events (id, type, created_at) values (?, ?, ?)", (event.id, event.type, event.created_at)).rowcount if first and event.type in ("generation.completed", "generation.failed"): # Only the job this generation started, for the user the event names. conn.execute("update jobs set status = ?, error_code = ?" " where project_id = ? and generation_id = ? and user_id = ?", ("complete" if event.type == "generation.completed" else "failed", data.error_code, data.project_id, data.id, data.end_user)) return "", 204 # after the commit; an exception above answers 500 and Svix retries if __name__ == "__main__": if sys.argv[1:] == ["portal"]: # The webhook portal belongs to the whole account: a client with no end user. account = DiffioClient() print(account.webhooks.portal().url) else: app.run(port=3000) ``` **app.mjs** ```javascript // Podcast cleanup in a SaaS app: browser uploads, one Diffio end user per customer, signed webhooks. // node app.mjs serves on http://localhost:3000 (Node 22.13 or later, for node:sqlite) // node app.mjs portal prints a link to the webhook portal import { DatabaseSync } from "node:sqlite"; import express from "express"; import session from "express-session"; import { DiffioClient, DiffioWebhookVerificationError, verifyWebhookSignature } from "diffio"; const db = new DatabaseSync("podcasts.db"); db.exec(` create table if not exists jobs ( project_id text primary key, user_id text not null, generation_id text not null, status text not null, error_code text, audio_url text, expires_at text); create table if not exists webhook_events (id text primary key, type text, created_at text); `); // A client that acts for one of your users: every call sends Diffio-End-User. const diffioFor = (userId) => new DiffioClient({ endUser: userId }); if (process.argv[2] === "portal") { // The webhook portal belongs to the whole account: a client with no end user. const account = new DiffioClient(); console.log((await account.webhooks.portal()).url); process.exit(0); } const app = express(); // Registered before express.json(): the signature covers the raw body. app.post("/webhooks/diffio", express.raw({ type: "*/*" }), (req, res) => { let event; try { event = verifyWebhookSignature(req.body, req.headers, process.env.DIFFIO_WEBHOOK_SECRET); } catch (error) { if (error instanceof DiffioWebhookVerificationError) return res.sendStatus(400); throw error; } const { data } = event; // One transaction: the receipt and the job update commit together, or neither does. node:sqlite is // synchronous, so no other delivery runs between begin and commit. db.exec("begin immediate"); try { const { changes } = db.prepare("insert or ignore into webhook_events (id, type, created_at) values (?, ?, ?)") .run(event.id, event.type, event.created_at); if (changes && (event.type === "generation.completed" || event.type === "generation.failed")) { // Only the job this generation started, for the user the event names. db.prepare("update jobs set status = ?, error_code = ? where project_id = ? and generation_id = ? and user_id = ?") .run(event.type === "generation.completed" ? "complete" : "failed", data.error_code ?? null, data.project_id, data.id, data.end_user ?? null); } db.exec("commit"); } catch (error) { db.exec("rollback"); throw error; // answers 500, and Svix retries } res.sendStatus(204); // after the commit }); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false })); app.use(express.json()); // Your own sign-in sets req.session.userId; the request body never names the user. function signedInUser(req) { if (!req.session.userId) throw Object.assign(new Error("Sign in first"), { status: 401 }); return req.session.userId; } app.post("/api/uploads", async (req, res) => { const userId = signedInUser(req); const { upload_key, file_name, size_bytes } = req.body; const project = await diffioFor(userId).projects.create( { file_name, size_bytes, generation: { model: "diffio-flash" } }, // starts by itself once the file lands { idempotencyKey: `upload-${upload_key}` } // a retried request gets the same project ); db.prepare("insert or ignore into jobs (project_id, user_id, generation_id, status) values (?, ?, ?, 'processing')") .run(project.id, userId, project.latest_generation.id); // Only the upload descriptors go to the browser; the API key stays here. res.json({ project_id: project.id, upload: project.upload }); }); app.post("/api/uploads/:projectId/complete", async (req, res) => { // 404 unless it is this user's project. const project = await diffioFor(signedInUser(req)).projects.completeUpload(req.params.projectId); res.json({ status: project.status }); }); app.get("/api/uploads/:projectId", async (req, res) => { const userId = signedInUser(req); const job = db.prepare("select * from jobs where project_id = ? and user_id = ?").get(req.params.projectId, userId); if (!job) return res.sendStatus(404); if (job.status === "complete" && !(Date.parse(job.expires_at) > Date.now() + 5 * 60_000)) { // Media is fetched here, on read: media URLs last 6 hours. const media = await diffioFor(userId).generations.media(job.project_id, job.generation_id); [job.audio_url, job.expires_at] = [media.files.audio, media.expires_at]; db.prepare("update jobs set audio_url = ?, expires_at = ? where project_id = ?") .run(job.audio_url, job.expires_at, job.project_id); } res.json({ status: job.status, error_code: job.error_code, audio_url: job.audio_url, expires_at: job.expires_at }); }); app.listen(3000); ``` ## What you get ![A finished Diffio project: the project title, the restored waveform, the play control, the Restored switch and the Background amount slider](https://diffio.ai/media/recording-rescue/flash-result-mobile-stack.jpg) Uploaded [Uploaded (MP3)](https://diffio.ai/media/recording-rescue/original.mp3) Restored by Diffio 4.7 Flash [Restored by Diffio 4.7 Flash (MP3)](https://diffio.ai/media/recording-rescue/flash.mp3) **What a user uploads and gets back: the first 60 seconds of an archival lecture, and the finished project in the Diffio app. [How this recording was restored](https://diffio.ai/recording-rescue/).** - Each customer's projects live under their own end user: another customer's project id answers `404`. - Files go from the browser to Diffio; your server never handles the audio. - A restored MP3 URL for each finished episode, renewed before its 6 hours run out. **Response of `GET /api/uploads/`** **JSON** ```json { "status": "complete", "error_code": null, "audio_url": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/restored.mp3", "expires_at": "2026-11-13T06:33:47Z" } ``` ## API reference - POST [Create a project](https://diffio.ai/docs/api-reference/create-project/) (`/projects`): Project, first generation and upload descriptors. - POST [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/) (`/projects/{project_id}/upload`): A new upload token when the old one expired. - POST [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/) (`/projects/{project_id}/upload/complete`): Check the file now instead of waiting. - GET [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) (`/projects/{project_id}/generations/{generation_id}/media`): Fresh playback and download URLs. - POST [Open the webhook portal](https://diffio.ai/docs/api-reference/open-webhook-portal/) (`/webhooks/portal`): Add endpoints and copy the signing secret. ## Related pages - Previous: [Bill your users from usage](https://diffio.ai/docs/developers/guides/bill-users-from-usage/): Usage per end user → invoice - Next: [Edit a transcript](https://diffio.ai/docs/developers/guides/edit-transcript/): Transcript → estimate → edit --- Source: https://diffio.ai/docs/developers/guides/edit-transcript/ # Edit a transcript and re-render the audio Change a word in a Pro result's transcript and get back the whole recording with the new word said in the same voice. ## How it works 1. Your code → Diffio API: `POST /projects`, model diffio-pro 2. Diffio API → Your code: `generation complete`, transcript_editable: true 3. Your code → Diffio API: `GET …/transcript`, words with id, text, start, end 4. Your code: `change words`, text, changed: true 5. Your code → Diffio API: `POST …/edits/estimate`, max_billable_seconds 6. Your code → Diffio API: `POST …/edits`, Idempotency-Key 7. Diffio API → Your code: `generation, kind "edit"`, complete (or generation.completed) 8. Your code → Diffio API: `GET …/media`, files.audio of the edit **One changed word restores one window; the rest of the recording is kept as it was.** ## Build it ### 1. Restore with Pro Only a finished `diffio-pro` result can be edited (`transcript_editable` is true). The transcript can arrive a moment after the audio: wait while `transcription_status` is `preparing`, for a bounded time, and show the generation's `error` when it fails. ### 2. Change the words Read the transcript and send every word back, in order. Change a word's `text` and mark it `changed`; `text: ""` removes a word. ### 3. Estimate first `edits.estimate` creates and bills nothing. Each restored window bills 30 seconds; `max_billable_seconds` is the most this edit can bill. ### 4. Create the edit and wait The edit is a new generation with `kind: "edit"`; only the windows around changed words are restored again. A fixed `Idempotency-Key` makes a retry return the same edit and bill it once. ### 5. Download the edited recording The edit's media is the whole recording with the new words in it. ### The complete script Put `interview.mp3` next to it and name the word to replace and its replacement. **edit.py** ```python """Restore interview.mp3 with Pro, replace one word in its transcript, and save the re-rendered audio. python edit.py Tuesday Thursday """ import sys import time from diffio import DiffioClient, DiffioTimeoutError, GenerationFailedError old_word, new_word = sys.argv[1], sys.argv[2] client = DiffioClient() # reads DIFFIO_API_KEY # 1. A finished Pro result, and its transcript (bounded waits). try: result = client.restore_audio("interview.mp3", model="diffio-pro", output_path="interview-restored.mp3", timeout=1800) except (GenerationFailedError, DiffioTimeoutError) as error: sys.exit(f"restore did not finish: {error}") project_id, generation = result.project.id, result.generation deadline = time.monotonic() + 300 while generation.transcription_status == "preparing" and time.monotonic() < deadline: time.sleep(2) generation = client.generations.get(project_id, generation.id) if generation.transcription_status != "ready" or not generation.transcript_editable: sys.exit(f"{generation.id} cannot be edited (transcription_status {generation.transcription_status}, " f"error {generation.error.to_dict() if generation.error else None})") # 2. Every word goes back; only the replaced ones change. transcript = client.transcripts.get(project_id, generation.id) words = [word.to_dict() for word in transcript.words] changed = 0 for word in words: core = word["text"].strip().rstrip(".,?!") if core.lower() == old_word.lower(): word["text"] = word["text"].replace(core, new_word) word["changed"] = True # said again in the same voice changed += 1 if not changed: sys.exit(f'"{old_word}" is not in the transcript') # 3. The most it can bill, before anything runs. estimate = client.edits.estimate(project_id, generation.id, words=words) print(f"{estimate.edit_count} change(s), at most {estimate.max_billable_seconds} billable seconds") # 4. The edit is a new generation; the same key never creates or bills it twice. edit = client.edits.create(project_id, generation.id, words=words, idempotency_key=f"edit-{generation.id}") try: finished = client.generations.wait(project_id, edit.id, timeout=1800) except GenerationFailedError as error: sys.exit(f"edit failed: {error.message}") # the message ends with (code) except DiffioTimeoutError: sys.exit(f"edit {edit.id} still running after 30 minutes") # 5. The whole recording with the new word. saved = client.generations.download(project_id, finished.id, path="interview-edited.mp3") print("saved", saved, "from generation", finished.id, "kind", finished.kind) ``` **edit.mjs** ```javascript // Restore interview.mp3 with Pro, replace one word in its transcript, and save the re-rendered audio. // node edit.mjs Tuesday Thursday import { setTimeout as sleep } from "node:timers/promises"; import { DiffioClient, DiffioResourceFailedError } from "diffio"; const [oldWord, newWord] = process.argv.slice(2); const client = new DiffioClient(); // reads DIFFIO_API_KEY // 1. A finished Pro result, and its transcript (bounded waits; a failure throws with its error code). const result = await client.restoreAudio({ file: "interview.mp3", model: "diffio-pro", outputPath: "interview-restored.mp3", timeout: 1800 }); const projectId = result.project.id; let generation = result.generation; const deadline = Date.now() + 300_000; while (generation.transcription_status === "preparing" && Date.now() < deadline) { await sleep(2000); generation = await client.generations.get(projectId, generation.id); } if (generation.transcription_status !== "ready" || !generation.transcript_editable) { throw new Error( `${generation.id} cannot be edited (transcription_status ${generation.transcription_status}, error ${JSON.stringify(generation.error)})` ); } // 2. Every word goes back; only the replaced ones change. const transcript = await client.transcripts.get(projectId, generation.id); let changed = 0; const words = transcript.words.map((word) => { const core = word.text.trim().replace(/[.,?!]+$/, ""); if (core.toLowerCase() !== oldWord.toLowerCase()) return word; changed += 1; return { ...word, text: word.text.replace(core, newWord), changed: true }; // said again in the same voice }); if (!changed) throw new Error(`"${oldWord}" is not in the transcript`); // 3. The most it can bill, before anything runs. const estimate = await client.edits.estimate(projectId, generation.id, { words }); console.log(`${estimate.edit_count} change(s), at most ${estimate.max_billable_seconds} billable seconds`); // 4. The edit is a new generation; the same key never creates or bills it twice. const edit = await client.edits.create(projectId, generation.id, { words }, { idempotencyKey: `edit-${generation.id}` }); let finished; try { finished = await client.generations.wait(projectId, edit.id, { timeout: 1800 }); // DiffioTimeoutError after 30 minutes } catch (error) { if (error instanceof DiffioResourceFailedError) throw new Error(`edit failed: ${error.code}: ${error.message}`); throw error; } // 5. The whole recording with the new word. const download = await client.generations.download(projectId, finished.id, { path: "interview-edited.mp3" }); console.log("saved", download.path, "from generation", finished.id, "kind", finished.kind); ``` ## What you get on the ground of scientific historical (changed: true) evidence, or in the end on the ground of any evidence whatever. **Words from the [Recording rescue](https://diffio.ai/recording-rescue/) lecture as an edit sends them: every word in order, one replaced and marked `changed`. Only the window around it is restored again.** - `interview-restored.mp3`: the Pro restore. - `interview-edited.mp3`: the same recording with the word replaced, from a generation of `kind` `edit`. **Output of `python edit.py Tuesday Thursday`** **Terminal** ```bash 1 change(s), at most 30 billable seconds saved interview-edited.mp3 from generation 9d1f4c2a-5b7e-5c3d-8a6f-2e4b1c0d9f87 kind edit ``` ## API reference - GET [Get a generation's transcript](https://diffio.ai/docs/api-reference/get-transcript/) (`/projects/{project_id}/generations/{generation_id}/transcript`): Words with ids and timings. - POST [Estimate a transcript edit](https://diffio.ai/docs/api-reference/estimate-transcript-edit/) (`/projects/{project_id}/generations/{generation_id}/edits/estimate`): The most an edit can bill. - POST [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/) (`/projects/{project_id}/generations/{generation_id}/edits`): Word fields, refusals and billing. - GET [Get a generation](https://diffio.ai/docs/api-reference/get-generation/) (`/projects/{project_id}/generations/{generation_id}`): Status and progress of the edit. - GET [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) (`/projects/{project_id}/generations/{generation_id}/media`): The edited files. ## Related pages - Previous: [Podcast cleanup in a SaaS app](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/): Browser upload → webhook → player - Next: [Let users edit by asking](https://diffio.ai/docs/developers/guides/edit-by-asking/): Ask → proposals → edit --- Source: https://diffio.ai/docs/developers/guides/edit-by-asking/ # Let users edit by asking Let people ask for changes in plain words, show the assistant's proposals, and turn the one they accept into an edit. ## How it works 1. Person → Your app: `"Remove the filler words"` 2. Your app → Diffio API: `POST …/assistant/turns`, messages; 202 processing 3. Your app → Diffio API: `GET …/assistant/turns/{id}`, until complete 4. Diffio API → Your app: `reply, proposals, moments` 5. Your app → Diffio API: `POST …/edits/estimate`, once per proposal 6. Your app → Person: `proposals and estimates` 7. Person → Your app: `accept p1` 8. Your app → Diffio API: `POST …/edits`, the accepted words 9. Your app → Diffio API: `POST …/assistant/feedback`, optional, over HTTP **Proposals change nothing until your app creates an edit with the words the person accepted.** ## Build it ### 1. Ask a turn Send the chat so far in `messages` (1 to 40 `{role, content}`, the question last). Leave `words` out to ask about the stored transcript, or send your editor's words as they stand. It works on finished `diffio-pro` results and answers `202` with `status: "processing"`. ### 2. Poll until it answers Read the turn every second or two; it can take a few minutes, because it may listen to the audio. A turn still running after 600 seconds ends `failed` with `assistant_timeout`; the `transcript_assistant_turn.completed` webhook also tells you. ### 3. Show the reply, proposals and moments `reply` is for the person. Each proposal has a `title` and `changes` (`kind`, `word_ids`, `before`, `after`); `moments` are times to jump to. Nothing changes the audio yet. ### 4. Estimate each, apply the one the person accepts Accepting a change gives its first word the `after` text (whitespace collapsed) and removes the rest (`regenerate` flags the words instead), the same rule the assistant uses. The script previews every proposal with its estimate and creates an [edit](https://diffio.ai/docs/developers/guides/edit-transcript/) only for the proposal named with `--apply`. ### 5. Send feedback (HTTP) A report about the assistant goes to Diffio with `POST …/assistant/feedback`. The SDKs have no helper for it yet, so the script calls it over HTTP. Up to 10 reports an hour per end user. ### The complete script Ask with a question to preview; apply with `--turn` and `--apply`; add `--feedback "a note"` to either to send feedback. **assistant.py** ```python """Ask the edit assistant about a Pro result, preview its proposals, and apply the one you name. python assistant.py PROJECT_ID GENERATION_ID "Remove the filler words" # ask and preview python assistant.py PROJECT_ID GENERATION_ID --turn TURN_ID --apply p1 # apply proposal p1 of that turn Add --feedback "a note for the Diffio team" to either. """ import argparse import sys import httpx from diffio import AssistantTurnFailedError, DiffioClient parser = argparse.ArgumentParser() parser.add_argument("project_id") parser.add_argument("generation_id") parser.add_argument("question", nargs="?") parser.add_argument("--turn", help="an earlier turn to read instead of asking") parser.add_argument("--apply", metavar="PROPOSAL_ID", help="create the edit for this proposal") parser.add_argument("--feedback", help="send this note to the Diffio team") args = parser.parse_args() if not args.question and not args.turn: parser.error("ask a question, or pass --turn") client = DiffioClient() # reads DIFFIO_API_KEY project_id, generation_id = args.project_id, args.generation_id # 1. Ask (or read an earlier turn), then poll for at most 10 minutes. turn_id = args.turn or client.assistant.create_turn( project_id, generation_id, messages=[{"role": "user", "content": args.question}]).id try: turn = client.assistant.wait_turn(project_id, generation_id, turn_id, timeout=600) except AssistantTurnFailedError as error: sys.exit(f"the assistant could not answer: {error.message}") # the message ends with (code) # 2. A proposal accepted: the first word of a change takes "after", the rest are removed. transcript_words = [word.to_dict() for word in client.transcripts.get(project_id, generation_id).words] def accepted(proposal): words = {word["id"]: dict(word) for word in transcript_words} # a fresh copy, in the transcript's order for change in proposal["changes"]: if change["kind"] == "regenerate": for word_id in change["word_ids"]: words[word_id]["regenerate"] = True continue first, *rest = change["word_ids"] words[first].update(text=" ".join(change["after"].split()), changed=True) # whitespace as the server reads it for word_id in rest: words[word_id].update(text="", changed=True) return list(words.values()) # 3. Preview: what the person sees, and what each proposal would bill at most. print("turn", turn.id) print("reply:", turn.reply) for moment in turn.moments or []: print(f"moment {moment['start_seconds']:.1f}s: {moment['label']}") for proposal in turn.proposals or []: estimate = client.edits.estimate(project_id, generation_id, words=accepted(proposal)) print(f"proposal {proposal['id']}: {proposal['title']} (at most {estimate.max_billable_seconds} billable seconds)") for change in proposal["changes"]: print(f" {change['kind']}: {change['before']!r} -> {change['after']!r}") # 4. Apply only the proposal the person accepted. if args.apply: proposal = next((item for item in turn.proposals or [] if item["id"] == args.apply), None) if proposal is None: sys.exit(f"turn {turn.id} has no proposal {args.apply}") edit = client.edits.create(project_id, generation_id, words=accepted(proposal), idempotency_key=f"assistant-{turn.id}-{proposal['id']}") finished = client.generations.wait(project_id, edit.id, timeout=1800) client.generations.download(project_id, finished.id, path="interview-assistant.mp3") print(f"applied {proposal['id']}: saved interview-assistant.mp3") elif turn.proposals: print(f"to apply one: python assistant.py {project_id} {generation_id} --turn {turn.id} --apply ") # 5. Feedback has no SDK helper yet: POST it over HTTP. if args.feedback: response = httpx.post( f"{client.base_url}/projects/{project_id}/generations/{generation_id}/transcript/assistant/feedback", headers={"Authorization": f"Bearer {client.api_key}"}, json={"kind": "other", "message": args.feedback, "turn_id": turn.id}, timeout=30, ) print("feedback:", response.status_code, response.json()) ``` **assistant.mjs** ```javascript // Ask the edit assistant about a Pro result, preview its proposals, and apply the one you name. // node assistant.mjs PROJECT_ID GENERATION_ID "Remove the filler words" # ask and preview // node assistant.mjs PROJECT_ID GENERATION_ID --turn TURN_ID --apply p1 # apply proposal p1 of that turn // Add --feedback "a note for the Diffio team" to either. import { parseArgs } from "node:util"; import { DiffioClient, DiffioResourceFailedError } from "diffio"; const { values: args, positionals } = parseArgs({ allowPositionals: true, options: { turn: { type: "string" }, apply: { type: "string" }, feedback: { type: "string" } } }); const [projectId, generationId, question] = positionals; if (!question && !args.turn) throw new Error("Ask a question, or pass --turn"); const client = new DiffioClient(); // reads DIFFIO_API_KEY // 1. Ask (or read an earlier turn), then poll for at most 10 minutes. const turnId = args.turn ?? (await client.assistant.createTurn(projectId, generationId, { messages: [{ role: "user", content: question }] })).id; let turn; try { turn = await client.assistant.waitTurn(projectId, generationId, turnId, { timeout: 600 }); } catch (error) { if (error instanceof DiffioResourceFailedError) throw new Error(`The assistant could not answer: ${error.code}: ${error.message}`); throw error; } // 2. A proposal accepted: the first word of a change takes "after", the rest are removed. const transcriptWords = (await client.transcripts.get(projectId, generationId)).words; function accepted(proposal) { const words = new Map(transcriptWords.map((word) => [word.id, { ...word }])); // a fresh copy, in order for (const change of proposal.changes) { if (change.kind === "regenerate") { for (const id of change.word_ids) words.get(id).regenerate = true; continue; } const [first, ...rest] = change.word_ids; const after = change.after.trim().split(/\s+/).filter(Boolean).join(" "); // whitespace as the server reads it Object.assign(words.get(first), { text: after, changed: true }); for (const id of rest) Object.assign(words.get(id), { text: "", changed: true }); } return [...words.values()]; } // 3. Preview: what the person sees, and what each proposal would bill at most. console.log("turn", turn.id); console.log("reply:", turn.reply); for (const moment of turn.moments ?? []) console.log(`moment ${moment.start_seconds.toFixed(1)}s: ${moment.label}`); for (const proposal of turn.proposals ?? []) { const estimate = await client.edits.estimate(projectId, generationId, { words: accepted(proposal) }); console.log(`proposal ${proposal.id}: ${proposal.title} (at most ${estimate.max_billable_seconds} billable seconds)`); for (const change of proposal.changes) console.log(` ${change.kind}: "${change.before}" -> "${change.after}"`); } // 4. Apply only the proposal the person accepted. if (args.apply) { const proposal = (turn.proposals ?? []).find((item) => item.id === args.apply); if (!proposal) throw new Error(`Turn ${turn.id} has no proposal ${args.apply}`); const edit = await client.edits.create(projectId, generationId, { words: accepted(proposal) }, { idempotencyKey: `assistant-${turn.id}-${proposal.id}` }); const finished = await client.generations.wait(projectId, edit.id, { timeout: 1800 }); await client.generations.download(projectId, finished.id, { path: "interview-assistant.mp3" }); console.log(`applied ${proposal.id}: saved interview-assistant.mp3`); } else if (turn.proposals?.length) { console.log(`to apply one: node assistant.mjs ${projectId} ${generationId} --turn ${turn.id} --apply `); } // 5. Feedback has no SDK helper yet: POST it over HTTP. if (args.feedback) { const response = await fetch(`${await client.baseUrl()}/projects/${projectId}/generations/${generationId}/transcript/assistant/feedback`, { method: "POST", headers: { Authorization: `Bearer ${process.env.DIFFIO_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ kind: "other", message: args.feedback, turn_id: turn.id }), signal: AbortSignal.timeout(30_000) }); console.log("feedback:", response.status, await response.json()); } ``` ## What you get | Limit | Value | | --- | --- | | Turns | 30 per 10 minutes, plus a daily usage cap; over either, the turn ends `failed` with `rate_limited` | | A turn's run | `failed` with `assistant_timeout` after 600 seconds | | `messages` | 1 to 40, the question last | | `reply`, `moments` | up to 1,200 characters; up to 8 moments | | Feedback | 10 reports per hour; `message` up to 4,000 characters | - The assistant's reply, its proposals and the moments it points to, ready to show in your editor. - Each proposal's estimate before anything is billed, and the accepted one as an edit: `interview-assistant.mp3`. **Output of a preview, then `--apply p1`** **Terminal** ```bash $ python assistant.py 62f62565-... ce832a32-... "Remove the filler words" turn 8f14e45fceea4e6b9d2c7a1b3e5d9f02 reply: I found two filler words and grouped them into one proposal. moment 12.4s: "um" before the main point proposal p1: Remove filler words (at most 30 billable seconds) remove: 'um' -> '' remove: 'you know' -> '' to apply one: python assistant.py 62f62565-... ce832a32-... --turn 8f14e45fceea4e6b9d2c7a1b3e5d9f02 --apply $ python assistant.py 62f62565-... ce832a32-... --turn 8f14e45fceea4e6b9d2c7a1b3e5d9f02 --apply p1 turn 8f14e45fceea4e6b9d2c7a1b3e5d9f02 reply: I found two filler words and grouped them into one proposal. moment 12.4s: "um" before the main point proposal p1: Remove filler words (at most 30 billable seconds) remove: 'um' -> '' remove: 'you know' -> '' applied p1: saved interview-assistant.mp3 ``` ## API reference - POST [Ask the edit assistant](https://diffio.ai/docs/api-reference/create-transcript-assistant-turn/) (`/projects/{project_id}/generations/{generation_id}/transcript/assistant/turns`): Ask; refusals and turn error codes. - GET [Get an edit assistant turn](https://diffio.ai/docs/api-reference/get-transcript-assistant-turn/) (`/projects/{project_id}/generations/{generation_id}/transcript/assistant/turns/{turn_id}`): reply, proposals, moments and the rest. - POST [Estimate a transcript edit](https://diffio.ai/docs/api-reference/estimate-transcript-edit/) (`/projects/{project_id}/generations/{generation_id}/edits/estimate`): The most the edit can bill. - POST [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/) (`/projects/{project_id}/generations/{generation_id}/edits`): Restore the accepted changes. - POST [Send assistant feedback](https://diffio.ai/docs/api-reference/create-transcript-assistant-feedback/) (`/projects/{project_id}/generations/{generation_id}/transcript/assistant/feedback`): Report a bug or an idea. ## Related pages - Previous: [Edit a transcript](https://diffio.ai/docs/developers/guides/edit-transcript/): Transcript → estimate → edit - Next: [Separate speech and background](https://diffio.ai/docs/developers/guides/separate-speech-and-background/): Stems → mix → export --- Source: https://diffio.ai/docs/developers/guides/separate-speech-and-background/ # Separate speech and background Turn the background down under the restored speech, save that balance, and download it as an MP3. ## How it works 1. Your code → Diffio API: `POST /projects`, restore, then wait for complete 2. Diffio API → Your code: `stems_status: "ready"`, or generation.stems_ready 3. Your code → Diffio API: `GET …/mix`, revision 4. Your code → Diffio API: `PUT …/mix`, background_gain 0.2, revision 5. Your code → Diffio API: `POST …/exports`, artifact mix, format mp3 6. Diffio API → Your code: `status: "ready"`, or export.ready, with url 7. Your code: `download url`, interview-mix.mp3 **Speech and background are separate tracks; a mix and an export only change how they are combined.** ## Build it ### 1. Restore the recording Any finished restore. The separated speech and background tracks are made from it. ### 2. Wait for the separated tracks The tracks can finish after the restore. Poll until `stems_status` is `ready`, or act on the `generation.stems_ready` webhook (`generation.stems_failed` when they never will be). ### 3. Save the balance `background_gain` runs from `0` (speech only) to `1` (all of the background). Read the mix first and send its `revision`: if someone saved since, the save is refused with `409` `revision_conflict` ([Errors](https://diffio.ai/docs/api-reference/errors/)); read again and decide. ### 4. Render an export and wait A `mix` export without `background_gain` uses the saved balance. Other recipes: `speech` or `background` alone, or `both` as a zip. Wait for `status: "ready"` or the `export.ready` webhook. Asking for the same recipe again returns the same export. ### 5. Download it A ready export carries a download `url`; `GET …/exports/{export_id}` gives a fresh one later. ### The complete script **tracks.py** ```python """Restore interview.mp3, turn its background down to 20%, and save that mix as an MP3. python tracks.py """ import sys import time import urllib.request from diffio import DiffioApiError, DiffioClient client = DiffioClient() # reads DIFFIO_API_KEY # 1. A finished restore. result = client.restore_audio("interview.mp3", output_path="interview-restored.mp3") project_id, generation = result.project.id, result.generation # 2. The separated tracks can finish after the restore. deadline = time.monotonic() + 600 while generation.stems_status != "ready": if generation.stems_status == "failed" or time.monotonic() > deadline: raise SystemExit(f"No separated tracks (stems_status {generation.stems_status})") time.sleep(3) generation = client.generations.get(project_id, generation.id) # 3. Save the balance (0 is speech only, 1 keeps all of the background) on the mix you read. current = client.mix.get(project_id, generation.id) try: mix = client.mix.save(project_id, generation.id, background_gain=0.2, revision=current.revision) except DiffioApiError as error: if error.code != "revision_conflict": raise sys.exit(f"Someone saved the mix since you read it (now {error.details}); read it again first") print("saved mix", mix.background_gain, "revision", mix.revision) # 4. Render the saved mix as an MP3 and wait for it. rendered = client.exports.create(project_id, generation.id, artifact="mix", format="mp3") rendered = client.exports.wait(project_id, generation.id, rendered.id) # 5. Download it. urllib.request.urlretrieve(rendered.url, "interview-mix.mp3") print("saved interview-mix.mp3 from export", rendered.id) ``` **tracks.mjs** ```javascript // Restore interview.mp3, turn its background down to 20%, and save that mix as an MP3. // node tracks.mjs import { writeFile } from "node:fs/promises"; import { setTimeout as sleep } from "node:timers/promises"; import { DiffioApiError, DiffioClient } from "diffio"; const client = new DiffioClient(); // reads DIFFIO_API_KEY // 1. A finished restore. const result = await client.restoreAudio({ file: "interview.mp3", outputPath: "interview-restored.mp3" }); const projectId = result.project.id; let generation = result.generation; // 2. The separated tracks can finish after the restore. const deadline = Date.now() + 600_000; while (generation.stems_status !== "ready") { if (generation.stems_status === "failed" || Date.now() > deadline) { throw new Error(`No separated tracks (stems_status ${generation.stems_status})`); } await sleep(3000); generation = await client.generations.get(projectId, generation.id); } // 3. Save the balance (0 is speech only, 1 keeps all of the background) on the mix you read. const current = await client.mix.get(projectId, generation.id); let mix; try { mix = await client.mix.save(projectId, generation.id, { background_gain: 0.2, revision: current.revision }); } catch (error) { if (error instanceof DiffioApiError && error.code === "revision_conflict") { throw new Error(`Someone saved the mix since you read it (${JSON.stringify(error.details)}); read it again first`); } throw error; } console.log("saved mix", mix.background_gain, "revision", mix.revision); // 4. Render the saved mix as an MP3 and wait for it. let rendered = await client.exports.create(projectId, generation.id, { artifact: "mix", format: "mp3" }); rendered = await client.exports.wait(projectId, generation.id, rendered.id); // 5. Download it. const response = await fetch(rendered.url); if (!response.ok) throw new Error(`Download failed (${response.status})`); await writeFile("interview-mix.mp3", Buffer.from(await response.arrayBuffer())); console.log("saved interview-mix.mp3 from export", rendered.id); ``` ## What you get As uploaded [As uploaded (MP3)](https://diffio.ai/media/remove-background-noise-from-video/outdoor-wind-original.mp3) Speech track (background_gain 0) [Speech track (background_gain 0) (MP3)](https://diffio.ai/media/remove-background-noise-from-video/outdoor-wind-speech.mp3) Background track [Background track (MP3)](https://diffio.ai/media/remove-background-noise-from-video/outdoor-wind-background.mp3) **An outdoor interview with wind across the mic, split by Diffio 4.7 Pro into its two tracks; a mix is any balance of the two. [The clip and its credit](https://diffio.ai/remove-background-noise-from-video/).** - `interview-restored.mp3`: the restored speech. - `interview-mix.mp3`: the speech with 20% of the background under it. - The saved balance on the generation, for the next export or your own player. **Output of `python tracks.py`** **Terminal** ```bash saved mix 0.2 revision 4014a8c299444bbb866971bbb7b657ca:1 saved interview-mix.mp3 from export 7c2e9b41d0a84f6e9a3b5c1d2e8f4a60 ``` ## API reference - GET [Get a generation](https://diffio.ai/docs/api-reference/get-generation/) (`/projects/{project_id}/generations/{generation_id}`): stems_status of the restore. - GET [Get the saved mix](https://diffio.ai/docs/api-reference/get-generation-mix/) (`/projects/{project_id}/generations/{generation_id}/mix`): The saved balance and its revision. - PUT [Save the mix](https://diffio.ai/docs/api-reference/save-generation-mix/) (`/projects/{project_id}/generations/{generation_id}/mix`): Save background_gain and leveling. - POST [Create an export](https://diffio.ai/docs/api-reference/create-generation-export/) (`/projects/{project_id}/generations/{generation_id}/exports`): Artifacts, formats and limits. - GET [Get an export](https://diffio.ai/docs/api-reference/get-generation-export/) (`/projects/{project_id}/generations/{generation_id}/exports/{export_id}`): Export status and a fresh url. ## Related pages - Previous: [Let users edit by asking](https://diffio.ai/docs/developers/guides/edit-by-asking/): Ask → proposals → edit - Next: [Share a restored result](https://diffio.ai/docs/developers/guides/share-a-result/): Publish → public read → revoke --- Source: https://diffio.ai/docs/developers/guides/share-a-result/ # Share a restored result with a public link Give anyone a link that plays a restored recording, read it from a public page without an API key, and turn it off when you are done. ## How it works 1. Your server → Diffio API: `PUT /projects/{id}/share`, API key 2. Diffio API → Your server: `share id`, and playback files 3. Your server → Listener: `link with the share id`, your page, your domain 4. Listener → Diffio API: `GET /shares/{share_id}`, no API key 5. Diffio API → Listener: `files.audio, files.hls_master`, current URLs 6. Your server → Diffio API: `DELETE /projects/{id}/share`, URLs stop within a minute **The share id is the only thing a listener holds; your API key never leaves your server.** ## Build it ### 1. Publish the share The share plays the project's newest finished generation, or the one you pin with `generation_id`. `preview_seconds` limits it to the start of the recording. Publishing again keeps the same share `id`. ### 2. Read it with no API key `GET /shares/{share_id}` needs no key and allows any origin, so a public page can call it directly. Read it each time a listener opens the page; it answers with current URLs. It never includes the uploaded original. **listen.html (public page)** ```html Listen ``` ### 3. Revoke it After a revoke the share id answers `404` `share_not_found`, and URLs it gave out stop working within about a minute. Publishing again later never revives an old URL. ### The complete script Pass the id of a project with a finished generation. **share.py** ```python """Publish a share of a finished project, read it the way a public page does, then revoke it. python share.py PROJECT_ID """ import sys from diffio import DiffioApiError, DiffioClient project_id = sys.argv[1] client = DiffioClient() # reads DIFFIO_API_KEY # 1. Publish: plays the project's newest finished generation. share = client.shares.publish(project_id) print("share id", share.id) # 2. The public read: GET /shares/{share_id}, sent without the API key. public = client.shares.get_public(share.id) print("plays", public.files["audio"]) # 3. Revoke, then the share id no longer resolves. client.shares.revoke(project_id) try: client.shares.get_public(share.id) except DiffioApiError as error: print("after revoke", error.status, error.code) ``` **share.mjs** ```javascript // Publish a share of a finished project, read it the way a public page does, then revoke it. // node share.mjs PROJECT_ID import { DiffioApiError, DiffioClient } from "diffio"; const projectId = process.argv[2]; const client = new DiffioClient(); // reads DIFFIO_API_KEY // 1. Publish: plays the project's newest finished generation. const share = await client.shares.publish(projectId); console.log("share id", share.id); // 2. The public read: GET /shares/{share_id}, sent without the API key. const shown = await client.shares.getPublic(share.id); console.log("plays", shown.files.audio); // 3. Revoke, then the share id no longer resolves. await client.shares.revoke(projectId); try { await client.shares.getPublic(share.id); } catch (error) { if (!(error instanceof DiffioApiError)) throw error; console.log("after revoke", error.status, error.code); } ``` **cURL: share.sh** ```bash API="https://api.diffio.ai/v2" PROJECT_ID="$1" CURL="curl -sS --connect-timeout 10 --max-time 60" # 1. Publish (with your key). SHARE_ID=$($CURL -X PUT "$API/projects/$PROJECT_ID/share" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Content-Type: application/json" -d '{}' | jq -r .id) # 2. The public read: no Authorization header. $CURL "$API/shares/$SHARE_ID" | jq -r .files.audio # 3. Revoke (with your key). $CURL -X DELETE "$API/projects/$PROJECT_ID/share" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## What you get Uploaded [Uploaded (MP3)](https://diffio.ai/media/recording-rescue/original.mp3) What the share link plays (files.audio) [What the share link plays (files.audio) (MP3)](https://diffio.ai/media/recording-rescue/flash.mp3) **A listener with the link hears the restored recording; the uploaded original is never part of a share. [How this recording was restored](https://diffio.ai/recording-rescue/).** - A share `id` you can put in any link, such as `https://your-app.example/listen.html?share=Hq7cTnWm3RkZpY2vB`. - A page that plays the restored audio for anyone with the link, without your API key. - One call that turns it off. **Output of `python share.py 62f62565-…`** **Terminal** ```bash share id Hq7cTnWm3RkZpY2vB plays https://media.diffio.io/s/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/restored.mp3 after revoke 404 share_not_found ``` ## API reference - PUT [Publish a project's share](https://diffio.ai/docs/api-reference/publish-project-share/) (`/projects/{project_id}/share`): Pin a generation or a preview length. - GET [Get a share](https://diffio.ai/docs/api-reference/get-share/) (`/shares/{share_id}`): The public read: fields and files. - GET [Get a project's share](https://diffio.ai/docs/api-reference/get-project-share/) (`/projects/{project_id}/share`): The project's share, with your key. - DELETE [Revoke a project's share](https://diffio.ai/docs/api-reference/revoke-project-share/) (`/projects/{project_id}/share`): Stop sharing. ## Related pages - Previous: [Separate speech and background](https://diffio.ai/docs/developers/guides/separate-speech-and-background/): Stems → mix → export - Next: [Restore a video and stream it](https://diffio.ai/docs/developers/guides/restore-video-and-stream/): Video upload → HLS stream --- Source: https://diffio.ai/docs/developers/guides/restore-video-and-stream/ # Restore a video and stream it Restore the speech in a video, download the restored MP4, and stream the result in a browser with hls.js. ## How it works 1. Your code → Diffio API: `POST /projects`, talk.mp4, generation 2. Your code → Media host: `upload.requests`, the SDK sends the parts 3. Diffio API → Your code: `generation complete`, files.video (MP4) 4. Your code → Diffio API: `GET /projects/{id}`, video_preview_status: "ready" 5. Your code → Diffio API: `GET …/media`, files.hls_master, 6 hour URLs 6. Your code → Browser: `player.html`, hls_master URL 7. Browser → Media host: `GET hls_master`, playlists and segments, any origin **The browser streams straight from the media host; your API key never reaches it.** ## Build it ### 1. Restore the video Upload MP4, MOV, WebM, AVI, MKV, 3GP or 3G2 (up to 2 GB; see [Video support](https://diffio.ai/docs/overview/capabilities/video-support/)) like any recording. The finished generation has `files.video`: the same video with the restored speech, as an MP4. `file="video"` (`downloadFile: "video"` in Node) saves it. ### 2. Wait for the picture stream The picture for streaming is prepared from the upload: the project's `video_preview_status` goes `preparing` → `ready`. Until then, `files.hls_master` plays sound only; if it ends `failed`, `files.video` still works. ### 3. Stream it `files.hls_master` plays the restored sound with the picture. Safari plays HLS itself; other browsers use hls.js. The media host answers these URLs from any origin, and they stop working at `expires_at` (6 hours): in production, your server asks for a fresh grant each time someone opens the player. ### The complete script Pass a video file; it writes `restored.mp4` and `player.html`. **video.py** ```python """Restore the speech in a video, save the restored MP4, and write player.html that streams it with hls.js. python video.py talk.mp4 """ import sys import time from diffio import DiffioClient, DiffioTimeoutError, GenerationFailedError PLAYER = """ Restored video """ path = sys.argv[1] client = DiffioClient() # reads DIFFIO_API_KEY # 1. Restore; files.video is the video with the restored speech. try: result = client.restore_audio(path, file="video", output_path="restored.mp4", timeout=3600) except (GenerationFailedError, DiffioTimeoutError) as error: sys.exit(f"restore did not finish: {error}") project_id, generation_id = result.project.id, result.generation.id # 2. The picture stream for HLS (bounded wait). deadline = time.monotonic() + 600 project = client.projects.get(project_id) while project.video_preview_status == "preparing" and time.monotonic() < deadline: time.sleep(3) project = client.projects.get(project_id) if not project.has_video or project.video_preview_status != "ready": sys.exit(f"no picture stream (has_video {project.has_video}, video_preview_status {project.video_preview_status})") # 3. A playback grant: hls_master plays the restored sound with the picture. media = client.generations.media(project_id, generation_id) with open("player.html", "w") as page: page.write(PLAYER.replace("HLS_MASTER_URL", media.files["hls_master"])) print("saved restored.mp4 and player.html; the stream works until", media.expires_at) ``` **video.mjs** ```javascript // Restore the speech in a video, save the restored MP4, and write player.html that streams it with hls.js. // node video.mjs talk.mp4 import { writeFile } from "node:fs/promises"; import { setTimeout as sleep } from "node:timers/promises"; import { DiffioClient } from "diffio"; const PLAYER = ` Restored video `; const path = process.argv[2]; const client = new DiffioClient(); // reads DIFFIO_API_KEY // 1. Restore; files.video is the video with the restored speech (a failure throws with its error code). const result = await client.restoreAudio({ file: path, downloadFile: "video", outputPath: "restored.mp4", timeout: 3600 }); const projectId = result.project.id; // 2. The picture stream for HLS (bounded wait). const deadline = Date.now() + 600_000; let project = await client.projects.get(projectId); while (project.video_preview_status === "preparing" && Date.now() < deadline) { await sleep(3000); project = await client.projects.get(projectId); } if (!project.has_video || project.video_preview_status !== "ready") { throw new Error(`No picture stream (has_video ${project.has_video}, video_preview_status ${project.video_preview_status})`); } // 3. A playback grant: hls_master plays the restored sound with the picture. const media = await client.generations.media(projectId, result.generation.id); await writeFile("player.html", PLAYER.replace("HLS_MASTER_URL", media.files.hls_master)); console.log("saved restored.mp4 and player.html; the stream works until", media.expires_at); ``` ## What you get ![A restored downtown street interview in the Diffio app: the video picture above the waveform, the Restored switch and the Background amount slider at 25%](https://diffio.ai/media/remove-background-noise-from-video/app-video-result.webp) Soundtrack as uploaded [Soundtrack as uploaded (MP3)](https://diffio.ai/media/remove-background-noise-from-video/downtown-traffic-original.mp3) Restored by Diffio 4.7 Pro [Restored by Diffio 4.7 Pro (MP3)](https://diffio.ai/media/remove-background-noise-from-video/downtown-traffic-speech.mp3) **A street interview in Kansas City with traffic passing: its soundtrack as uploaded, the speech restored by Diffio 4.7 Pro, and the restored video in the Diffio app. Video by Kansas City, Mo. City Communications, CC BY 3.0. [More restored videos](https://diffio.ai/remove-background-noise-from-video/).** - `restored.mp4`: the video with the restored speech. - `player.html`: the HLS stream with the picture, playable in any modern browser for 6 hours. **Output of `python video.py talk.mp4`** **Terminal** ```bash saved restored.mp4 and player.html; the stream works until 2026-11-13T06:33:47Z ``` ## API reference - POST [Create a project](https://diffio.ai/docs/api-reference/create-project/) (`/projects`): Upload a video like any recording. - GET [Get a project](https://diffio.ai/docs/api-reference/get-project/) (`/projects/{project_id}`): has_video and video_preview_status. - GET [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) (`/projects/{project_id}/generations/{generation_id}/media`): video, hls_master, video_hls and the other files. ## Related pages - Previous: [Share a restored result](https://diffio.ai/docs/developers/guides/share-a-result/): Publish → public read → revoke - Next: [Compare Flash and Pro](https://diffio.ai/docs/developers/guides/compare-flash-and-pro/): One project → two generations --- Source: https://diffio.ai/docs/developers/guides/compare-flash-and-pro/ # Compare Flash and Pro on one recording Restore one recording with both models, listen to them side by side, and see what each one cost. ## How it works 1. Your code → Diffio API: `POST /projects`, generation diffio-flash 2. Your code → Diffio API: `upload`, once 3. Your code → Diffio API: `POST …/generations`, diffio-pro, same upload 4. Diffio API → Your code: `two generations complete`, price_per_hour_usd each 5. Your code → Diffio API: `GET …/media`, once per generation 6. Your code: `compare.html`, original, Flash, Pro **Two generations of one project share its upload; only the restore runs twice.** ## Build it ### 1. One project, a Flash generation Create the project with `generation: {"model": "diffio-flash"}` and upload the file once. ### 2. A Pro generation on the same upload `POST …/generations` with `diffio-pro`. Nothing is uploaded again; each generation has its own status, files and price. ### 3. Work out the cost Each generation reports `price_per_hour_usd` (the same list prices as [GET /models](https://diffio.ai/docs/api-reference/list-models/)). A restore bills whole seconds of the recording with a 60 second minimum; [GET /usage](https://diffio.ai/docs/api-reference/usage-summary/) reports what was billed. ### 4. Listen side by side Each generation's media grant has `files.audio`; the owner's grant also has `files.original`. ### The complete script Pass an audio or video file; it writes `compare.html`. **compare.py** ```python """Restore one recording with Flash and Pro, then write compare.html to hear them side by side. python compare.py interview.mp3 """ import html import math import os import sys from diffio import DiffioClient path = sys.argv[1] client = DiffioClient() # reads DIFFIO_API_KEY # 1. One project and one upload, with a Flash generation... project = client.projects.create(file_name=os.path.basename(path), size_bytes=os.path.getsize(path), generation={"model": "diffio-flash"}) client.projects.upload(project, path) # 2. ...and a Pro generation on the same upload. pro = client.generations.create(project.id, model="diffio-pro") # 3. Wait for both; work out each one's cost at list price. players = [] for generation_id in (project.latest_generation.id, pro.id): generation = client.generations.wait(project.id, generation_id, timeout=3600) media = client.generations.media(project.id, generation.id) seconds = max(60, math.ceil(generation.duration_seconds or 0)) # whole seconds, 60 second minimum cost = seconds * (generation.price_per_hour_usd or 0) / 3600 print(f"{generation.model}: {seconds} s at ${generation.price_per_hour_usd}/h = ${cost:.2f}") players.append((f"{generation.model} (${cost:.2f})", media.files["audio"])) players.insert(0, ("Original", media.files["original"])) # 4. One page with all three; the URLs work for 6 hours. with open("compare.html", "w") as page: page.write("Flash and Pro") for label, url in players: page.write(f'

{html.escape(label)}

') print("open compare.html") ``` **compare.mjs** ```javascript // Restore one recording with Flash and Pro, then write compare.html to hear them side by side. // node compare.mjs interview.mp3 import { writeFile } from "node:fs/promises"; import { DiffioClient } from "diffio"; const path = process.argv[2]; const client = new DiffioClient(); // reads DIFFIO_API_KEY const escape = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); // 1. One project and one upload, with a Flash generation... const project = await client.projects.create({ file_name: path.split("/").pop(), generation: { model: "diffio-flash" } }); await client.projects.upload(project, path); // 2. ...and a Pro generation on the same upload. const pro = await client.generations.create(project.id, { model: "diffio-pro" }); // 3. Wait for both; work out each one's cost at list price. const players = []; let media; for (const generationId of [project.latest_generation.id, pro.id]) { const generation = await client.generations.wait(project.id, generationId, { timeout: 3600 }); media = await client.generations.media(project.id, generation.id); const seconds = Math.max(60, Math.ceil(generation.duration_seconds ?? 0)); // whole seconds, 60 second minimum const cost = (seconds * (generation.price_per_hour_usd ?? 0)) / 3600; console.log(`${generation.model}: ${seconds} s at $${generation.price_per_hour_usd}/h = $${cost.toFixed(2)}`); players.push([`${generation.model} ($${cost.toFixed(2)})`, media.files.audio]); } players.unshift(["Original", media.files.original]); // 4. One page with all three; the URLs work for 6 hours. const body = players.map(([label, url]) => `

${escape(label)}

`).join(""); await writeFile("compare.html", `Flash and Pro${body}`); console.log("open compare.html"); ``` ## What you get ![The finished Diffio 4.7 Pro project of the same lecture in the Diffio app](https://diffio.ai/media/recording-rescue/pro-result.jpg) Uploaded [Uploaded (MP3)](https://diffio.ai/media/recording-rescue/original.mp3) Diffio 4.7 Flash [Diffio 4.7 Flash (MP3)](https://diffio.ai/media/recording-rescue/flash.mp3) Diffio 4.7 Pro [Diffio 4.7 Pro (MP3)](https://diffio.ai/media/recording-rescue/pro.mp3) **The same 60 seconds of an archival lecture, as uploaded and restored by each model. [How this recording was restored](https://diffio.ai/recording-rescue/).** - `compare.html`: the original and both results on one page, each with its cost. - Both generations stay on the project: keep the one you prefer, or let your users choose. **Output of `python compare.py interview.mp3`** **Terminal** ```bash diffio-4.7-flash: 60 s at $5.0/h = $0.08 diffio-4.7-pro: 60 s at $10.0/h = $0.17 open compare.html ``` ## API reference - POST [Create a project](https://diffio.ai/docs/api-reference/create-project/) (`/projects`): The project and its Flash generation. - POST [Create a generation](https://diffio.ai/docs/api-reference/create-generation/) (`/projects/{project_id}/generations`): The Pro generation. - GET [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) (`/projects/{project_id}/generations/{generation_id}/media`): audio and original URLs. - GET [List models](https://diffio.ai/docs/api-reference/list-models/) (`/models`): Every model and its price per hour. ## Related pages - Previous: [Restore a video and stream it](https://diffio.ai/docs/developers/guides/restore-video-and-stream/): Video upload → HLS stream - Next: [Clean up a back catalogue](https://diffio.ai/docs/developers/guides/clean-up-a-back-catalogue/): Folder → restores → usage --- Source: https://diffio.ai/docs/developers/guides/clean-up-a-back-catalogue/ # Clean up a back catalogue Restore every recording in a folder, a few at a time, pick up where a stopped run left off, and total what it used. ## How it works 1. State file → Your script: `done files`, skipped if digest and output match 2. Your script → Diffio API: `POST /projects`, Idempotency-Key from path and content, 3 at a time 3. Diffio API → Your script: `upload or upload: null`, null: it already arrived 4. Your script → Diffio API: `GET …/generations/{id}`, until complete 5. Your script → Diffio API: `GET …/media`, download the restored MP3 6. Your script → State file: `done`, after each file 7. Your script → Diffio API: `GET /usage?start=…`, the run's total **Stop the script at any point; the next run picks up from the state file and the same keys.** ## Build it ### 1. One Idempotency-Key per file The key hashes the file's relative path with a SHA-256 of its content, under a batch name. Running again finds the same project instead of creating and billing a second one; a changed file gets a new key. Keys belong to your account (and end user, if you send one). ### 2. Skip what already arrived A repeated `POST /projects` answers `upload: null` once the file has arrived: skip the upload and wait for the project's first generation (`latest_generation`). ### 3. A few at a time Three workers keep uploads and downloads moving without flooding your network; restores queue on Diffio's side (see `queue` on a generation). Each worker waits at most 2 hours for one file. ### 4. Resume from the state file The state file is named after `BATCH` and the source and target folders, so another batch or folder pair never reuses it (give each source its own target). A file counts as done only when its stored digest matches its content and its output exists; outputs are written to a `.part` file and renamed. A failed generation fails again with the same key; a new `BATCH` name starts over with new keys and restores every file again. ### 5. Total the usage [GET /usage](https://diffio.ai/docs/api-reference/usage-summary/) from the first run's start time. It counts the whole account's generations in that period; send `Diffio-End-User` on the run to count only its own. ### The complete script Pass the folder to read and the folder to write; `ep01.wav` becomes `ep01.wav.restored.mp3` at the same relative path. **catalogue.py** ```python """Restore every recording in a folder, three at a time, and resume where a stopped run left off. python catalogue.py ./archive ./restored """ import hashlib import os import sqlite3 import sys from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timezone from pathlib import Path from diffio import DiffioClient, DiffioError SOURCE, TARGET = Path(sys.argv[1]).resolve(), Path(sys.argv[2]).resolve() EXTENSIONS = {".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg", ".mp4", ".mov", ".webm"} WORKERS = 3 BATCH = "catalogue-v1" # a new name starts a new state file and new projects: everything is restored again client = DiffioClient() # reads DIFFIO_API_KEY # One state file per BATCH, SOURCE and TARGET: another batch or folder pair never reuses this progress. pair = hashlib.sha256(f"{BATCH}\n{SOURCE}\n{TARGET}".encode()).hexdigest()[:16] state = sqlite3.connect(f"catalogue-{pair}.db") state.executescript(""" create table if not exists files (path text primary key, digest text, status text, project_id text, error text); create table if not exists run (started_at text); """) with state: if not state.execute("select 1 from run").fetchone(): state.execute("insert into run values (?)", (datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),)) def sha256_of(path): digest = hashlib.sha256() with open(path, "rb") as source: for block in iter(lambda: source.read(1 << 20), b""): digest.update(block) return digest.hexdigest() def restore(path, done_digest): relative = path.relative_to(SOURCE).as_posix() output = TARGET / f"{relative}.restored.mp3" # ep01.wav -> ep01.wav.restored.mp3 digest = sha256_of(path) # identity is the content, not the size if digest == done_digest and output.exists(): return digest, None # finished on an earlier run, unchanged since key = f"{BATCH}-" + hashlib.sha256(f"{relative}\n{digest}".encode()).hexdigest() project = client.projects.create(file_name=path.name, size_bytes=path.stat().st_size, generation={"model": "diffio-flash"}, idempotency_key=key) if project.upload is not None: # None: an earlier run already uploaded this file client.projects.upload(project, path) generation = client.generations.wait(project.id, project.latest_generation.id, timeout=7200) output.parent.mkdir(parents=True, exist_ok=True) partial = output.with_name(output.name + ".part") client.generations.download(project.id, generation.id, path=partial) os.replace(partial, output) # a stop never leaves a half-written output return digest, project.id done = dict(state.execute("select path, digest from files where status = 'done'")) todo = [path for path in sorted(SOURCE.rglob("*")) if path.is_file() and path.suffix.lower() in EXTENSIONS and TARGET not in path.parents] with ThreadPoolExecutor(max_workers=WORKERS) as pool: futures = {pool.submit(restore, path, done.get(path.relative_to(SOURCE).as_posix())): path.relative_to(SOURCE).as_posix() for path in todo} for future in as_completed(futures): # state is written here, on one thread relative = futures[future] try: digest, project_id = future.result() except DiffioError as error: digest, project_id, outcome = None, None, ("failed", str(error)) else: outcome = ("skipped", None) if project_id is None else ("done", None) if outcome[0] != "skipped": with state: state.execute("insert or replace into files values (?, ?, ?, ?, ?)", (relative, digest, outcome[0], project_id, outcome[1])) print(outcome[0], relative) started_at = state.execute("select started_at from run").fetchone()[0] usage = client.usage.get(start=started_at) print(f"since {started_at}: {usage.generations} generations, {usage.billable_seconds} s, " f"${usage.list_price_usd:.2f} at list price") ``` **catalogue.mjs** ```javascript // Restore every recording in a folder, three at a time, and resume where a stopped run left off. // node catalogue.mjs ./archive ./restored import { createHash } from "node:crypto"; import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs"; import { basename, dirname, extname, join, resolve, sep } from "node:path"; import { DiffioClient, DiffioError } from "diffio"; const [SOURCE, TARGET] = process.argv.slice(2).map((folder) => resolve(folder)); const EXTENSIONS = new Set([".mp3", ".wav", ".m4a", ".aac", ".flac", ".ogg", ".mp4", ".mov", ".webm"]); const WORKERS = 3; const BATCH = "catalogue-v1"; // a new name starts a new state file and new projects: everything is restored again const client = new DiffioClient(); // reads DIFFIO_API_KEY const sha256 = (text) => createHash("sha256").update(text).digest("hex"); // One state file per BATCH, SOURCE and TARGET: another batch or folder pair never reuses this progress. const STATE_FILE = `catalogue-${sha256(`${BATCH}\n${SOURCE}\n${TARGET}`).slice(0, 16)}.json`; const state = existsSync(STATE_FILE) ? JSON.parse(readFileSync(STATE_FILE, "utf8")) : { source: SOURCE, target: TARGET, started_at: new Date().toISOString().replace(/\.\d+Z$/, "Z"), files: {} }; const save = () => { // write then rename, so a stop never leaves half a file writeFileSync(`${STATE_FILE}.tmp`, JSON.stringify(state, null, 2)); renameSync(`${STATE_FILE}.tmp`, STATE_FILE); }; save(); const sha256Of = (path) => new Promise((done, fail) => { const hash = createHash("sha256"); createReadStream(path).on("data", (block) => hash.update(block)).on("end", () => done(hash.digest("hex"))).on("error", fail); }); async function restore(relative) { const path = join(SOURCE, relative); const output = join(TARGET, `${relative}.restored.mp3`); // ep01.wav -> ep01.wav.restored.mp3 const digest = await sha256Of(path); // identity is the content, not the size const previous = state.files[relative]; if (previous?.status === "done" && previous.digest === digest && existsSync(output)) return null; // unchanged const project = await client.projects.create( { file_name: basename(path), size_bytes: statSync(path).size, generation: { model: "diffio-flash" } }, { idempotencyKey: `${BATCH}-${sha256(`${relative}\n${digest}`)}` } ); if (project.upload) await client.projects.upload(project, path); // null: an earlier run already uploaded it const generation = await client.generations.wait(project.id, project.latest_generation.id, { timeout: 7200 }); mkdirSync(dirname(output), { recursive: true }); await client.generations.download(project.id, generation.id, { path: `${output}.part` }); renameSync(`${output}.part`, output); // a stop never leaves a half-written output return { status: "done", digest, project_id: project.id }; } const todo = readdirSync(SOURCE, { recursive: true }) .filter((relative) => EXTENSIONS.has(extname(relative).toLowerCase())) .filter((relative) => statSync(join(SOURCE, relative)).isFile() && !join(SOURCE, relative).startsWith(TARGET + sep)) .sort(); const queue = [...todo]; async function worker() { for (let relative = queue.shift(); relative; relative = queue.shift()) { let result; try { result = await restore(relative); } catch (error) { if (!(error instanceof DiffioError)) throw error; result = { status: "failed", error: error.message }; } if (result) { state.files[relative] = result; save(); } console.log(result ? result.status : "skipped", relative); } } await Promise.all(Array.from({ length: WORKERS }, worker)); const usage = await client.usage.get({ start: state.started_at }); console.log( `since ${state.started_at}: ${usage.generations} generations, ${usage.billable_seconds} s, ` + `$${usage.list_price_usd.toFixed(2)} at list price` ); ``` ## What you get | File | Run 1 | Run 2 | | --- | --- | --- | | `ep01.wav` | done | **skipped** | | `ep02.wav` | done | **skipped** | | `ep03.mp3` | uploaded, then stopped | **done (no second upload)** | | `ep04.mp3` | not started | **done** | | `ep01.mp3` | not started | **done (its own output)** | - One `.restored.mp3` per recording, named after the whole original file name, so `ep.wav` and `ep.mp3` never collide. - No file billed twice: a rerun reuses each unchanged file's project; a changed file is restored again. - The run's generations, billable seconds and list price from `GET /usage`. **Output of `python catalogue.py ./archive ./restored` (second run)** **Terminal** ```bash skipped ep01.wav skipped ep02.wav done ep03.mp3 done ep01.mp3 done ep04.mp3 since 2026-11-13T09:00:00Z: 5 generations, 14400 s, $20.00 at list price ``` ## API reference - POST [Create a project](https://diffio.ai/docs/api-reference/create-project/) (`/projects`): Idempotency-Key, generation and upload. - GET [Get a generation](https://diffio.ai/docs/api-reference/get-generation/) (`/projects/{project_id}/generations/{generation_id}`): status, stage and queue. - GET [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) (`/projects/{project_id}/generations/{generation_id}/media`): The restored file. - GET [Get usage](https://diffio.ai/docs/api-reference/usage-summary/) (`/usage`): Generations, billable seconds and list price. ## Related pages - Previous: [Compare Flash and Pro](https://diffio.ai/docs/developers/guides/compare-flash-and-pro/): One project → two generations - Next: [Bill your users from usage](https://diffio.ai/docs/developers/guides/bill-users-from-usage/): Usage per end user → invoice --- Source: https://diffio.ai/docs/developers/guides/bill-users-from-usage/ # Bill your users from usage Read each customer's Diffio usage for a billing period and turn it into one line on their invoice. ## How it works 1. Your billing job → Diffio API: `GET /usage?start=…&end=…`, Diffio-End-User: customer-42 2. Diffio API → Your billing job: `billable_seconds, list_price_usd`, and by_model 3. Your billing job: `minutes × your price` 4. Your billing job → Your invoices: `one line per customer` **One request per customer and period; repeat it for each end user you bill.** ## Build it ### 1. Create every project for an end user Usage is reported per end user only for work created with `Diffio-End-User`. The [SaaS guide](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/) sends it on every call. ### 2. Read usage for each customer `GET /usage` with the customer's `Diffio-End-User` and your billing period. `start` and `end` are ISO 8601 dates or times (UTC) and bound when each generation was created; the period can be up to 366 days. Without them, the report is this calendar month so far. ### 3. Price it your way `billable_seconds` is what the customer used; failed generations count in `generations` and use nothing. `list_price_usd` is that usage at Diffio's list price, for your margin. ### The complete script Pass the period, then your customers' end user ids (from your own database). **invoice.py** ```python """One invoice line per customer from their Diffio usage in a billing period. python invoice.py 2026-10-01 2026-11-01 customer-42 customer-7 """ import math import sys from diffio import DiffioClient start, end, *customers = sys.argv[1:] PRICE_PER_MINUTE_USD = 0.15 # what you charge your customers client = DiffioClient() # reads DIFFIO_API_KEY for customer in customers: # Diffio-End-User narrows the report to this customer's work. usage = client.usage.get(start=start, end=end, end_user=customer) minutes = math.ceil(usage.billable_seconds / 60) print(f"{customer}: {usage.generations} generations, {minutes} min, " f"${minutes * PRICE_PER_MINUTE_USD:.2f} (Diffio list price ${usage.list_price_usd:.2f})") for row in usage.by_model: print(f" {row.model}: {row.generations} generations, {row.billable_seconds} s") ``` **invoice.mjs** ```javascript // One invoice line per customer from their Diffio usage in a billing period. // node invoice.mjs 2026-10-01 2026-11-01 customer-42 customer-7 import { DiffioClient } from "diffio"; const [start, end, ...customers] = process.argv.slice(2); const PRICE_PER_MINUTE_USD = 0.15; // what you charge your customers const client = new DiffioClient(); // reads DIFFIO_API_KEY for (const customer of customers) { // Diffio-End-User narrows the report to this customer's work. const usage = await client.usage.get({ start, end }, { endUser: customer }); const minutes = Math.ceil(usage.billable_seconds / 60); console.log( `${customer}: ${usage.generations} generations, ${minutes} min, ` + `$${(minutes * PRICE_PER_MINUTE_USD).toFixed(2)} (Diffio list price $${usage.list_price_usd.toFixed(2)})` ); for (const row of usage.by_model) { console.log(` ${row.model}: ${row.generations} generations, ${row.billable_seconds} s`); } } ``` **cURL** ```bash curl -sS --connect-timeout 10 --max-time 60 "https://api.diffio.ai/v2/usage?start=2026-10-01&end=2026-11-01" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Diffio-End-User: customer-42" ``` ## What you get | Customer | Usage | Amount | | --- | --- | --- | | `customer-42` | 12 generations, 95 min | **$14.25** (list $7.92) | - One invoice line per customer: generations, minutes and your amount. - Diffio's list price beside it, and the seconds per model. **Output of `python invoice.py 2026-10-01 2026-11-01 customer-42`** **Terminal** ```bash customer-42: 12 generations, 95 min, $14.25 (Diffio list price $7.92) diffio-4.7-flash: 12 generations, 5700 s ``` ## API reference - GET [Get usage](https://diffio.ai/docs/api-reference/usage-summary/) (`/usage`): Fields, period limits and refusals. - POST [Create a project](https://diffio.ai/docs/api-reference/create-project/) (`/projects`): Diffio-End-User on the work you bill. ## Related pages - Previous: [Clean up a back catalogue](https://diffio.ai/docs/developers/guides/clean-up-a-back-catalogue/): Folder → restores → usage - Next: [Podcast cleanup in a SaaS app](https://diffio.ai/docs/developers/guides/saas-podcast-cleanup/): Browser upload → webhook → player --- Source: https://diffio.ai/docs/api-reference/introduction/ # Diffio API reference: base URL, auth and errors Use this reference to integrate the Diffio API. Every endpoint speaks JSON over HTTPS at `https://api.diffio.ai/v2`. Check your key with a first request (`pip install diffio` or `npm install diffio`). It lists your account's projects; see [List projects](https://diffio.ai/docs/api-reference/list-projects/) for the response shape. **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) page = client.projects.list() ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const page = await client.projects.list() ``` **cURL** ```bash curl "https://api.diffio.ai/v2/projects" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` 1. URL base URL + resource path 2. Header `Authorization: Bearer ` 3. Response `snake_case` JSON resource or page ## API reference essentials 1. Your code or SDK `GET · POST · PUT · DELETE` resource path, Bearer key header 2. Success `200` `201` `202` `JSON` `snake_case` fields for each resource 3. Error `4xx` `{"error": {...}}` `code`, `message`, `request_id`, optional `details` ### 1. Base URL and OpenAPI spec Append each endpoint path to the production base URL. `https://api.diffio.ai/v2` Fetch the machine-readable OpenAPI 3.1.0 specification at `GET https://api.diffio.ai/v2/openapi.json` (public, no API key required). The API version is in the path; within it, changes only add. Releases and the versioning rules are in the [Changelog](https://diffio.ai/docs/overview/changelog/#versioning). ### 2. Authentication Send your API key in the `Authorization` header on every non-public request. Create and manage keys on the [API keys](https://diffio.ai/developers/api-keys/) page in the developer dashboard. - `Authorization: Bearer ` Each endpoint page lists the scope it requires (`projects:read`, `projects:write`, `generations:read`, `generations:write`, `artifacts:read`, `usage:read`, or `webhooks:write`). [List models](https://diffio.ai/docs/api-reference/list-models/), [Get a share](https://diffio.ai/docs/api-reference/get-share/), and `GET /openapi.json` are public and need no key. ### 3. Request conventions - `snake_case` JSON fields - `Content-Type: application/json` - `Idempotency-Key` - `Diffio-End-User` - `limit` and `cursor` pagination - `X-Request-Id` response header - `OPTIONS` for CORS preflight - **JSON bodies:** `POST` and `PUT` calls that take fields accept a JSON object (`{...}`) with `snake_case` keys such as `file_name`, `size_bytes`, and `preview_seconds`. - **`Idempotency-Key`:** Optional header (up to 255 characters) honoured on [Create a project](https://diffio.ai/docs/api-reference/create-project/), [Create a generation](https://diffio.ai/docs/api-reference/create-generation/), and [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/). Repeating the same request returns the original resource without charging twice; changing any body field returns `409` with code `idempotency_key_conflict`. Both SDKs send an `Idempotency-Key` automatically when you omit one. - **`Diffio-End-User`:** Optional header (up to 128 characters) for multi-tenant apps. Requests carrying this header assign new projects to that `end_user` and scope project reads, generations, shares, and [Get usage](https://diffio.ai/docs/api-reference/usage-summary/) reports to that end user. Omit it on account-wide calls such as [Open the webhook portal](https://diffio.ai/docs/api-reference/open-webhook-portal/). - **Cursor pagination:** [List projects](https://diffio.ai/docs/api-reference/list-projects/) and [List a project's generations](https://diffio.ai/docs/api-reference/list-project-generations/) return `{"object": "list", "data": [...], "next_cursor": "..."}` newest first. Pass `limit` (`1` to `100`, default `20`) and pass `next_cursor` as `cursor` until `next_cursor` is `null`. **Uploads, playback URLs, and models** - [Create a project](https://diffio.ai/docs/api-reference/create-project/) returns `upload.requests` (`start`, `part` in 32 MiB chunks, `complete`, and `abort`) authenticated with `Authorization: Bearer {upload.upload_token}` (valid for 24 hours). Files can be up to 2 GB (`2,147,483,648` bytes) with no media length limit. Call [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/) for immediate readiness, or let the upload edge report completion after about 30 seconds. Both official SDKs handle multipart uploads and retries automatically. - [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) returns signed media URLs in `files` (`audio`, `video`, `hls_master`, `transcript`, `stems_manifest`, `original`, and waveforms) valid for 6 hours until `expires_at`, with no API key required. Append `?download=` to a media URL to trigger a browser file download. - [List models](https://diffio.ai/docs/api-reference/list-models/) returns hosted models (`diffio-4.7-flash` at $5/hour and `diffio-4.7-pro` at $10/hour), rolling tier aliases (`diffio-flash` and `diffio-pro`), and retired model names. Retired model names run on the current hosted model of the same tier (`substituted: true`) at the lower of the two list prices ([Models](https://diffio.ai/docs/overview/models/)). ### 4. Error responses Every 4xx and 5xx response returns one JSON shape: `error.code` (stable `snake_case` identifier to branch on), `error.message`, `error.request_id` (also sent in the `X-Request-Id` header), and an optional `error.details` object when structured context applies. **Error response shape** ```json { "error": { "code": "unknown_model", "message": "nope is not a Diffio model. See GET /v2/models.", "request_id": "f064e4099097414da3fb5b37684ab1bb", "details": { "field": "model", "models": [ "diffio-4.7-flash", "diffio-4.7-pro", "diffio-flash", "diffio-pro" ] } } } ``` #### Common error codes | Status and `code` | When it happens | | --- | --- | | `400` `invalid_field` · `missing_field` | Malformed JSON (`invalid_json`), missing or invalid body field (`details.field`), bad query parameter (`invalid_parameter`, `details.parameter`), oversized header (`invalid_header`), or unknown model (`unknown_model`). | | `401` `missing_api_key` · `invalid_api_key` | No API key was sent, or the API key was not recognized. | | `403` `permission_denied` | The key is inactive, lacks the required scope, or sent `Diffio-End-User` to an account-only route. | | `404` `*_not_found` | Unknown resource for this account or end user (`project_not_found`, `generation_not_found`, `export_not_found`, `share_not_found`, `transcript_not_found`, `route_not_found`). | | `405` `method_not_allowed` | The path exists, but does not accept this HTTP method; check the `Allow` header. | | `409` `not_ready` · `not_available` · `revision_conflict` | State conflict: prerequisite still running (`not_ready`), permanently unavailable (`not_available`), stale save revision (`revision_conflict`, `details.current_revision`), or reused `Idempotency-Key` with a different body (`idempotency_key_conflict`). | | `413` `upload_too_large` · `415` `unsupported_media_type` | File exceeds 2 GB (`upload_too_large`), draft JSON exceeds 900,000 bytes (`transcript_draft_too_large`), or file extension/MIME type is not supported audio or video (`unsupported_media_type`). | | `429` `rate_limited` | Too many requests of this kind in a short time (for example, more than 10 [assistant feedback](https://diffio.ai/docs/api-reference/create-transcript-assistant-feedback/) reports in an hour); retry later with backoff, honouring `Retry-After` when sent. | | `500` `internal_error` · `503` `unavailable` | A transient server error occurred (`internal_error`, `generation_start_failed`, `unavailable`); retry with exponential backoff. | Every code, with its retry rule and the codes a failed resource reports: [Errors](https://diffio.ai/docs/api-reference/errors/). #### Billing error codes (`402`) | Status and `code` | Meaning | What to do | | --- | --- | --- | | `402` `insufficient_credit` | Your API credit is used up, or cannot cover this file. | Add credit on the Billing page. | | `402` `needs_payment_method` | The credit is used up, or cannot cover this file, and no payment method is saved. | Add a payment method on the Billing page. | | `402` `payment_failed` | A payment for API usage failed, or the last invoice of ended card billing is unpaid. | On the Billing page, select Update payment method and choose a card for your subscription, or Pay invoice once card billing has ended. | | `402` `usage_limit_reached` | Unbilled usage reached $100; it is being charged now. | Wait for the charge to complete; the API continues as soon as it does. | `needs_payment_method`, `payment_failed` and `usage_limit_reached` reach only accounts with card billing (a card added before prepaid credit). **Example 402 responses and billing details** **402 insufficient_credit** ```json { "error": { "code": "insufficient_credit", "message": "This file needs about $1.25 of API credit and your balance is $0.40. Add credit in the developer dashboard to continue.", "request_id": "f064e4099097414da3fb5b37684ab1bb", "details": { "estimated_cost_cents": 125, "remaining_credit_cents": 40 } } } ``` **402 payment_failed** ```json { "error": { "code": "payment_failed", "message": "A payment for API usage failed. On the developer dashboard's Billing page, select Update payment method and choose a card for your subscription.", "request_id": "f064e4099097414da3fb5b37684ab1bb" } } ``` **402 payment_failed, card billing ended** ```json { "error": { "code": "payment_failed", "message": "The last invoice of your API card billing is unpaid. Pay it from the developer dashboard's Billing page to continue.", "request_id": "f064e4099097414da3fb5b37684ab1bb" } } ``` **402 usage_limit_reached** ```json { "error": { "code": "usage_limit_reached", "message": "Your unbilled API usage reached $100.00. It is being billed to your payment method now, and the API continues as soon as that payment completes.", "request_id": "f064e4099097414da3fb5b37684ab1bb" } } ``` An `insufficient_credit` or `needs_payment_method` refusal from a credit check includes `details.estimated_cost_cents` and `details.remaining_credit_cents`; treat `details` as optional. A generation created before its upload finishes is checked again when processing starts, and fails with the same error code in `generation.error.code` if credit cannot cover the recording. [Billing](https://diffio.ai/docs/overview/administration/billing/) explains credit and card billing. ### 5. Rate limits No general per-key quota: Most endpoints set no per-key request limit; when workers are busy, generations wait in a queue (see `queue` on [Get a generation](https://diffio.ai/docs/api-reference/get-generation/)). A few actions have their own limits, per end user (or per account without `Diffio-End-User`): - [Ask the edit assistant](https://diffio.ai/docs/api-reference/create-transcript-assistant-turn/): up to 30 turns per 10 minutes plus a daily cap; a turn over the limit ends `failed` with `error.code` `rate_limited`. - [Send assistant feedback](https://diffio.ai/docs/api-reference/create-transcript-assistant-feedback/): up to 10 reports per hour; more answer `429` `rate_limited`. Treat any `429` as "retry later with backoff"; both SDKs do this for calls that are safe to repeat and honour `Retry-After`. Usage is billed per second ([API pricing](https://diffio.ai/api-pricing/)). ## Endpoints Browse all 30 endpoints across 8 categories: models, projects, generations, separated tracks, transcripts, shares, usage, and webhooks. - [Models 1](#endpoints-models) - [Projects 6](#endpoints-projects) - [Generations 6](#endpoints-generations) - [Separated tracks 4](#endpoints-separated-tracks) - [Transcripts 7](#endpoints-transcripts) - [Shares 4](#endpoints-shares) - [Usage 1](#endpoints-usage) - [Webhooks 1](#endpoints-webhooks) ### Models 1 endpoint | Endpoint, method and path | What it does | | --- | --- | | [List models](https://diffio.ai/docs/api-reference/list-models/) GET `/models` | List every hosted model, tier alias, and retired model name with hourly list pricing. | ### Projects 6 endpoints | Endpoint, method and path | What it does | | --- | --- | | [Create a project](https://diffio.ai/docs/api-reference/create-project/) POST `/projects` | Create a project for one audio or video file and receive multipart upload instructions. | | [List projects](https://diffio.ai/docs/api-reference/list-projects/) GET `/projects` | List projects on the account newest first with cursor pagination. | | [Get a project](https://diffio.ai/docs/api-reference/get-project/) GET `/projects/{project_id}` | Retrieve one project's upload status, media metadata, and latest generation. | | [Delete a project](https://diffio.ai/docs/api-reference/delete-project/) DELETE `/projects/{project_id}` | Delete a project and all of its stored uploads, generations, exports, and shares. | | [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/) POST `/projects/{project_id}/upload` | Mint fresh 24-hour multipart upload instructions for a project awaiting its file. | | [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/) POST `/projects/{project_id}/upload/complete` | Verify and prepare a finished multipart upload immediately instead of waiting for edge callback. | ### Generations 6 endpoints | Endpoint, method and path | What it does | | --- | --- | | [Create a generation](https://diffio.ai/docs/api-reference/create-generation/) POST `/projects/{project_id}/generations` | Start a speech restoration generation on a project with a chosen model. | | [List a project's generations](https://diffio.ai/docs/api-reference/list-project-generations/) GET `/projects/{project_id}/generations` | List every restore and transcript edit generation on a project, newest first. | | [Get a generation](https://diffio.ai/docs/api-reference/get-generation/) GET `/projects/{project_id}/generations/{generation_id}` | Check one generation's status, live stage progress, queue position, available files, or failure reason. | | [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/) GET `/projects/{project_id}/generations/{generation_id}/media` | Mint 6-hour signed playback and download URLs for a generation's audio, video, HLS, stems, and transcript files. | | [Estimate a transcript edit](https://diffio.ai/docs/api-reference/estimate-transcript-edit/) POST `/projects/{project_id}/generations/{generation_id}/edits/estimate` | Estimate the changed word runs, 30-second windows, and maximum billable seconds of a Pro transcript edit. | | [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/) POST `/projects/{project_id}/generations/{generation_id}/edits` | Edit a finished Pro generation's transcript and re-restore only the windows around changed words. | ### Separated tracks 4 endpoints | Endpoint, method and path | What it does | | --- | --- | | [Get the saved mix](https://diffio.ai/docs/api-reference/get-generation-mix/) GET `/projects/{project_id}/generations/{generation_id}/mix` | Read the saved background gain, speech leveling setting, and revision for a generation's separated tracks. | | [Save the mix](https://diffio.ai/docs/api-reference/save-generation-mix/) PUT `/projects/{project_id}/generations/{generation_id}/mix` | Save the background track gain and speech leveling setting for a generation's separated tracks. | | [Create an export](https://diffio.ai/docs/api-reference/create-generation-export/) POST `/projects/{project_id}/generations/{generation_id}/exports` | Render a downloadable or inline-playable file from a generation's separated speech and background tracks. | | [Get an export](https://diffio.ai/docs/api-reference/get-generation-export/) GET `/projects/{project_id}/generations/{generation_id}/exports/{export_id}` | Poll an export's render status and mint a fresh 6-hour download or playback URL once ready. | ### Transcripts 7 endpoints | Endpoint, method and path | What it does | | --- | --- | | [Get a generation's transcript](https://diffio.ai/docs/api-reference/get-transcript/) GET `/projects/{project_id}/generations/{generation_id}/transcript` | Retrieve a generation's normalized word-timed transcript for display, assistant turns, or Pro edits. | | [Get the transcript draft](https://diffio.ai/docs/api-reference/get-transcript-draft/) GET `/projects/{project_id}/generations/{generation_id}/transcript/draft` | Read the saved JSON editor draft and compare-and-swap revision for a generation's transcript. | | [Save the transcript draft](https://diffio.ai/docs/api-reference/save-transcript-draft/) PUT `/projects/{project_id}/generations/{generation_id}/transcript/draft` | Save an editor's JSON draft state (up to 900,000 bytes) for a generation's transcript. | | [Delete the transcript draft](https://diffio.ai/docs/api-reference/delete-transcript-draft/) DELETE `/projects/{project_id}/generations/{generation_id}/transcript/draft` | Delete a generation's saved transcript editor draft with optional revision checking. | | [Ask the edit assistant](https://diffio.ai/docs/api-reference/create-transcript-assistant-turn/) POST `/projects/{project_id}/generations/{generation_id}/transcript/assistant/turns` | Start an asynchronous edit-assistant chat turn on a finished Pro generation's transcript. | | [Get an edit assistant turn](https://diffio.ai/docs/api-reference/get-transcript-assistant-turn/) GET `/projects/{project_id}/generations/{generation_id}/transcript/assistant/turns/{turn_id}` | Poll an edit-assistant turn for its reply, word-level edit proposals, moments, or failure details. | | [Send assistant feedback](https://diffio.ai/docs/api-reference/create-transcript-assistant-feedback/) POST `/projects/{project_id}/generations/{generation_id}/transcript/assistant/feedback` | Send the Diffio team a bug report or an idea about the edit assistant, with the conversation if wanted. | ### Shares 4 endpoints | Endpoint, method and path | What it does | | --- | --- | | [Publish a project's share](https://diffio.ai/docs/api-reference/publish-project-share/) PUT `/projects/{project_id}/share` | Publish or update a project's public playback share, optionally pinned to one generation or preview length. | | [Get a project's share](https://diffio.ai/docs/api-reference/get-project-share/) GET `/projects/{project_id}/share` | Read a project's currently published share and its playback URLs using your API key. | | [Revoke a project's share](https://diffio.ai/docs/api-reference/revoke-project-share/) DELETE `/projects/{project_id}/share` | Revoke a project's published share so its public share ID and media URLs stop working. | | [Get a share](https://diffio.ai/docs/api-reference/get-share/) GET `/shares/{share_id}` | Fetch a published share's playback metadata and signed media URLs without an API key. | ### Usage 1 endpoint | Endpoint, method and path | What it does | | --- | --- | | [Get usage](https://diffio.ai/docs/api-reference/usage-summary/) GET `/usage` | Report generation counts, billable seconds, and USD list-price usage in total and by model. | ### Webhooks 1 endpoint | Endpoint, method and path | What it does | | --- | --- | | [Open the webhook portal](https://diffio.ai/docs/api-reference/open-webhook-portal/) POST `/webhooks/portal` | Create a short-lived login link to the hosted webhook portal to manage endpoints and secrets. | --- Source: https://diffio.ai/docs/api-reference/errors/ # Errors: every API error code and what to do Every error carries a stable `error.code` to branch on. This page lists all 84 codes from the API's error catalogue, with what to do about each. **Where error codes appear** Refused request: `4xx` `5xx` ``` {"error": { "code": "not_ready", "message": "...", "request_id": "..." }} ``` The answer to your call. Quote `request_id` to support. Failed resource: `"status": "failed"` ``` {"status": "failed", "error": { "code": "no_speech_detected", "message": "..." }} ``` On a generation, project, export or assistant turn, read later (or sent by webhook). ## What to do - Retry: Retry later with backoff, or make a new resource. (30 codes) - Fix: Change the request (body, header, key or id) first. (30 codes) - Pay: Add credit or a payment method, then retry. (9 codes) - Stop: Will not change: do not retry. (15 codes) Both SDKs retry calls that are safe to repeat after `408`, `429`, `5xx` and network errors, with exponential backoff and `Retry-After`. A refusal they give up on raises `DiffioApiError` with `status`, `code`, `request_id` and `details`. ## Error codes `400` ### Bad request | Code | Meaning | What to do | | --- | --- | --- | | `invalid_request` (`400`) | The request is malformed in a way no more specific code names. | Fix: Do not retry unchanged: fix the request first. | | `invalid_json` (`400`) | The body is not a JSON object. | Fix: Do not retry unchanged: fix the request first. | | `invalid_header` (`400`) | A header (`Idempotency-Key` or `Diffio-End-User`) is too long. | Fix: Do not retry unchanged: fix the request first. | | `invalid_parameter` (`400`) | A query parameter is not valid; `details.parameter` names it. | Fix: Do not retry unchanged: fix the request first. | | `missing_field` (`400`) | A required body field is missing; `details.field` names it. | Fix: Do not retry unchanged: fix the request first. | | `invalid_field` (`400`) | A body field is not valid, `details.field` names it when it is one field (for an edit, words that change nothing are `invalid_field` with field words). | Fix: Do not retry unchanged: fix the request first. | | `unknown_model` (`400`) | model names no Diffio model; `details.models` lists them. | Fix: Do not retry unchanged: fix the request first. | | `usage_period_too_large` (`400`) | The usage period has too many generations for one report. | Fix: Ask for a shorter period. | `401` `403` ### API key and permission | Code | Meaning | What to do | | --- | --- | --- | | `missing_api_key` (`401`) | No API key was sent. | Fix: Do not retry unchanged: fix the request first. | | `invalid_api_key` (`401`) | The API key is not valid. | Fix: Do not retry unchanged: fix the request first. | | `unauthenticated` (`401`) | The request could not be authenticated. | Fix: Do not retry unchanged: fix the request first. | | `permission_denied` (`403`) | The key is not active, or lacks the scope or the read or write permission this route needs. | Fix: Do not retry with this key: use a key with the right scope. | `402` ### Billing | Code | Meaning | What to do | | --- | --- | --- | | `payment_required` (`402`) | The account cannot start this work. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | | `insufficient_credit` (`402`) | The prepaid balance does not cover the most this could bill. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | | `usage_limit_reached` (`402`) | The account reached the monthly usage limit it set. | Pay: Retry after raising the limit, or next month. | | `payment_failed` (`402`) | The account's last payment failed. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | | `needs_payment_method` (`402`) | The free credit is used up and the account has no card. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | `404` `405` ### Not found and wrong method | Code | Meaning | What to do | | --- | --- | --- | | `not_found` (`404`) | What the path names does not exist. | Fix: Do not retry unchanged: fix the request first. | | `route_not_found` (`404`) | No version-two route has that path. | Fix: Do not retry unchanged: fix the request first. | | `project_not_found` (`404`) | No project of this account (and end user, with `Diffio-End-User`) has that id. | Fix: Do not retry unchanged: fix the request first. | | `generation_not_found` (`404`) | No generation of the project has that id. | Fix: Do not retry unchanged: fix the request first. | | `export_not_found` (`404`) | No export of the generation has that id. | Fix: Do not retry unchanged: fix the request first. | | `share_not_found` (`404`) | No share has that id, or it was revoked. | Stop: Do not retry: this will not change. | | `transcript_not_found` (`404`) | A finished generation has no stored transcript (results made before transcripts were kept). | Stop: Do not retry: this will not change. | | `transcript_assistant_turn_not_found` (`404`) | No assistant turn has that id. | Fix: Do not retry unchanged: fix the request first. | | `method_not_allowed` (`405`) | The route does not take this method; Allow names those it does. | Fix: Do not retry unchanged: fix the request first. | `409` ### State conflicts | Code | Meaning | What to do | | --- | --- | --- | | `conflict` (`409`) | Another request changed or revoked the same share at the same time, and the later one won. | Fix: Read the resource again, then retry with what it now says. | | `revision_conflict` (`409`) | A save named a revision that is no longer current; `details.current_revision` is the current one. | Fix: Read the resource again, then retry with what it now says. | | `idempotency_key_conflict` (`409`) | The `Idempotency-Key` was used for a different request. | Fix: Use a new key for a different request. | | `not_ready` (`409`) | Not yet: what the request needs is still being made (a generation still running, separated tracks or a transcript still being prepared). `details.generation_status` or `details.transcription_status` says which. | Retry: Retry the same request shortly (after a second or more, backing off). | | `not_available` (`409`) | Never, for this resource: it failed, it will never have what the request needs, or its project is being deleted. `details.transcription_status` says the transcript's state where it matters. | Stop: Do not retry: this will not change. | | `not_editable` (`409`) | This result's transcript cannot be edited: it is not a finished Pro result that kept what an edit needs, or shortening (tighten) was asked of a video project. | Stop: Do not retry: this will not change. | | `too_many_exports` (`409`) | Four exports of this generation are already rendering. | Retry: Retry once one of them finishes. | | `leveling_not_available` (`409`) | Leveling cannot be applied to this generation. | Fix: Retry without leveling. | | `video_not_available` (`409`) | An mp4 was asked for and the project has no video. | Fix: Retry with an audio format. | | `generation_in_progress` (`409`) | A generation of the project is still running; `details.generation_ids` names them. | Retry: Retry once they finish. | | `upload_already_received` (`409`) | The project's file has already been uploaded. | Stop: Do not retry: this will not change. | | `upload_missing` (`409`) | The upload has not completed yet. | Fix: Finish the upload, then retry. | | `project_exists` (`409`) | A project with that id already exists. | Fix: Read the resource again, then retry with what it now says. | | `generation_unavailable` (`409`) | The project or the API key was removed while it ran. | Stop: Do not retry: this will not change. | `413` `415` `422` ### Content | Code | Meaning | What to do | | --- | --- | --- | | `payload_too_large` (`413`) | The request is too large. | Fix: Do not retry unchanged: fix the request first. | | `upload_too_large` (`413`) | The file is larger than the upload limit. | Fix: Do not retry unchanged: fix the request first. | | `transcript_draft_too_large` (`413`) | A draft's data is over 900,000 bytes as JSON. | Fix: Do not retry unchanged: fix the request first. | | `unsupported_media_type` (`415`) | The file type cannot be restored. | Fix: Do not retry unchanged: fix the request first. | | `transcript_unreadable` (`422`) | The generation's stored transcript cannot be read. | Stop: Do not retry: this will not change. | `429` ### Rate limits | Code | Meaning | What to do | | --- | --- | --- | | `rate_limited` (`429`) | Too many requests of this kind in a short time. | Retry: Retry later, backing off. | `5xx` ### Diffio's side | Code | Meaning | What to do | | --- | --- | --- | | `internal_error` (`500` `502`) | Diffio could not complete the request. | Retry: Retry with exponential backoff; quote `request_id` if it keeps happening. | | `generation_start_failed` (`500`) | The generation was created but could not be started. | Retry: Retry with exponential backoff; quote `request_id` if it keeps happening. | | `unavailable` (`503`) | A service the request needs is unavailable. | Retry: Retry with exponential backoff; quote `request_id` if it keeps happening. | | `edit_not_queued` (`503`) | The edit could not be queued; nothing was billed. | Retry: Retry the same request shortly (after a second or more, backing off). | | `assistant_unavailable` (`503`) | The edit assistant is unavailable. | Retry: Retry with exponential backoff; quote `request_id` if it keeps happening. | ### Failed generation | Code | Meaning | What to do | | --- | --- | --- | | `restoration_failed` | Restoring the audio failed. | Retry: Create a new generation. | | `no_speech_detected` | No speech was heard in the recording. | Stop: Do not retry this file: it has no speech to restore. | | `media_too_long` | The recording is longer than the length limit. | Stop: Do not retry this file: upload a shorter one. | | `transcription_failed` | Transcribing the recording failed on Diffio's side. | Retry: Create a new generation (`error.retryable` is true). | | `cancelled` | The generation was cancelled. | Retry: Create a new generation. | | `timed_out` | The generation did not finish in the time allowed. | Retry: Create a new generation. | | `invalid_input` | The recording could not be read as it is. | Stop: Do not retry this file: export the recording again. | | `edit_not_queued` | The transcript edit could not be queued. | Retry: Send the edit again (`edited_transcript` in a playback grant holds its words). | | `upload_missing` | The project's upload never arrived. | Retry: Upload the file again (`POST .../upload)`, then create a new generation. | | `preprocessing_failed` | The upload could not be prepared. | Stop: Do not retry this file: upload another export of it. | | `needs_payment_method` | The account had no card once the recording's length was known. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | | `insufficient_credit` | The prepaid balance did not cover the recording. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | | `usage_limit_reached` | The account reached its monthly usage limit. | Pay: Create a new generation after raising the limit. | | `payment_failed` | The account's last payment failed. | Pay: Retry once the account can pay (add credit or a payment method in the dashboard). | | `expired` | The generation waited too long to start. | Retry: Create a new generation. | | `restored_video_failed` | Making the restored video (mp4) failed. | Retry: Create a new generation. | | `generation_invalid` | The generation's request could not be started. | Retry: Create a new generation. | | `unsupported_model` | The model the generation named is not served. | Retry: Create a new generation with a model from `GET /v2/models`. | | `job_missing` | The generation's job was lost before it started. | Retry: Create a new generation. | | `start_failed` | The generation could not be started. | Retry: Create a new generation. | | `generation_failed` | The generation failed for another reason. | Retry: Create a new generation; quote its id if it keeps happening. | ### Failed project | Code | Meaning | What to do | | --- | --- | --- | | `media_processing_failed` | The upload could not be prepared. | Retry: Create a new project with another export of the recording. | | `project_failed` | The project failed for another reason. | Retry: Create a new project. | ### Failed export | Code | Meaning | What to do | | --- | --- | --- | | `export_failed` | Rendering the export failed. | Retry: Ask for the export again (`POST .../exports` renders it again). | ### Failed assistant turn | Code | Meaning | What to do | | --- | --- | --- | | `rate_limited` | Too many assistant requests in a few minutes, or a day's worth of use. | Retry: Ask again later. | | `assistant_timeout` | The assistant did not finish the turn. | Retry: Ask again, perhaps something narrower. | | `assistant_unavailable` | The assistant is unavailable. | Retry: Ask again shortly. | | `not_editable` | The result stopped being editable while the turn ran. | Stop: Do not retry: this will not change. | | `invalid_field` | The assistant could not read the request. | Stop: Do not retry unchanged: fix the request first. | | `permission_denied` | The account may not use the assistant. | Stop: Do not retry: this will not change. | | `unauthenticated` | The turn's owner could not be named. | Retry: Ask again. | | `project_not_found` | The project went away while the turn ran. | Stop: Do not retry: this will not change. | | `internal_error` | The turn failed on Diffio's side. | Retry: Ask again. | The same table is in the OpenAPI document as `x-error-codes` on the `Error` and `ResourceError` schemas (`GET https://api.diffio.ai/v2/openapi.json`). ## Related pages - [API reference introduction](https://diffio.ai/docs/api-reference/introduction/): The error shape, base URL, authentication and request conventions. - [Billing](https://diffio.ai/docs/overview/administration/billing/): What the 402 codes mean for credit and card billing. - [Get a generation](https://diffio.ai/docs/api-reference/get-generation/): Where a failed generation reports its error. - [Webhooks](https://diffio.ai/docs/developers/webhooks/): The failed events that carry a resource error. --- Source: https://diffio.ai/docs/api-reference/list-models/ # List models Lists every model ID accepted when creating a generation, along with its status (`hosted`, `alias`, or `retired`), serving model, and hourly USD list price. Public; requires no API key. GET `https://api.diffio.ai/v2/models` - Key scope: None (public) - Auth header: No API key needed - Body: None ## Request Takes no parameters, headers, or request body. ## Example request **Python** ```python from diffio import DiffioClient # A public call: no API key needed. client = DiffioClient() models = client.models.list() ``` **Node.js** ```javascript import { DiffioClient } from "diffio" // A public call: no API key needed. const client = new DiffioClient() const models = await client.models.list() ``` **cURL** ```bash curl "https://api.diffio.ai/v2/models" ``` ## Response Returns a `list` object containing all model entries (`next_cursor` is always `null`). Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `object` | string | Always | Resource type, always `"list"`. | | `data` | array | Always | All accepted model entries: hosted models first, then tier aliases (`diffio-flash`, `diffio-pro`), then retired model names. [Fields below](#fields-data) | | `next_cursor` | string \| null | Always | Always `null`; all models are returned in one response. | **`data[]` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `data[].id` | string | Always | Model identifier accepted in `model` when creating a generation. | | `data[].object` | string | Always | Resource type, always `"model"`. | | `data[].status` | string | Always | `hosted` for active models, `alias` for rolling tier pointers, or `retired` for older names that substitute to a hosted model. | | `data[].label` | string \| null | Always | Display name for hosted models and aliases, or `null` for retired model names. | | `data[].served_by` | string | Always | Hosted model ID that executes generations requesting this model. | | `data[].price_per_hour_usd` | number | Always | Hourly list price in USD (`5` for Flash, `10` for Pro; retired models report the lower of their last list price and `served_by`). | ## Example response (200) **Excerpt: Response: excerpt (one entry of each kind)** ```json { "object": "list", "data": [ { "id": "diffio-4.7-flash", "object": "model", "status": "hosted", "label": "Diffio 4.7 Flash", "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-flash", "object": "model", "status": "alias", "label": "Diffio 4.7 Flash", "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-2", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 } ], "next_cursor": null } ``` **Full response: Successful response** ```json { "object": "list", "data": [ { "id": "diffio-4.7-flash", "object": "model", "status": "hosted", "label": "Diffio 4.7 Flash", "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-4.7-pro", "object": "model", "status": "hosted", "label": "Diffio 4.7 Pro", "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-flash", "object": "model", "status": "alias", "label": "Diffio 4.7 Flash", "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-pro", "object": "model", "status": "alias", "label": "Diffio 4.7 Pro", "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-2", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-2-flash", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-2.0", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-2.0-flash", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-3.0", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-3.2", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-3.4", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-3.5", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-4.0", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-4.0-flash", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-4.0-pro", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-4.5-flash", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-4.5-pro", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 }, { "id": "diffio-4.6-flash", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-flash", "price_per_hour_usd": 5 }, { "id": "diffio-4.6-pro", "object": "model", "status": "retired", "label": null, "served_by": "diffio-4.7-pro", "price_per_hour_usd": 10 } ], "next_cursor": null } ``` ## Return codes - `200` Returns every model entry with its serving model and hourly USD price. - **`405` Same on every endpoint** - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response **Error response** ```json { "error": { "code": "method_not_allowed", "message": "/models accepts GET.", "request_id": "70968c6cd6534e1e9f1547f19966f424" } } ``` ## Notes - Pass `diffio-flash` or `diffio-pro` to always run the newest hosted model in that tier without changing your code. - Requests naming a `retired` model run on `served_by` with `substituted: true` on the generation and bill the lower of the two list prices. - See [Models](https://diffio.ai/docs/overview/models/) for quality and speed guidance between Flash and Pro. ## Related pages - Previous: [API reference introduction](https://diffio.ai/docs/api-reference/introduction/): Base URL, authentication, errors and every endpoint. - Next: [Create a project](https://diffio.ai/docs/api-reference/create-project/): Create a project for one audio or video file and receive multipart upload instructions. - [Models](https://diffio.ai/docs/overview/models/): Choosing between Diffio 4.7 Flash and Pro. - [API pricing](https://diffio.ai/api-pricing/): The current rate per hour for each model. --- Source: https://diffio.ai/docs/api-reference/create-project/ # Create a project Creates a project for one audio or video recording and returns pre-built multipart upload instructions (`upload.requests`). Pass `generation` to queue the first restore immediately so it starts automatically as soon as the upload is ready. POST `https://api.diffio.ai/v2/projects` - Key scope: `projects:write` - Auth header: `Authorization: Bearer ` - Body: JSON **The HTTP upload sequence, call by call** 1. POST `/projects` id and upload 2. POST `upload.requests.start.url` uploadId 3. PUT `upload.requests.part.url (one per part)` etag per part 4. POST `upload.requests.complete.url` sizeBytes, etag 5. POST `/projects/{project_id}/upload/complete` optional; status preparing or ready Every edge call: `Authorization: Bearer {upload_token}` Parts ≤ 32 MiB (`part_size_bytes`, numbered from 1) ## Request Send a JSON object naming the recording (`file_name`) and optional file size, MIME type, metadata, or initial `generation`. ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Assigns the new project to `end_user` and scopes `Idempotency-Key` to that end user. | | `Idempotency-Key` | string | No | Optional key (up to 255 characters) for safe retries. Repeating the same request returns the original project; changing any body field returns `409` (`idempotency_key_conflict`). | ### Body fields | Field | Type | Required | Description | | --- | --- | --- | --- | | `file_name` | string | Yes | Recording filename with a supported audio or video extension. | | `content_type` | string | No | Recording MIME type (for example `audio/mpeg` or `video/mp4`); defaults to `application/octet-stream` when omitted. | | `size_bytes` | integer | No | File size in bytes when known, from `0` up to `2147483648` (2 GB). | | `metadata` | object | No | Optional string-to-string map saved on the project (up to 50 keys; each key up to 40 characters, each value up to 500 characters). | | `generation` | object | No | Optional initial restore to queue immediately (`latest_generation`); requires `generations:write` scope in addition to `projects:write`. [Fields below](#fields-generation) | **`generation` fields** | Field | Type | Required | Description | | --- | --- | --- | --- | | `generation.model` | string | Yes | Model ID from `GET /models`, such as `diffio-flash` or `diffio-pro`. | | `generation.sampling` | object | No | Optional advanced sampling overrides object. | | `generation.label` | string | No | Optional caller-defined name for the generation (up to 120 characters). | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) project = client.projects.create( file_name="interview.mp3", content_type="audio/mpeg", size_bytes=510957, metadata={"order_id": "1042"}, end_user="customer-mwe8tm1g", idempotency_key="v2docs-a-mwe8tm1g", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const project = await client.projects.create( { file_name: "interview.mp3", content_type: "audio/mpeg", size_bytes: 510957, metadata: { "order_id": "1042" }, }, { endUser: "customer-mwe8tm1g", idempotencyKey: "v2docs-a-mwe8tm1g", }, ) ``` **cURL** ```bash curl -X POST "https://api.diffio.ai/v2/projects" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Diffio-End-User: customer-mwe8tm1g" \ -H "Idempotency-Key: v2docs-a-mwe8tm1g" \ -H "Content-Type: application/json" \ -d '{ "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "metadata": { "order_id": "1042" } }' ``` **JSON: JSON body** ```json { "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "metadata": { "order_id": "1042" } } ``` ## Response Returns the new `project` (`status: "awaiting_upload"`) with signed multipart `upload` instructions valid for 24 hours. Success: `201` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Unique project identifier (UUID). | | `object` | string | Always | Resource type, always `"project"`. | | `status` | string | Always | Upload and preparation state: `awaiting_upload` until bytes arrive, `preparing` while media is probed, `ready` when ready to restore, or `failed`. | | `latest_generation` | object \| null | Always | Newest `Generation` object on this project, or `null` when no generation exists yet. | | `upload` | object \| null | Always | Multipart upload instructions for sending the file to the media edge, or `null` on an idempotent replay after the upload has arrived. [Fields below](#fields-upload) | **`upload` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `upload.upload_session_id` | string | Always | Upload session identifier (`api-{project_id}`). | | `upload.edge_base_url` | string | Always | Origin URL of the media upload edge (`https://media.diffio.io`). | | `upload.upload_token` | string | Always | Signed bearer token sent as `Authorization: Bearer ` on every upload edge request. | | `upload.part_size_bytes` | integer | Always | Required byte length for every upload part except the last (`33554432`, 32 MiB). | | `upload.max_bytes` | integer | Always | Maximum total upload size in bytes (`2147483648`, 2 GB). | | `upload.expires_at` | string | Always | ISO 8601 UTC timestamp when `upload_token` expires (24 hours after minting); renew via `POST /projects/{project_id}/upload`. | | `upload.requests` | object | Always | Pre-built HTTP request descriptors for the multipart upload (`start`, `part`, `complete`, `abort`). | | `upload.requests.start` | object | Always | Descriptor (`method`, `url`, `headers`, `body`, `returns`, `description`) called once first to obtain `uploadId`. | | `upload.requests.part` | object | Always | Descriptor called once per part (numbered from `1`) with raw bytes as the `PUT` body; save each returned `etag`. | | `upload.requests.complete` | object | Always | Descriptor called once after all parts finish, sending `uploadId` and the ordered `parts` array (`partNumber`, `etag`). | | `upload.requests.abort` | object | Always | Optional descriptor to discard uploaded parts for an unfinished `uploadId`. | **Other response fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `file_name` | string \| null | Always | Recording filename as sent at creation, or `null`. | | `content_type` | string \| null | Always | MIME type sent at creation (`application/octet-stream` when none was sent), or `null`. | | `size_bytes` | integer \| null | Always | File size in bytes: the uploaded byte count once the upload arrives, before that the `size_bytes` sent at creation; `null` when unknown. | | `duration_seconds` | number \| null | Always | Recording duration in seconds once `status` is `ready`, or `null` while awaiting upload or preparing. | | `has_video` | boolean | Always | True when the recording has video: inferred from `content_type` or the file name until the upload is probed, then from the file itself. | | `end_user` | string \| null | Always | End-user identifier from the `Diffio-End-User` header at creation, or `null` for account-level projects. | | `metadata` | object | Always | Key-value string map saved with the project (`{}` when none was supplied). | | `generation_count` | integer | Always | Total number of generations created for this project. | | `video_preview_status` | string \| null | Always | State of a video project's picture-only HLS stream (`video_hls`): `preparing`, `ready`, or `failed`; `null` for audio projects. | | `share_id` | string \| null | Always | Public 17-character share identifier while a share is published, or `null` when unshared. | | `created_at` | string \| null | Always | ISO 8601 UTC timestamp when the project was created, or `null`. | | `updated_at` | string \| null | Always | ISO 8601 UTC timestamp when the project last changed, or `null`. | | `error` | object \| null | Always | Failure details when `status` is `failed`, or `null` otherwise. | | `error.code` | string | Always | Stable `snake_case` project failure code (`media_processing_failed` or `project_failed`). | | `error.message` | string | Always | Human-readable explanation of why the upload could not be prepared. | ## Example response (201) **Response, key fields: Response: key fields** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "awaiting_upload", "latest_generation": null, "upload": { "upload_token": "v1.REDACTED", "part_size_bytes": 33554432, "expires_at": "2026-11-14T00:33:21.812909Z", "requests": { "start": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/start", "headers": { "Authorization": "Bearer v1.REDACTED" }, "body": null, "returns": [ "uploadId", "partSizeBytes", "maxBytes" ], "description": "Once, first. Keep uploadId for the other requests." } } } } ``` **Full response: Successful response** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "awaiting_upload", "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "duration_seconds": null, "has_video": false, "end_user": "customer-mwe8tm1g", "metadata": { "order_id": "1042" }, "generation_count": 0, "video_preview_status": null, "latest_generation": null, "share_id": null, "created_at": "2026-11-13T00:33:21.812909Z", "updated_at": "2026-11-13T00:33:21.812909Z", "error": null, "upload": { "upload_session_id": "api-62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "edge_base_url": "https://media.diffio.io", "upload_token": "v1.REDACTED", "part_size_bytes": 33554432, "max_bytes": 2147483648, "expires_at": "2026-11-14T00:33:21.812909Z", "requests": { "start": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/start", "headers": { "Authorization": "Bearer v1.REDACTED" }, "body": null, "returns": [ "uploadId", "partSizeBytes", "maxBytes" ], "description": "Once, first. Keep uploadId for the other requests." }, "part": { "method": "PUT", "url": "https://media.diffio.io/v1/uploads/parts/{part_number}?uploadId={upload_id}", "headers": { "Authorization": "Bearer v1.REDACTED", "Content-Length": "{part_length}" }, "body": null, "returns": [ "partNumber", "etag" ], "description": "Once per part, numbered from 1; the body is the part's raw bytes. Every part but the last is exactly part_size_bytes. Keep each etag." }, "complete": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/complete", "headers": { "Authorization": "Bearer v1.REDACTED", "Content-Type": "application/json" }, "body": { "uploadId": "{upload_id}", "parts": [ { "partNumber": "{part_number}", "etag": "{etag}" } ] }, "returns": [ "sizeBytes", "etag" ], "description": "Once, after every part, listing every part. Repeating it is safe." }, "abort": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/abort", "headers": { "Authorization": "Bearer v1.REDACTED", "Content-Type": "application/json" }, "body": { "uploadId": "{upload_id}" }, "returns": [], "description": "Optional: drop an unfinished upload's parts." } } } } ``` ## Return codes - `201` Project created with multipart `upload` instructions (and queued `latest_generation` when `generation` was sent). - `400` - Malformed JSON: [`invalid_json`](https://diffio.ai/docs/api-reference/errors/#invalid_json) - Missing `file_name`: [`missing_field`](https://diffio.ai/docs/api-reference/errors/#missing_field) - Invalid body field: [`invalid_field`](https://diffio.ai/docs/api-reference/errors/#invalid_field) - Oversized header: [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - Unknown `generation.model`: [`unknown_model`](https://diffio.ai/docs/api-reference/errors/#unknown_model) - `402` When `generation` is included and the account cannot pay for the first restore (checked at the 60-second minimum until the upload is probed); see the error codes below. [`insufficient_credit`](https://diffio.ai/docs/api-reference/errors/#insufficient_credit) [`needs_payment_method`](https://diffio.ai/docs/api-reference/errors/#needs_payment_method) [`payment_failed`](https://diffio.ai/docs/api-reference/errors/#payment_failed) [`usage_limit_reached`](https://diffio.ai/docs/api-reference/errors/#usage_limit_reached) - `403` Key is inactive or lacks `projects:write`, or `generations:write` when `generation` is included. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `409` Reused `Idempotency-Key` with different request fields. [`idempotency_key_conflict`](https://diffio.ai/docs/api-reference/errors/#idempotency_key_conflict) - `413` `size_bytes` exceeds the 2 GB (`2,147,483,648` bytes) upload limit. [`upload_too_large`](https://diffio.ai/docs/api-reference/errors/#upload_too_large) - `415` File extension or `content_type` is not a supported audio or video format. [`unsupported_media_type`](https://diffio.ai/docs/api-reference/errors/#unsupported_media_type) - `500` Initial `generation` could not be started and nothing was charged, or server error. [`generation_start_failed`](https://diffio.ai/docs/api-reference/errors/#generation_start_failed) [`internal_error`](https://diffio.ai/docs/api-reference/errors/#internal_error) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Error codes | Status | Code | Meaning | Also returned | | --- | --- | --- | --- | | `402` | [`insufficient_credit`](https://diffio.ai/docs/api-reference/errors/#insufficient_credit) | Your API credit is used up, or cannot cover this file. | `estimated_cost_cents` `remaining_credit_cents` | | `402` | [`needs_payment_method`](https://diffio.ai/docs/api-reference/errors/#needs_payment_method) | Card billing accounts: no payment method, and the credit is used up or cannot cover this file. | `estimated_cost_cents` `remaining_credit_cents` (when the credit was read) | | `402` | [`payment_failed`](https://diffio.ai/docs/api-reference/errors/#payment_failed) | A payment for API usage failed, or the last invoice of ended card billing is unpaid. | `details` omitted | | `402` | [`usage_limit_reached`](https://diffio.ai/docs/api-reference/errors/#usage_limit_reached) | Unbilled usage reached $100; it is being charged now. | `details` omitted | | `409` | [`idempotency_key_conflict`](https://diffio.ai/docs/api-reference/errors/#idempotency_key_conflict) | Idempotency-Key was already used with different request fields. | `details` omitted | ### Example error response **Error response** ```json { "error": { "code": "insufficient_credit", "message": "This file needs about $1.25 of API credit and your balance is $0.40. Add credit in the developer dashboard to continue.", "request_id": "f064e4099097414da3fb5b37684ab1bb", "details": { "estimated_cost_cents": 125, "remaining_credit_cents": 40 } } } ``` ## Notes - Upload the recording by executing `upload.requests.start`, `upload.requests.part` (32 MiB parts except the last), and `upload.requests.complete`, or call `client.projects.upload(...)` in the Python and Node.js SDKs. - Files can be up to 2 GB (`2,147,483,648` bytes) with no media length limit. - After `upload.requests.complete` succeeds, the upload edge reports completion automatically within about 30 seconds; call [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/) to make readiness immediate. ## Related pages - Previous: [List models](https://diffio.ai/docs/api-reference/list-models/): List every hosted model, tier alias, and retired model name with hourly list pricing. - Next: [List projects](https://diffio.ai/docs/api-reference/list-projects/): List projects on the account newest first with cursor pagination. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [Diffio API overview](https://diffio.ai/api-overview/): The cloud batch workflow and SDKs on one page. --- Source: https://diffio.ai/docs/api-reference/list-projects/ # List projects Lists the account's projects newest first, including each project's `latest_generation`. Pass `Diffio-End-User` to restrict results to one end user. GET `https://api.diffio.ai/v2/projects` - Key scope: `projects:read` - Auth header: `Authorization: Bearer ` - Body: None 1. GET `/projects?limit=20` `data[]` newest first, `next_cursor` 2. GET `/projects?cursor={next_cursor}` until `next_cursor` is `null` 3. Next [/projects/{project_id}/generations](https://diffio.ai/docs/api-reference/list-project-generations/) with a project's `id` ## Request Pass optional `limit` and `cursor` query parameters to page through projects. ### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `limit` | integer | No | Maximum number of items to return per page, from `1` to `100` (default `20`). | | `cursor` | string | No | Opaque pagination token from the previous page's `next_cursor`. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) page = client.projects.list() ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const page = await client.projects.list() ``` **cURL** ```bash curl "https://api.diffio.ai/v2/projects" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns a `list` page of `project` objects ordered from newest to oldest, with `next_cursor` for the next page. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `object` | string | Always | Resource type, always `"list"`. | | `data` | array | Always | Page of `Project` objects (same fields as [Get a project](https://diffio.ai/docs/api-reference/get-project/)), newest first. | | `next_cursor` | string \| null | Always | Opaque cursor to pass as `cursor` for the next page, or `null` on the final page. | ## Example response (200) **Response, key fields: Response: key fields** ```json { "object": "list", "data": [ { "id": "73118d99-36cf-4039-8005-b962d522fff7", "status": "ready", "file_name": "sermon clip.mp3" }, { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "status": "ready", "file_name": "interview.mp3" } ], "next_cursor": null } ``` **Full response: Successful response** ```json { "object": "list", "data": [ { "id": "73118d99-36cf-4039-8005-b962d522fff7", "object": "project", "status": "ready", "file_name": "sermon clip.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "duration_seconds": 31.9, "has_video": false, "end_user": "customer-mwe8tm1g", "metadata": {}, "generation_count": 1, "video_preview_status": null, "latest_generation": { "id": "73c84c4a-c1ca-5485-b396-171ab632d4b7", "object": "generation", "project_id": "73118d99-36cf-4039-8005-b962d522fff7", "status": "complete", "stage": "complete", "stage_progress": null, "queue": null, "warnings": [], "label": "First pass", "kind": "restore", "source_generation_id": null, "edit": null, "transcript_editable": true, "duration_seconds": 31.8, "quality_score": 4.518, "transcription_status": "ready", "files_available": [ "audio", "audio_mixed", "hls_master", "hls_original", "hls_restored", "metadata", "stems_manifest", "transcript", "waveform_original", "waveform_restored" ], "error": null, "model": "diffio-4.7-pro", "requested_model": "diffio-pro", "substituted": false, "price_per_hour_usd": 10, "stems_status": "ready", "created_at": "2026-11-13T00:33:29.591679Z", "updated_at": "2026-11-13T00:33:47.290000Z" }, "share_id": null, "created_at": "2026-11-13T00:33:29.384479Z", "updated_at": "2026-11-13T00:33:31.899000Z", "error": null }, { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "ready", "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "duration_seconds": 31.9, "has_video": false, "end_user": "customer-mwe8tm1g", "metadata": { "order_id": "1042" }, "generation_count": 1, "video_preview_status": null, "latest_generation": { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "status": "complete", "stage": "complete", "stage_progress": null, "queue": null, "warnings": [], "label": "Take 1", "kind": "restore", "source_generation_id": null, "edit": null, "transcript_editable": false, "duration_seconds": 31.8, "quality_score": 4.572, "transcription_status": "ready", "files_available": [ "audio", "audio_mixed", "hls_master", "hls_original", "hls_restored", "metadata", "stems_manifest", "transcript", "waveform_original", "waveform_restored" ], "error": null, "model": "diffio-4.7-flash", "requested_model": "diffio-flash", "substituted": false, "price_per_hour_usd": 5, "stems_status": "ready", "created_at": "2026-11-13T00:33:27.117344Z", "updated_at": "2026-11-13T00:33:40.864000Z" }, "share_id": null, "created_at": "2026-11-13T00:33:21.812909Z", "updated_at": "2026-11-13T00:33:27.117344Z", "error": null } ], "next_cursor": null } ``` ## Return codes - `200` Returns a page of projects and `next_cursor`. - `400` Invalid `limit` or `cursor` query value, or `Diffio-End-User` exceeds 128 characters. [`invalid_parameter`](https://diffio.ai/docs/api-reference/errors/#invalid_parameter) [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `projects:read`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Without `Diffio-End-User`, the response lists every project on the account regardless of which API key or end user created it. - Each item includes `latest_generation` so a project list UI can show restore progress without extra calls. - In Python use `client.projects.iter()`, and in Node.js use `for await (const project of client.projects.list())`, to walk every page automatically. ## Related pages - Previous: [Create a project](https://diffio.ai/docs/api-reference/create-project/): Create a project for one audio or video file and receive multipart upload instructions. - Next: [Get a project](https://diffio.ai/docs/api-reference/get-project/): Retrieve one project's upload status, media metadata, and latest generation. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [Diffio API overview](https://diffio.ai/api-overview/): The cloud batch workflow and SDKs on one page. --- Source: https://diffio.ai/docs/api-reference/get-project/ # Get a project Returns one project, including its upload `status`, probed `duration_seconds` and `has_video`, active `share_id`, and `latest_generation`. GET `https://api.diffio.ai/v2/projects/{project_id}` - Key scope: `projects:read` - Auth header: `Authorization: Bearer ` - Body: None ## Request Pass `project_id` in the path; takes no request body. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) project = client.projects.get( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const project = await client.projects.get( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **cURL** ```bash curl "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns the `project` object. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Unique project identifier (UUID). | | `object` | string | Always | Resource type, always `"project"`. | | `status` | string | Always | Upload and preparation state: `awaiting_upload` until bytes arrive, `preparing` while media is probed, `ready` when ready to restore, or `failed`. | | `file_name` | string \| null | Always | Recording filename as sent at creation, or `null`. | | `content_type` | string \| null | Always | MIME type sent at creation (`application/octet-stream` when none was sent), or `null`. | | `size_bytes` | integer \| null | Always | File size in bytes: the uploaded byte count once the upload arrives, before that the `size_bytes` sent at creation; `null` when unknown. | | `duration_seconds` | number \| null | Always | Recording duration in seconds once `status` is `ready`, or `null` while awaiting upload or preparing. | | `has_video` | boolean | Always | True when the recording has video: inferred from `content_type` or the file name until the upload is probed, then from the file itself. | | `end_user` | string \| null | Always | End-user identifier from the `Diffio-End-User` header at creation, or `null` for account-level projects. | | `metadata` | object | Always | Key-value string map saved with the project (`{}` when none was supplied). | | `generation_count` | integer | Always | Total number of generations created for this project. | | `video_preview_status` | string \| null | Always | State of a video project's picture-only HLS stream (`video_hls`): `preparing`, `ready`, or `failed`; `null` for audio projects. | | `share_id` | string \| null | Always | Public 17-character share identifier while a share is published, or `null` when unshared. | | `latest_generation` | object \| null | Always | Newest `Generation` object on this project, or `null` when no generation exists yet. | | `created_at` | string \| null | Always | ISO 8601 UTC timestamp when the project was created, or `null`. | | `updated_at` | string \| null | Always | ISO 8601 UTC timestamp when the project last changed, or `null`. | | `error` | object \| null | Always | Failure details when `status` is `failed`, or `null` otherwise. | | `error.code` | string | Always | Stable `snake_case` project failure code (`media_processing_failed` or `project_failed`). | | `error.message` | string | Always | Human-readable explanation of why the upload could not be prepared. | ## Example response (200) **Successful response** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "awaiting_upload", "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "duration_seconds": null, "has_video": false, "end_user": "customer-mwe8tm1g", "metadata": { "order_id": "1042" }, "generation_count": 0, "video_preview_status": null, "latest_generation": null, "share_id": null, "created_at": "2026-11-13T00:33:21.812909Z", "updated_at": "2026-11-13T00:33:21.812909Z", "error": null } ``` ## Return codes - `200` Returns the requested project. - `400` `Diffio-End-User` exceeds 128 characters. [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `projects:read`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` No project with that `project_id` exists for this account and end user. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - `status` transitions from `awaiting_upload` to `preparing` to `ready` (or `failed` with `error` if the uploaded file cannot be decoded). - Once `status` is `ready`, `duration_seconds` and `has_video` reflect the probed file; `size_bytes` is the uploaded byte count from when the upload arrives. - Upload credentials are not returned here; call [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/) if an upload has not arrived yet. ## Related pages - Previous: [List projects](https://diffio.ai/docs/api-reference/list-projects/): List projects on the account newest first with cursor pagination. - Next: [Delete a project](https://diffio.ai/docs/api-reference/delete-project/): Delete a project and all of its stored uploads, generations, exports, and shares. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [Diffio API overview](https://diffio.ai/api-overview/): The cloud batch workflow and SDKs on one page. --- Source: https://diffio.ai/docs/api-reference/delete-project/ # Delete a project Deletes a project and everything stored for it: the original upload, every generation, separated tracks, rendered exports, transcript drafts, assistant turns, and any published share. DELETE `https://api.diffio.ai/v2/projects/{project_id}` - Key scope: `projects:write` - Auth header: `Authorization: Bearer ` - Body: None ## Request Pass `project_id` in the path; takes no request body. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) deleted = client.projects.delete( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const deleted = await client.projects.delete( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **cURL** ```bash curl -X DELETE "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns deletion counts once the project and its stored media objects are removed. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Identifier of the deleted project. | | `object` | string | Always | Resource type, always `"project"`. | | `deleted` | boolean | Always | Always `true` when deletion completes. | | `deleted_generations` | integer | Always | Number of generations removed with the project. | | `deleted_media_objects` | integer | Always | Number of stored media files deleted. | ## Example response (200) **Successful response** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "deleted": true, "deleted_generations": 1, "deleted_media_objects": 48 } ``` ## Return codes - `200` Project and all stored records and media files were deleted. - `400` `Diffio-End-User` exceeds 128 characters. [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `projects:write`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` No project with that `project_id` exists for this account and end user. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) - `409` A generation on the project is still queued or processing, with `details.generation_ids` listing it. [`generation_in_progress`](https://diffio.ai/docs/api-reference/errors/#generation_in_progress) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Refused with `409` (`generation_in_progress`) while a generation is running, except a queued generation waiting for an upload that never arrived (deleted uncharged with the project). - Any published share is revoked first (existing share URLs stop working within about 60 seconds), and signed media URLs stop resolving once objects are deleted. - Usage already charged stays on your account's billing records, but the deleted generations no longer count in [Get usage](https://diffio.ai/docs/api-reference/usage-summary/). If a delete is interrupted midway, calling `DELETE` again finishes the cleanup. ## Related pages - Previous: [Get a project](https://diffio.ai/docs/api-reference/get-project/): Retrieve one project's upload status, media metadata, and latest generation. - Next: [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/): Mint fresh 24-hour multipart upload instructions for a project awaiting its file. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [Diffio API overview](https://diffio.ai/api-overview/): The cloud batch workflow and SDKs on one page. --- Source: https://diffio.ai/docs/api-reference/reopen-project-upload/ # Get new upload instructions Returns fresh multipart `upload` instructions (with a new 24-hour `upload_token`) for a project whose file has not arrived yet. POST `https://api.diffio.ai/v2/projects/{project_id}/upload` - Key scope: `projects:write` - Auth header: `Authorization: Bearer ` - Body: None ## Request Pass `project_id` in the path; send no body (or `{}`). ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) project = client.projects.reopen_upload( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const project = await client.projects.reopenUpload( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **cURL** ```bash curl -X POST "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/upload" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns the `project` with renewed `upload` descriptors pointing to the same destination. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Unique project identifier (UUID). | | `object` | string | Always | Resource type, always `"project"`. | | `status` | string | Always | Upload and preparation state: `awaiting_upload` until bytes arrive, `preparing` while media is probed, `ready` when ready to restore, or `failed`. | | `upload` | object \| null | Always | Multipart upload instructions for sending the file to the media edge, or `null` on an idempotent replay after the upload has arrived. [Fields below](#fields-upload) | **`upload` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `upload.upload_session_id` | string | Always | Upload session identifier (`api-{project_id}`). | | `upload.edge_base_url` | string | Always | Origin URL of the media upload edge (`https://media.diffio.io`). | | `upload.upload_token` | string | Always | Signed bearer token sent as `Authorization: Bearer ` on every upload edge request. | | `upload.part_size_bytes` | integer | Always | Required byte length for every upload part except the last (`33554432`, 32 MiB). | | `upload.max_bytes` | integer | Always | Maximum total upload size in bytes (`2147483648`, 2 GB). | | `upload.expires_at` | string | Always | ISO 8601 UTC timestamp when `upload_token` expires (24 hours after minting); renew via `POST /projects/{project_id}/upload`. | | `upload.requests` | object | Always | Pre-built HTTP request descriptors for the multipart upload (`start`, `part`, `complete`, `abort`). | | `upload.requests.start` | object | Always | Descriptor (`method`, `url`, `headers`, `body`, `returns`, `description`) called once first to obtain `uploadId`. | | `upload.requests.part` | object | Always | Descriptor called once per part (numbered from `1`) with raw bytes as the `PUT` body; save each returned `etag`. | | `upload.requests.complete` | object | Always | Descriptor called once after all parts finish, sending `uploadId` and the ordered `parts` array (`partNumber`, `etag`). | | `upload.requests.abort` | object | Always | Optional descriptor to discard uploaded parts for an unfinished `uploadId`. | **Other response fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `file_name` | string \| null | Always | Recording filename as sent at creation, or `null`. | | `content_type` | string \| null | Always | MIME type sent at creation (`application/octet-stream` when none was sent), or `null`. | | `size_bytes` | integer \| null | Always | File size in bytes: the uploaded byte count once the upload arrives, before that the `size_bytes` sent at creation; `null` when unknown. | | `duration_seconds` | number \| null | Always | Recording duration in seconds once `status` is `ready`, or `null` while awaiting upload or preparing. | | `has_video` | boolean | Always | True when the recording has video: inferred from `content_type` or the file name until the upload is probed, then from the file itself. | | `end_user` | string \| null | Always | End-user identifier from the `Diffio-End-User` header at creation, or `null` for account-level projects. | | `metadata` | object | Always | Key-value string map saved with the project (`{}` when none was supplied). | | `generation_count` | integer | Always | Total number of generations created for this project. | | `video_preview_status` | string \| null | Always | State of a video project's picture-only HLS stream (`video_hls`): `preparing`, `ready`, or `failed`; `null` for audio projects. | | `share_id` | string \| null | Always | Public 17-character share identifier while a share is published, or `null` when unshared. | | `latest_generation` | object \| null | Always | Newest `Generation` object on this project, or `null` when no generation exists yet. | | `created_at` | string \| null | Always | ISO 8601 UTC timestamp when the project was created, or `null`. | | `updated_at` | string \| null | Always | ISO 8601 UTC timestamp when the project last changed, or `null`. | | `error` | object \| null | Always | Failure details when `status` is `failed`, or `null` otherwise. | | `error.code` | string | Always | Stable `snake_case` project failure code (`media_processing_failed` or `project_failed`). | | `error.message` | string | Always | Human-readable explanation of why the upload could not be prepared. | ## Example response (200) **Response, key fields: Response: key fields** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "awaiting_upload", "upload": { "upload_token": "v1.REDACTED", "part_size_bytes": 33554432, "expires_at": "2026-11-14T00:33:21.812909Z", "requests": { "start": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/start", "headers": { "Authorization": "Bearer v1.REDACTED" }, "body": null, "returns": [ "uploadId", "partSizeBytes", "maxBytes" ], "description": "Once, first. Keep uploadId for the other requests." } } } } ``` **Full response: Successful response** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "awaiting_upload", "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "duration_seconds": null, "has_video": false, "end_user": "customer-mwe8tm1g", "metadata": { "order_id": "1042" }, "generation_count": 0, "video_preview_status": null, "latest_generation": null, "share_id": null, "created_at": "2026-11-13T00:33:21.812909Z", "updated_at": "2026-11-13T00:33:21.812909Z", "error": null, "upload": { "upload_session_id": "api-62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "edge_base_url": "https://media.diffio.io", "upload_token": "v1.REDACTED", "part_size_bytes": 33554432, "max_bytes": 2147483648, "expires_at": "2026-11-14T00:33:21.812909Z", "requests": { "start": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/start", "headers": { "Authorization": "Bearer v1.REDACTED" }, "body": null, "returns": [ "uploadId", "partSizeBytes", "maxBytes" ], "description": "Once, first. Keep uploadId for the other requests." }, "part": { "method": "PUT", "url": "https://media.diffio.io/v1/uploads/parts/{part_number}?uploadId={upload_id}", "headers": { "Authorization": "Bearer v1.REDACTED", "Content-Length": "{part_length}" }, "body": null, "returns": [ "partNumber", "etag" ], "description": "Once per part, numbered from 1; the body is the part's raw bytes. Every part but the last is exactly part_size_bytes. Keep each etag." }, "complete": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/complete", "headers": { "Authorization": "Bearer v1.REDACTED", "Content-Type": "application/json" }, "body": { "uploadId": "{upload_id}", "parts": [ { "partNumber": "{part_number}", "etag": "{etag}" } ] }, "returns": [ "sizeBytes", "etag" ], "description": "Once, after every part, listing every part. Repeating it is safe." }, "abort": { "method": "POST", "url": "https://media.diffio.io/v1/uploads/abort", "headers": { "Authorization": "Bearer v1.REDACTED", "Content-Type": "application/json" }, "body": { "uploadId": "{upload_id}" }, "returns": [], "description": "Optional: drop an unfinished upload's parts." } } } } ``` ## Return codes - `200` Returns the project with renewed 24-hour `upload` instructions. - `400` Malformed JSON body, or `Diffio-End-User` exceeds 128 characters. [`invalid_json`](https://diffio.ai/docs/api-reference/errors/#invalid_json) [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `projects:write`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` No project with that `project_id` exists for this account and end user. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) - `409` The project's file has already arrived, with `details.project_status` reporting its current status. [`upload_already_received`](https://diffio.ai/docs/api-reference/errors/#upload_already_received) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Only projects in `status: "awaiting_upload"` accept new upload instructions; once the upload arrives, create a new project to upload a different file. - Both SDKs call this from `projects.upload(...)` when you pass a project id instead of the created project; the Python SDK also calls it when `upload.expires_at` is less than 60 seconds away. ## Related pages - Previous: [Delete a project](https://diffio.ai/docs/api-reference/delete-project/): Delete a project and all of its stored uploads, generations, exports, and shares. - Next: [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/): Verify and prepare a finished multipart upload immediately instead of waiting for edge callback. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [Diffio API overview](https://diffio.ai/api-overview/): The cloud batch workflow and SDKs on one page. --- Source: https://diffio.ai/docs/api-reference/complete-project-upload/ # Complete a project's upload Optional call after `upload.requests.complete` that probes and prepares the uploaded recording immediately, starting any queued generation right away. POST `https://api.diffio.ai/v2/projects/{project_id}/upload/complete` - Key scope: `projects:write` - Auth header: `Authorization: Bearer ` - Body: None **The HTTP upload sequence, call by call** 1. POST `/projects` id and upload 2. POST `upload.requests.start.url` uploadId 3. PUT `upload.requests.part.url (one per part)` etag per part 4. POST `upload.requests.complete.url` sizeBytes, etag 5. POST `/projects/{project_id}/upload/complete` optional; status preparing or ready Every edge call: `Authorization: Bearer {upload_token}` Parts ≤ 32 MiB (`part_size_bytes`, numbered from 1) ## Request Pass `project_id` in the path after all parts and `upload.requests.complete` have succeeded; takes no body. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) project = client.projects.complete_upload( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const project = await client.projects.completeUpload( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **cURL** ```bash curl -X POST "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/upload/complete" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns the updated `project` (`preparing`, `ready`, or `failed`), including `latest_generation`. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Unique project identifier (UUID). | | `object` | string | Always | Resource type, always `"project"`. | | `status` | string | Always | Upload and preparation state: `awaiting_upload` until bytes arrive, `preparing` while media is probed, `ready` when ready to restore, or `failed`. | | `file_name` | string \| null | Always | Recording filename as sent at creation, or `null`. | | `content_type` | string \| null | Always | MIME type sent at creation (`application/octet-stream` when none was sent), or `null`. | | `size_bytes` | integer \| null | Always | File size in bytes: the uploaded byte count once the upload arrives, before that the `size_bytes` sent at creation; `null` when unknown. | | `duration_seconds` | number \| null | Always | Recording duration in seconds once `status` is `ready`, or `null` while awaiting upload or preparing. | | `has_video` | boolean | Always | True when the recording has video: inferred from `content_type` or the file name until the upload is probed, then from the file itself. | | `end_user` | string \| null | Always | End-user identifier from the `Diffio-End-User` header at creation, or `null` for account-level projects. | | `metadata` | object | Always | Key-value string map saved with the project (`{}` when none was supplied). | | `generation_count` | integer | Always | Total number of generations created for this project. | | `video_preview_status` | string \| null | Always | State of a video project's picture-only HLS stream (`video_hls`): `preparing`, `ready`, or `failed`; `null` for audio projects. | | `share_id` | string \| null | Always | Public 17-character share identifier while a share is published, or `null` when unshared. | | `latest_generation` | object \| null | Always | Newest `Generation` object on this project, or `null` when no generation exists yet. | | `created_at` | string \| null | Always | ISO 8601 UTC timestamp when the project was created, or `null`. | | `updated_at` | string \| null | Always | ISO 8601 UTC timestamp when the project last changed, or `null`. | | `error` | object \| null | Always | Failure details when `status` is `failed`, or `null` otherwise. | | `error.code` | string | Always | Stable `snake_case` project failure code (`media_processing_failed` or `project_failed`). | | `error.message` | string | Always | Human-readable explanation of why the upload could not be prepared. | ## Example response (200) **Successful response** ```json { "id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "object": "project", "status": "ready", "file_name": "interview.mp3", "content_type": "audio/mpeg", "size_bytes": 510957, "duration_seconds": 31.9, "has_video": false, "end_user": "customer-mwe8tm1g", "metadata": { "order_id": "1042" }, "generation_count": 0, "video_preview_status": null, "latest_generation": null, "share_id": null, "created_at": "2026-11-13T00:33:21.812909Z", "updated_at": "2026-11-13T00:33:26.311000Z", "error": null } ``` ## Return codes - `200` Upload verified and the updated `project` is returned. - `400` Malformed JSON body, or `Diffio-End-User` exceeds 128 characters. [`invalid_json`](https://diffio.ai/docs/api-reference/errors/#invalid_json) [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `projects:write`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` No project with that `project_id` exists for this account and end user. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) - `409` Upload bytes have not finished landing in storage yet. [`upload_missing`](https://diffio.ai/docs/api-reference/errors/#upload_missing) - `413` Stored upload exceeds the 2 GB (`2,147,483,648` bytes) limit. [`upload_too_large`](https://diffio.ai/docs/api-reference/errors/#upload_too_large) - `503` Storage service temporarily unavailable while verifying the upload (code unavailable). - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Calling this endpoint is optional: the media upload edge notifies Diffio automatically about 30 seconds after `upload.requests.complete` finishes. - Safe to repeat; calling it again on an already `ready` project returns the current `project` unchanged. - If probing reveals an unreadable or unsupported media container, the call returns `200` with `status: "failed"` and `error.code: "media_processing_failed"`. ## Related pages - Previous: [Get new upload instructions](https://diffio.ai/docs/api-reference/reopen-project-upload/): Mint fresh 24-hour multipart upload instructions for a project awaiting its file. - Next: [Create a generation](https://diffio.ai/docs/api-reference/create-generation/): Start a speech restoration generation on a project with a chosen model. - [Full API guide](https://diffio.ai/docs/developers/full-api-guide/): Every topic, limit and concept in one index. - [Diffio API overview](https://diffio.ai/api-overview/): The cloud batch workflow and SDKs on one page. --- Source: https://diffio.ai/docs/api-reference/create-generation/ # Create a generation Starts a speech restoration run on a project's recording using the specified `model`. Accepted while the upload is still in progress: the generation waits in `queued` and starts automatically once the project is `ready`. POST `https://api.diffio.ai/v2/projects/{project_id}/generations` - Key scope: `generations:write` - Auth header: `Authorization: Bearer ` - Body: JSON 1. POST [/projects](https://diffio.ai/docs/api-reference/create-project/) `id` 2. POST `/projects/{project_id}/generations` `id` 3. GET [/projects/{project_id}/generations/{generation_id}](https://diffio.ai/docs/api-reference/get-generation/) `status` 4. GET [/projects/{project_id}/generations/{generation_id}/media](https://diffio.ai/docs/api-reference/get-generation-media/) `files` **Replays and conflicts, case by case** - First request `201` new generation - Same `Idempotency-Key`, same body `201` the same generation `id` - Same `Idempotency-Key`, other `model`, `sampling` or `label` `409` `idempotency_key_conflict` ## Request Specify `model` (`diffio-flash`, `diffio-pro`, or any ID from `GET /models`) and optional `label` or `sampling`. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | | `Idempotency-Key` | string | No | Optional key (up to 255 characters) for safe retries. Repeating the same request returns the original generation; changing `model`, `sampling`, or `label` returns `409` (`idempotency_key_conflict`). | ### Body fields | Field | Type | Required | Description | | --- | --- | --- | --- | | `model` | string | Yes | Model ID from `GET /models`, such as `diffio-flash`, `diffio-pro`, `diffio-4.7-flash`, or `diffio-4.7-pro`. | | `sampling` | object | No | Optional advanced sampling overrides object. | | `label` | string | No | Optional caller-defined name for this generation (up to 120 characters), such as `"Take 1"`. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) generation = client.generations.create( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", model="diffio-flash", label="Take 1", idempotency_key="v2docs-g-mwe8tm1g", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const generation = await client.generations.create( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", { model: "diffio-flash", label: "Take 1", }, { idempotencyKey: "v2docs-g-mwe8tm1g" }, ) ``` **cURL** ```bash curl -X POST "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/generations" \ -H "Authorization: Bearer $DIFFIO_API_KEY" \ -H "Idempotency-Key: v2docs-g-mwe8tm1g" \ -H "Content-Type: application/json" \ -d '{ "model": "diffio-flash", "label": "Take 1" }' ``` **JSON: JSON body** ```json { "model": "diffio-flash", "label": "Take 1" } ``` ## Response Returns the new `generation` (`status: "queued"` or `"processing"`). Success: `201` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Unique generation identifier (UUID). | | `object` | string | Always | Resource type, always `"generation"`. | | `status` | string | Always | Lifecycle state: `queued`, `processing`, `complete`, or `failed`. | | `model` | string \| null | Always | Hosted model that ran or is running (such as `diffio-4.7-flash` or `diffio-4.7-pro`), or `null`. | | `stage` | string \| null | Always | Current worker stage (`pending`, `preparing`, `transcribing`, `queued`, `starting`, `downloading`, `decoding`, `restoring`, `finalizing`, `uploading`, then `complete` or `failed`), or `null`. | | `stage_progress` | object \| null | Always | Live worker progress while `status` is `processing`, or `null` before a worker reports progress and after completion. [Fields below](#fields-stage-progress) | | `queue` | object \| null | Always | Worker queue snapshot while the generation waits to start, or `null` otherwise. [Fields below](#fields-queue) | | `error` | object \| null | Always | Failure details when `status` is `failed` (also includes boolean `retryable` and nullable `explanation` on the wire), or `null` otherwise. | | `error.code` | string | Always | Stable `snake_case` generation failure code (such as `restoration_failed`, `no_speech_detected`, `transcription_failed`, `upload_missing`, or `generation_failed`). | | `error.message` | string | Always | Human-readable message explaining why the generation failed. | **`stage_progress` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `stage_progress.overall_percent` | number | Sometimes | Overall generation completion percentage from `0` to `100`, present once reported. | | `stage_progress.stage_percent` | number | Sometimes | Completion percentage of the current `stage` from `0` to `100`, present once reported. | | `stage_progress.bytes_done` | number | Sometimes | Bytes transferred so far in a `downloading` or `uploading` stage. | | `stage_progress.bytes_total` | number | Sometimes | Total bytes to transfer in the current `downloading` or `uploading` stage. | | `stage_progress.available_through_seconds` | number | Sometimes | Seconds of restored output already playable via `hls_master` while processing. | | `stage_progress.duration_seconds` | number | Sometimes | Recording length in seconds as reported by the worker. | **`queue` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `queue.position` | integer \| null | Always | Number of queued jobs ahead of this generation, or `null`. | | `queue.connected_workers` | integer \| null | Always | Total workers connected to the queue, or `null`. | | `queue.idle_workers` | integer \| null | Always | Connected workers currently idle, or `null`. | | `queue.busy_workers` | integer \| null | Always | Connected workers currently running jobs, or `null`. | | `queue.wait_reason` | string \| null | Always | Why the job is waiting (`all_busy`, `no_workers`, or `next_in_line`), or `null`. | | `queue.message` | string | Always | Human-readable message explaining why the generation is waiting. | **Other response fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `project_id` | string | Always | Identifier of the parent project. | | `requested_model` | string \| null | Always | Model name sent in the request (hosted model, tier alias, or retired model), or `null`. | | `substituted` | boolean | Always | True when `requested_model` was a retired model name and ran on the current hosted model of the same tier; `false` for hosted names and aliases. | | `price_per_hour_usd` | number \| null | Always | List price per hour in USD applied to this generation (for retired models, the lower of the requested and serving models' list prices), or `null`. | | `warnings` | array | Always | Non-fatal warnings recorded during processing (the generation still runs). [Fields below](#fields-warnings) | | `label` | string \| null | Always | Caller-supplied label (up to 120 characters), `Transcript edit` for an edit, or `null` when none was set. | | `kind` | string | Always | Generation kind: `restore` for a full recording restore, or `edit` for a transcript edit of a finished Pro generation. | | `source_generation_id` | string \| null | Always | For `kind: "edit"`, the Pro generation that was edited; `null` for `restore`. | | `edit` | object \| null | Always | Transcript edit details and progress when `kind` is `edit`, or `null` for `restore`. [Fields below](#fields-edit) | | `transcript_editable` | boolean | Always | True when this result's transcript can be edited via `POST .../edits` (a finished Pro result with stored edit latents). | | `duration_seconds` | number \| null | Always | Duration of the restored output in seconds once known, or `null`. | | `quality_score` | number \| null | Always | Estimated speech quality score of the result from `1` to `5`, or `null`. | | `transcription_status` | string \| null | Always | Word-timed transcript status: `preparing`, `ready`, or `failed`; `null` when no transcription is reported. | | `files_available` | array | Always | Sorted names of artifacts currently available from `GET .../media` (such as `audio`, `video`, `hls_master`, `transcript`, `stems_manifest`). | | `stems_status` | string \| null | Always | Separated speech and background track status: `preparing`, `ready`, or `failed`; `null` when none are reported. | | `created_at` | string \| null | Always | ISO 8601 UTC timestamp when the generation was created, or `null`. | | `updated_at` | string \| null | Always | ISO 8601 UTC timestamp when the generation last changed, or `null`. | **`warnings[]` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `warnings[].code` | string | Always | Warning code; `unsupported_language` when the transcript contains words in languages the model cannot restore. | | `warnings[].languages` | array | Sometimes | ISO 639-1 language codes of unsupported words, ordered by word count. | | `warnings[].message` | string | Always | Human-readable warning message. | **`edit` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `edit.edit_count` | integer \| null | Always | Number of edits (each run of changed, inserted, or removed words between kept words counts once), or `null`. | | `edit.max_windows` | integer \| null | Always | Maximum number of 30-second windows this edit could restore, or `null`. | | `edit.windows` | integer \| null | Always | Actual number of windows restored (or being restored) by the worker, or `null` before starting. | | `edit.windows_done` | integer \| null | Always | Number of restore windows completed so far, or `null`. | | `edit.ranges` | array | Always | Time ranges on the recording (in seconds) covered by the restored windows. | | `edit.ranges[].start` | number | Sometimes | Window start time in seconds. | | `edit.ranges[].end` | number | Sometimes | Window end time in seconds. | | `edit.billable_seconds` | integer \| null | Always | Seconds billed once complete (`30` per restored window, `0` when no window was restored), or `null` until complete. | | `edit.cut_seconds` | number \| null | Always | Seconds trimmed from the recording by `tighten`, or `null`. | | `edit.request_id` | string \| null | Always | Caller-supplied `request_id` from the edit request, or `null`. | | `edit.language` | string \| null | Always | Primary language code used for the edit, or `null`. | | `edit.tighten` | object \| null | Always | Silence-shortening settings applied by the edit, or `null` when none were requested. | | `edit.tighten.close_removed_gaps` | boolean | Always | Whether silence left by removed words was closed. | | `edit.tighten.max_pause_seconds` | number \| null | Always | Maximum pause duration in seconds after shortening, or `null` when pauses were left unchanged. | ## Example response (201) **Response, key fields: Response: key fields** ```json { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "status": "processing", "stage": "preparing", "stage_progress": null, "queue": null, "error": null, "model": "diffio-4.7-flash" } ``` **Full response: Successful response** ```json { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "status": "processing", "stage": "preparing", "stage_progress": null, "queue": null, "warnings": [], "label": "Take 1", "kind": "restore", "source_generation_id": null, "edit": null, "transcript_editable": false, "duration_seconds": null, "quality_score": null, "transcription_status": null, "files_available": [], "error": null, "model": "diffio-4.7-flash", "requested_model": "diffio-flash", "substituted": false, "price_per_hour_usd": 5, "stems_status": null, "created_at": "2026-11-13T00:33:27.117344Z", "updated_at": "2026-11-13T00:33:27.999000Z" } ``` ## Return codes - `201` Generation created and queued for restoration. - `400` - Malformed JSON: [`invalid_json`](https://diffio.ai/docs/api-reference/errors/#invalid_json) - Missing `model`: [`missing_field`](https://diffio.ai/docs/api-reference/errors/#missing_field) - Invalid `label` or `sampling`: [`invalid_field`](https://diffio.ai/docs/api-reference/errors/#invalid_field) - Oversized header: [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - Unrecognized `model`: [`unknown_model`](https://diffio.ai/docs/api-reference/errors/#unknown_model) - `402` The account cannot pay for this restore (checked at the 60-second minimum until the upload is probed); see the error codes below. [`insufficient_credit`](https://diffio.ai/docs/api-reference/errors/#insufficient_credit) [`needs_payment_method`](https://diffio.ai/docs/api-reference/errors/#needs_payment_method) [`payment_failed`](https://diffio.ai/docs/api-reference/errors/#payment_failed) [`usage_limit_reached`](https://diffio.ai/docs/api-reference/errors/#usage_limit_reached) - `403` Key is inactive or lacks `generations:write`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` No project with that `project_id` exists for this account and end user. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) - `409` - Reused `Idempotency-Key` with different body fields - The project failed or was removed - The API key was revoked - During admission Codes: [`idempotency_key_conflict`](https://diffio.ai/docs/api-reference/errors/#idempotency_key_conflict), [`generation_unavailable`](https://diffio.ai/docs/api-reference/errors/#generation_unavailable), - `500` Generation record was created without starting or billing; retry with the same `Idempotency-Key`. [`generation_start_failed`](https://diffio.ai/docs/api-reference/errors/#generation_start_failed) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Error codes | Status | Code | Meaning | Also returned | | --- | --- | --- | --- | | `402` | [`insufficient_credit`](https://diffio.ai/docs/api-reference/errors/#insufficient_credit) | Your API credit is used up, or cannot cover this file. | `estimated_cost_cents` `remaining_credit_cents` | | `402` | [`needs_payment_method`](https://diffio.ai/docs/api-reference/errors/#needs_payment_method) | Card billing accounts: no payment method, and the credit is used up or cannot cover this file. | `estimated_cost_cents` `remaining_credit_cents` (when the credit was read) | | `402` | [`payment_failed`](https://diffio.ai/docs/api-reference/errors/#payment_failed) | A payment for API usage failed, or the last invoice of ended card billing is unpaid. | `details` omitted | | `402` | [`usage_limit_reached`](https://diffio.ai/docs/api-reference/errors/#usage_limit_reached) | Unbilled usage reached $100; it is being charged now. | `details` omitted | | `409` | [`idempotency_key_conflict`](https://diffio.ai/docs/api-reference/errors/#idempotency_key_conflict) | Idempotency-Key was already used with different request fields. | `details` omitted | ### Example error response **Error response** ```json { "error": { "code": "insufficient_credit", "message": "This file needs about $1.25 of API credit and your balance is $0.40. Add credit in the developer dashboard to continue.", "request_id": "f064e4099097414da3fb5b37684ab1bb", "details": { "estimated_cost_cents": 125, "remaining_credit_cents": 40 } } } ``` ## Notes - Restores bill whole seconds rounded up with a 60-second minimum (`$5`/hour for `diffio-4.7-flash`, `$10`/hour for `diffio-4.7-pro`). Failed generations charge nothing. - Poll [Get a generation](https://diffio.ai/docs/api-reference/get-generation/) (or use `client.generations.wait(...)` or `generation.completed` / `generation.failed` webhooks), then fetch URLs from [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/). - Only finished Pro generations (`diffio-pro` / `diffio-4.7-pro`) set `transcript_editable: true` for [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/) and [Ask the edit assistant](https://diffio.ai/docs/api-reference/create-transcript-assistant-turn/). ## Related pages - Previous: [Complete a project's upload](https://diffio.ai/docs/api-reference/complete-project-upload/): Verify and prepare a finished multipart upload immediately instead of waiting for edge callback. - Next: [List a project's generations](https://diffio.ai/docs/api-reference/list-project-generations/): List every restore and transcript edit generation on a project, newest first. - [Models](https://diffio.ai/docs/overview/models/): Choosing between Diffio 4.7 Flash and Pro. - [API model cards](https://diffio.ai/api-model-cards/): Best uses for each model id. - [API pricing](https://diffio.ai/api-pricing/): The current rate per hour for each model. - [Webhooks guide](https://diffio.ai/docs/developers/webhooks/): Get notified when a generation finishes instead of polling. --- Source: https://diffio.ai/docs/api-reference/list-project-generations/ # List a project's generations Lists a project's generations (both full restores and transcript edits) newest first, one page at a time. GET `https://api.diffio.ai/v2/projects/{project_id}/generations` - Key scope: `generations:read` - Auth header: `Authorization: Bearer ` - Body: None 1. GET `/projects/{project_id}/generations` `data[]` newest first, `next_cursor` 2. Pick `status: complete` its `id` 3. GET [/projects/{project_id}/generations/{generation_id}/media](https://diffio.ai/docs/api-reference/get-generation-media/) `files` URLs ## Request Pass `project_id` in the path and optional `limit` and `cursor` query parameters. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | ### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `limit` | integer | No | Maximum number of items to return per page, from `1` to `100` (default `20`). | | `cursor` | string | No | Opaque pagination token from the previous page's `next_cursor`. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) page = client.generations.list( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const page = await client.generations.list( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", ) ``` **cURL** ```bash curl "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/generations" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns a `list` page of `Generation` objects ordered newest first, with `next_cursor`. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `object` | string | Always | Resource type, always `"list"`. | | `data` | array | Always | Page of `Generation` objects (same fields as [Get a generation](https://diffio.ai/docs/api-reference/get-generation/)), newest first. | | `next_cursor` | string \| null | Always | Opaque cursor to pass as `cursor` for the next page, or `null` on the final page. | ## Example response (200) **Response, key fields: Response: key fields** ```json { "object": "list", "data": [ { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "status": "complete", "model": "diffio-4.7-flash" } ], "next_cursor": null } ``` **Full response: Successful response** ```json { "object": "list", "data": [ { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "status": "complete", "stage": "complete", "stage_progress": null, "queue": null, "warnings": [], "label": "Take 1", "kind": "restore", "source_generation_id": null, "edit": null, "transcript_editable": false, "duration_seconds": 31.8, "quality_score": 4.572, "transcription_status": "ready", "files_available": [ "audio", "audio_mixed", "hls_master", "hls_original", "hls_restored", "metadata", "stems_manifest", "transcript", "waveform_original", "waveform_restored" ], "error": null, "model": "diffio-4.7-flash", "requested_model": "diffio-flash", "substituted": false, "price_per_hour_usd": 5, "stems_status": "ready", "created_at": "2026-11-13T00:33:27.117344Z", "updated_at": "2026-11-13T00:33:40.864000Z" } ], "next_cursor": null } ``` ## Return codes - `200` Returns a page of generations for the project. - `400` Invalid `limit` or `cursor` query value, or `Diffio-End-User` exceeds 128 characters. [`invalid_parameter`](https://diffio.ai/docs/api-reference/errors/#invalid_parameter) [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `generations:read`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` No project with that `project_id` exists for this account and end user. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Includes both `kind: "restore"` generations and `kind: "edit"` generations created by [Edit a generation's transcript](https://diffio.ai/docs/api-reference/create-transcript-edit/). - Use `client.generations.iter(project_id)` in Python or `for await (const gen of client.generations.list(projectId))` in Node.js to iterate through every page. ## Related pages - Previous: [Create a generation](https://diffio.ai/docs/api-reference/create-generation/): Start a speech restoration generation on a project with a chosen model. - Next: [Get a generation](https://diffio.ai/docs/api-reference/get-generation/): Check one generation's status, live stage progress, queue position, available files, or failure reason. - [Models](https://diffio.ai/docs/overview/models/): Choosing between Diffio 4.7 Flash and Pro. - [API model cards](https://diffio.ai/api-model-cards/): Best uses for each model id. - [API pricing](https://diffio.ai/api-pricing/): The current rate per hour for each model. - [Webhooks guide](https://diffio.ai/docs/developers/webhooks/): Get notified when a generation finishes instead of polling. --- Source: https://diffio.ai/docs/api-reference/get-generation/ # Get a generation Returns one generation, including its `status`, live `stage` and `stage_progress`, worker `queue` details, `files_available`, `stems_status`, `transcription_status`, and `error` when failed. GET `https://api.diffio.ai/v2/projects/{project_id}/generations/{generation_id}` - Key scope: `generations:read` - Auth header: `Authorization: Bearer ` - Body: None Overall `status` 1. queued 2. processing 3. complete 4. *or* failed `stage` while it runs 1. pending 2. preparing 3. transcribing 4. queued 5. starting 6. downloading 7. decoding 8. restoring 9. finalizing 10. uploading 11. complete 12. *or* failed `stage_progress` in the example response `overall_percent` 88% `available_through_seconds` 0 of 31.8 s **Poll until `status` is `complete` or `failed`.** ## Request Pass `project_id` and `generation_id` in the path; takes no request body. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | | `generation_id` | string | Yes | Unique identifier of the generation within the project. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) generation = client.generations.get( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "ce832a32-a1ce-516a-b8bd-75457bd8517f", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const generation = await client.generations.get( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "ce832a32-a1ce-516a-b8bd-75457bd8517f", ) ``` **cURL** ```bash curl "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns the `generation` object. Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `id` | string | Always | Unique generation identifier (UUID). | | `object` | string | Always | Resource type, always `"generation"`. | | `status` | string | Always | Lifecycle state: `queued`, `processing`, `complete`, or `failed`. | | `model` | string \| null | Always | Hosted model that ran or is running (such as `diffio-4.7-flash` or `diffio-4.7-pro`), or `null`. | | `stage` | string \| null | Always | Current worker stage (`pending`, `preparing`, `transcribing`, `queued`, `starting`, `downloading`, `decoding`, `restoring`, `finalizing`, `uploading`, then `complete` or `failed`), or `null`. | | `stage_progress` | object \| null | Always | Live worker progress while `status` is `processing`, or `null` before a worker reports progress and after completion. [Fields below](#fields-stage-progress) | | `queue` | object \| null | Always | Worker queue snapshot while the generation waits to start, or `null` otherwise. [Fields below](#fields-queue) | | `error` | object \| null | Always | Failure details when `status` is `failed` (also includes boolean `retryable` and nullable `explanation` on the wire), or `null` otherwise. | | `error.code` | string | Always | Stable `snake_case` generation failure code (such as `restoration_failed`, `no_speech_detected`, `transcription_failed`, `upload_missing`, or `generation_failed`). | | `error.message` | string | Always | Human-readable message explaining why the generation failed. | **`stage_progress` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `stage_progress.overall_percent` | number | Sometimes | Overall generation completion percentage from `0` to `100`, present once reported. | | `stage_progress.stage_percent` | number | Sometimes | Completion percentage of the current `stage` from `0` to `100`, present once reported. | | `stage_progress.bytes_done` | number | Sometimes | Bytes transferred so far in a `downloading` or `uploading` stage. | | `stage_progress.bytes_total` | number | Sometimes | Total bytes to transfer in the current `downloading` or `uploading` stage. | | `stage_progress.available_through_seconds` | number | Sometimes | Seconds of restored output already playable via `hls_master` while processing. | | `stage_progress.duration_seconds` | number | Sometimes | Recording length in seconds as reported by the worker. | **`queue` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `queue.position` | integer \| null | Always | Number of queued jobs ahead of this generation, or `null`. | | `queue.connected_workers` | integer \| null | Always | Total workers connected to the queue, or `null`. | | `queue.idle_workers` | integer \| null | Always | Connected workers currently idle, or `null`. | | `queue.busy_workers` | integer \| null | Always | Connected workers currently running jobs, or `null`. | | `queue.wait_reason` | string \| null | Always | Why the job is waiting (`all_busy`, `no_workers`, or `next_in_line`), or `null`. | | `queue.message` | string | Always | Human-readable message explaining why the generation is waiting. | **Other response fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `project_id` | string | Always | Identifier of the parent project. | | `requested_model` | string \| null | Always | Model name sent in the request (hosted model, tier alias, or retired model), or `null`. | | `substituted` | boolean | Always | True when `requested_model` was a retired model name and ran on the current hosted model of the same tier; `false` for hosted names and aliases. | | `price_per_hour_usd` | number \| null | Always | List price per hour in USD applied to this generation (for retired models, the lower of the requested and serving models' list prices), or `null`. | | `warnings` | array | Always | Non-fatal warnings recorded during processing (the generation still runs). [Fields below](#fields-warnings) | | `label` | string \| null | Always | Caller-supplied label (up to 120 characters), `Transcript edit` for an edit, or `null` when none was set. | | `kind` | string | Always | Generation kind: `restore` for a full recording restore, or `edit` for a transcript edit of a finished Pro generation. | | `source_generation_id` | string \| null | Always | For `kind: "edit"`, the Pro generation that was edited; `null` for `restore`. | | `edit` | object \| null | Always | Transcript edit details and progress when `kind` is `edit`, or `null` for `restore`. [Fields below](#fields-edit) | | `transcript_editable` | boolean | Always | True when this result's transcript can be edited via `POST .../edits` (a finished Pro result with stored edit latents). | | `duration_seconds` | number \| null | Always | Duration of the restored output in seconds once known, or `null`. | | `quality_score` | number \| null | Always | Estimated speech quality score of the result from `1` to `5`, or `null`. | | `transcription_status` | string \| null | Always | Word-timed transcript status: `preparing`, `ready`, or `failed`; `null` when no transcription is reported. | | `files_available` | array | Always | Sorted names of artifacts currently available from `GET .../media` (such as `audio`, `video`, `hls_master`, `transcript`, `stems_manifest`). | | `stems_status` | string \| null | Always | Separated speech and background track status: `preparing`, `ready`, or `failed`; `null` when none are reported. | | `created_at` | string \| null | Always | ISO 8601 UTC timestamp when the generation was created, or `null`. | | `updated_at` | string \| null | Always | ISO 8601 UTC timestamp when the generation last changed, or `null`. | **`warnings[]` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `warnings[].code` | string | Always | Warning code; `unsupported_language` when the transcript contains words in languages the model cannot restore. | | `warnings[].languages` | array | Sometimes | ISO 639-1 language codes of unsupported words, ordered by word count. | | `warnings[].message` | string | Always | Human-readable warning message. | **`edit` fields** | Field | Type | Present | Description | | --- | --- | --- | --- | | `edit.edit_count` | integer \| null | Always | Number of edits (each run of changed, inserted, or removed words between kept words counts once), or `null`. | | `edit.max_windows` | integer \| null | Always | Maximum number of 30-second windows this edit could restore, or `null`. | | `edit.windows` | integer \| null | Always | Actual number of windows restored (or being restored) by the worker, or `null` before starting. | | `edit.windows_done` | integer \| null | Always | Number of restore windows completed so far, or `null`. | | `edit.ranges` | array | Always | Time ranges on the recording (in seconds) covered by the restored windows. | | `edit.ranges[].start` | number | Sometimes | Window start time in seconds. | | `edit.ranges[].end` | number | Sometimes | Window end time in seconds. | | `edit.billable_seconds` | integer \| null | Always | Seconds billed once complete (`30` per restored window, `0` when no window was restored), or `null` until complete. | | `edit.cut_seconds` | number \| null | Always | Seconds trimmed from the recording by `tighten`, or `null`. | | `edit.request_id` | string \| null | Always | Caller-supplied `request_id` from the edit request, or `null`. | | `edit.language` | string \| null | Always | Primary language code used for the edit, or `null`. | | `edit.tighten` | object \| null | Always | Silence-shortening settings applied by the edit, or `null` when none were requested. | | `edit.tighten.close_removed_gaps` | boolean | Always | Whether silence left by removed words was closed. | | `edit.tighten.max_pause_seconds` | number \| null | Always | Maximum pause duration in seconds after shortening, or `null` when pauses were left unchanged. | ## Example response (200) **Response, key fields: Response: key fields** ```json { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "status": "processing", "stage": "finalizing", "stage_progress": { "overall_percent": 88, "stage_percent": 0, "available_through_seconds": 0, "duration_seconds": 31.8 }, "queue": null, "error": null, "model": "diffio-4.7-flash" } ``` **Full response: Successful response** ```json { "id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "object": "generation", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "status": "processing", "stage": "finalizing", "stage_progress": { "overall_percent": 88, "stage_percent": 0, "available_through_seconds": 0, "duration_seconds": 31.8 }, "queue": null, "warnings": [], "label": "Take 1", "kind": "restore", "source_generation_id": null, "edit": null, "transcript_editable": false, "duration_seconds": null, "quality_score": null, "transcription_status": "ready", "files_available": [], "error": null, "model": "diffio-4.7-flash", "requested_model": "diffio-flash", "substituted": false, "price_per_hour_usd": 5, "stems_status": null, "created_at": "2026-11-13T00:33:27.117344Z", "updated_at": "2026-11-13T00:33:36.673000Z" } ``` ## Return codes - `200` Returns the requested generation. - `400` `Diffio-End-User` exceeds 128 characters. [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `generations:read`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` Project not found, or no generation with `generation_id` belongs to this project. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) [`generation_not_found`](https://diffio.ai/docs/api-reference/errors/#generation_not_found) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Poll every couple of seconds until `status` is `complete` or `failed` (the SDKs' `generations.wait(...)` helper does this with a 2-second default interval), or subscribe to `generation.completed` and `generation.failed` webhooks. - Separated speech and background tracks can finish after `status` reaches `complete`; wait for `stems_status: "ready"` (or the `generation.stems_ready` webhook) before calling mix or export routes. - `hls_master` appears in `files_available` while the generation is still `processing` and can be streamed progressively via [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/). ## Related pages - Previous: [List a project's generations](https://diffio.ai/docs/api-reference/list-project-generations/): List every restore and transcript edit generation on a project, newest first. - Next: [Get a playback grant](https://diffio.ai/docs/api-reference/get-generation-media/): Mint 6-hour signed playback and download URLs for a generation's audio, video, HLS, stems, and transcript files. - [Models](https://diffio.ai/docs/overview/models/): Choosing between Diffio 4.7 Flash and Pro. - [API model cards](https://diffio.ai/api-model-cards/): Best uses for each model id. - [API pricing](https://diffio.ai/api-pricing/): The current rate per hour for each model. - [Webhooks guide](https://diffio.ai/docs/developers/webhooks/): Get notified when a generation finishes instead of polling. --- Source: https://diffio.ai/docs/api-reference/get-generation-media/ # Get a playback grant Mints a 6-hour playback and download grant (`files`) mapping each available artifact of the generation (plus the project's `original` upload) to a signed media URL. GET `https://api.diffio.ai/v2/projects/{project_id}/generations/{generation_id}/media` - Key scope: `artifacts:read` - Auth header: `Authorization: Bearer ` - Body: None ## Request Pass `project_id` and `generation_id` in the path, and optional `preview_seconds` in the query string. ### Path parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `project_id` | string | Yes | Unique identifier of the project. | | `generation_id` | string | Yes | Unique identifier of the generation within the project. | ### Query parameters | Field | Type | Required | Description | | --- | --- | --- | --- | | `preview_seconds` | integer | No | Optional playback limit in seconds, from `4` to `3600` (rounded up to whole 4-second segments). Omits full-length download files. | ### Headers | Field | Type | Required | Description | | --- | --- | --- | --- | | `Diffio-End-User` | string | No | Optional end-user identifier (up to 128 characters). Scopes the request to that end user's projects; omit to act across the whole account. | ## Example request **Python** ```python import os from diffio import DiffioClient key = os.environ["DIFFIO_API_KEY"] client = DiffioClient(api_key=key) media = client.generations.media( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "ce832a32-a1ce-516a-b8bd-75457bd8517f", ) ``` **Node.js** ```javascript import { DiffioClient } from "diffio" const client = new DiffioClient({ apiKey: process.env.DIFFIO_API_KEY, }) const media = await client.generations.media( "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "ce832a32-a1ce-516a-b8bd-75457bd8517f", ) ``` **cURL** ```bash curl "https://api.diffio.ai/v2/projects/62f62565-049f-5e7e-bbd2-9de0cf7ddbfe/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/media" \ -H "Authorization: Bearer $DIFFIO_API_KEY" ``` ## Response Returns `files` (artifact name to signed URL), `base_url`, and `expires_at` (6 hours from issuance). Success: `200` ### Response fields | Field | Type | Present | Description | | --- | --- | --- | --- | | `object` | string | Always | Resource type, always `"generation_media"`. | | `project_id` | string | Always | Identifier of the parent project. | | `generation_id` | string | Always | Identifier of the generation. | | `status` | string | Always | Current lifecycle status of the generation (`queued`, `processing`, `complete`, or `failed`). | | `files` | object | Always | Map of existing artifact names (`audio`, `video`, `audio_mixed`, `hls_master`, `hls_restored`, `hls_original`, `waveform_restored`, `waveform_original`, `transcript`, `stems_manifest`, `metadata`, `video_hls`, `edited_transcript`, `original`) to signed URLs. | | `base_url` | string | Always | Common URL prefix of every entry in `files`; relative entries inside HLS playlists and `stems_manifest` resolve against their own URL. | | `expires_at` | string | Always | ISO 8601 UTC timestamp when every URL in this grant expires (6 hours after creation); call again to mint fresh URLs. | | `preview_seconds` | integer \| null | Always | Effective preview cap in seconds (rounded up to a multiple of `4`), or `null` when full-length access was granted. | ## Example response (200) **Successful response** ```json { "object": "generation_media", "project_id": "62f62565-049f-5e7e-bbd2-9de0cf7ddbfe", "generation_id": "ce832a32-a1ce-516a-b8bd-75457bd8517f", "status": "complete", "base_url": "https://media.diffio.io/m/v1.REDACTED/", "expires_at": "2026-11-13T06:33:47Z", "preview_seconds": null, "files": { "audio": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/restored.mp3", "audio_mixed": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/mixed.mp3", "hls_master": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/hls/master.m3u8", "hls_original": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/hls/noisy/index.m3u8", "hls_restored": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/hls/clean/index.m3u8", "metadata": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/metadata.json", "original": "https://media.diffio.io/m/v1.REDACTED/original/interview.mp3", "stems_manifest": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/stems/4014a8c299444bbb866971bbb7b657ca/manifest.v2.json", "transcript": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/word_timestamps.json", "waveform_original": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/visualizations/hls_waveform_noisy.json", "waveform_restored": "https://media.diffio.io/m/v1.REDACTED/generations/ce832a32-a1ce-516a-b8bd-75457bd8517f/visualizations/hls_waveform_clean.json" } } ``` ## Return codes - `200` Returns signed media URLs valid until `expires_at`. - `400` `preview_seconds` is outside `4` to `3600`, or `Diffio-End-User` exceeds 128 characters. [`invalid_parameter`](https://diffio.ai/docs/api-reference/errors/#invalid_parameter) [`invalid_header`](https://diffio.ai/docs/api-reference/errors/#invalid_header) - `403` Key is inactive or lacks `artifacts:read`. [`permission_denied`](https://diffio.ai/docs/api-reference/errors/#permission_denied) - `404` Project not found, or generation not found on this project. [`project_not_found`](https://diffio.ai/docs/api-reference/errors/#project_not_found) [`generation_not_found`](https://diffio.ai/docs/api-reference/errors/#generation_not_found) - **`401` `405` Same on every endpoint** - `401` Missing API key (code missing_api_key), or invalid API key (code invalid_api_key). - `405` HTTP method not supported on this path; check the Allow header (code method_not_allowed). ### Example error response Errors are JSON: an `error` object with `code`, `message` and `request_id`. An unrecognized key returns `401`: **Error response** ```json { "error": { "code": "invalid_api_key", "message": "Invalid API key.", "request_id": "dead773b60e148fd9e22d680a22fa701" } } ``` ## Notes - Signed URLs in `files` require no `Authorization` header (safe for browser `