> For the complete documentation index, see [llms.txt](https://diffio.ai/llms.txt). This page is also available as HTML at 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
