# Podcast and audiobook from a translation

> Make a Persian podcast (two voices talking about the book) or a Persian audiobook (one narrator) from a finished PDF translation. Sequence: `GET /api/v1/audio/pricing` → `POST /api/v1/audio/jobs` (holds Fara) → poll `GET /api/v1/audio/jobs/{id}` until `awaiting_review` → optional `PATCH /api/v1/audio/jobs/{id}/segments/{segmentId}` → `POST /api/v1/audio/jobs/{id}/approve` → poll until `completed` → `GET /api/v1/audio/jobs/{id}/download`.

## At a glance

- Base path: `/api/v1/audio`
- Auth: `Authorization: Bearer fara_sk_...` ([Authentication](https://faraatarjomeh.com/api/v1/docs/authentication.md))
- Scope: `read` for GET, `write` for everything else
- Spends Fara: yes, `POST /api/v1/audio/jobs` holds Fara. Everything else is free.
- Async: yes. The script is ready in a few minutes; the audio takes a few more after approval.
- Needs: a translation job you own with status `completed` or `completed_partial` ([PDF translation](https://faraatarjomeh.com/api/v1/docs/guides/pdf-translation.md))
- Review: always. Every job stops at `awaiting_review` and waits until you approve or cancel. There is no time limit.
- Terminal statuses: `completed`, `failed`, `cancelled`
- Webhook events: `audio.awaiting_review`, `audio.completed`, `audio.failed`, `audio.cancelled`
- Output: MP3

## Before you start

### Price

```http
GET /api/v1/audio/pricing HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`:

```json
{
  "faraPerMin": 1.87,
  "podcast": { "targetMinutes": 12, "maxMinutes": 20, "holdFara": 46 },
  "audiobook": { "targetMinutes": 25, "minMinutes": 15, "maxMinutes": 30, "holdFara": 68 }
}
```

```bash
curl -sS "https://faraatarjomeh.com/api/v1/audio/pricing" -H "Authorization: Bearer $FARA_API_KEY"
```

| Field | Meaning |
|---|---|
| `podcast.holdFara`, `audiobook.holdFara` | Fara held at create: the price of the longest length plus 20%. The job is charged its real cost when it finishes and the rest is released. Compare it with the user's budget. |
| `targetMinutes` | Length the script aims for. |
| `minMinutes` | Audiobook: shortest length it aims for. |
| `maxMinutes` | Longest possible length. The hold pays for this length. |
| `faraPerMin` | Fara per minute of finished audio. `holdFara` = `maxMinutes × faraPerMin` plus 20%; the charge is about `real minutes × faraPerMin`, plus the cost of writing the script. After the script is ready, `estimatedCost` gives the price of that script. |

**The hold is for the maximum length; the charge is for the real length.** A 13-minute podcast holds 46 Fara and is charged about the price of 13 minutes. The rest comes back when the job finishes.

### Limits

| Limit | Value |
|---|---|
| Source | Your own translation job, `completed` or `completed_partial` |
| One at a time | One running job per translation and `feature`. A second create answers `409 DUPLICATE_JOB`. |
| Script segment | At most 2,800 characters per segment |
| Whole script | Podcast at most 22,000 characters, audiobook at most 33,000 (the maximum length plus 10%) |
| Rate limits | 120 requests per 60 s per API key; job creation 300 uploads per hour per account |

## Steps

### 1. Create the job

Send an `Idempotency-Key` (a new UUID per job). A success (and a `500`/`502`/`504`) is stored for 24 hours: sending the same key again returns that first answer and never charges twice. A `4xx` or `503` answer is not stored, so after you fix the request (or the user tops up) you can send it again with the same key.

```http
POST /api/v1/audio/jobs HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
Idempotency-Key: 7e3a1c90-5b2d-4f8e-a6c4-1d0b9e8f7a65

{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "feature": "audiobook",
  "voiceGender": "female"
}
```

Response `201 Created` (the new job, without its script):

```json
{
  "job": {
    "_id": "66f5c9a0b1d2e3f4a5b6c7d8",
    "feature": "audiobook",
    "translationJobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
    "status": "pending",
    "stage": "queued",
    "progress": 5,
    "voiceGender": "female",
    "cost": { "faraCharged": 600, "minutesBilled": 30 },
    "audio": null,
    "reviewVersion": 0,
    "customerErrorCode": null,
    "createdAt": "2026-09-25T11:00:00.000Z",
    "updatedAt": "2026-09-25T11:00:00.000Z",
    "completedAt": null,
    "failedAt": null
  }
}
```

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/audio/jobs" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"jobId":"3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70","feature":"audiobook","voiceGender":"female"}'
```

| Field | Type | Required | Default | Allowed values | Notes |
|---|---|---|---|---|---|
| `jobId` | string | yes | — | a translation job id | Must be yours and `completed` or `completed_partial`. |
| `feature` | string | yes | — | `podcast`, `audiobook` | `podcast`: two voices talk about the book. `audiobook`: one narrator. |
| `voiceId` | string | no | `male` | a voice `id` from `GET /api/v1/audio/voices`, `male`, `female` | Audiobook narrator. Anything else answers `400`. |
| `voiceGender` | string | no | `male` | `male`, `female` | Audiobook narrator, used when `voiceId` is left out. Ignored for `podcast` (stored as `null`). |
| `speaker1VoiceId` | string | no | the male default | a voice `id` | Podcast only: the first speaker. |
| `speaker2VoiceId` | string | no | the female default | a voice `id` | Podcast only: the second speaker. |
| `voiceMood` | string | no | `neutral` | `neutral`, `friendly`, `formal`, `happy`, `sad`, `calm`, `energetic`, `serious` | How the voices sound. Does not change the price. |

`GET /api/v1/audio/voices` lists the voices (`voices`: `id`, `gender`, Persian and English names, `previewUrl` of a short Persian sample) and the moods (`moods`). Always read the list from that call; voices can be added.

If a job for the same translation and `feature` is still `pending`, `active` or `awaiting_review`, the answer is `409 DUPLICATE_JOB` with `audioJobId` (the running job). Continue with that job instead.

### 2. Wait for the script

```http
GET /api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8 HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK` when the script is ready (trimmed):

```json
{
  "job": {
    "_id": "66f5c9a0b1d2e3f4a5b6c7d8",
    "feature": "audiobook",
    "status": "awaiting_review",
    "stage": "awaiting_review",
    "progress": 50,
    "reviewVersion": 0,
    "script": [
      { "id": "seg_0001", "title": "فصل اول", "text": "این کتاب با یک پرسش ساده آغاز می‌شود..." },
      { "id": "seg_0002", "text": "نویسنده در ادامه توضیح می‌دهد که..." }
    ],
    "estimatedMinutes": 24,
    "estimatedCost": { "faraCharged": 480, "minutesBilled": 24 },
    "cost": { "faraCharged": 600, "minutesBilled": 30 },
    "customerErrorCode": null
  }
}
```

```bash
curl -sS "https://faraatarjomeh.com/api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8" -H "Authorization: Bearer $FARA_API_KEY"
```

Poll every 15 seconds, or wait for the `audio.awaiting_review` webhook.

| Field | Type | Notes |
|---|---|---|
| `_id` | string | Audio job id (24 hex characters). Not the translation id. |
| `feature`, `translationJobId`, `voiceGender`, `voiceKey`, `speakerVoiceKeys`, `voiceMood` | | From create. `voiceKey` is the narrator's voice `id`; `speakerVoiceKeys` holds the podcast speakers' ids. |
| `status` | string | See [State machine](#state-machine). |
| `stage` | string | Display only: `queued`, `scripting`, `awaiting_review`, `synthesizing`, `finalizing`, `done`. More values can appear. |
| `script` | array | Only on `GET /api/v1/audio/jobs/{id}`. Items: `id` (`seg_0001` …), `text` (Persian). Podcast items also have `speaker` (`1` or `2`). Audiobook items can have `title`. |
| `estimatedMinutes` | number | Length of the script as it is now (whole minutes). |
| `estimatedCost` | object or null | Price of the script as it is now: `{ faraCharged, minutesBilled }`. The real charge is close to this. |
| `reviewVersion` | integer | Send it in `If-Match` on edits and approve. |
| `cost` | object | The hold while running; after `completed`, the real charge plus `heldFara` and `refundedFara`. |
| `audio` | object or null | After `completed`: `{ "durationSeconds": 1432.6 }`. |
| `customerErrorCode` | string or null | Why a `failed` job failed. |

### 3. Edit the script (optional)

Send the current `reviewVersion` in `If-Match`, bare (`1`) or quoted (`"1"`).

```http
PATCH /api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/segments/seg_0002 HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
If-Match: "0"

{"text": "نویسنده سپس نشان می‌دهد که..."}
```

Response `200 OK`:

```json
{
  "ok": true,
  "reviewVersion": 1,
  "estimatedMinutes": 24,
  "estimatedCost": { "faraCharged": 480, "minutesBilled": 24 }
}
```

```bash
curl -sS -X PATCH "https://faraatarjomeh.com/api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/segments/seg_0002" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Content-Type: application/json" \
  -H 'If-Match: "0"' -d '{"text":"نویسنده سپس نشان می‌دهد که..."}'
```

| Body field | Type | Required | Notes |
|---|---|---|---|
| `text` | string | yes | New Persian text for this segment. At most 2,800 characters (`413` with `maxChars`). The whole script must stay within 22,000 (podcast) or 33,000 (audiobook) characters (`413` with `maxChars`). |

Use the returned `reviewVersion` for the next call.

### 4. Approve

```http
POST /api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/approve HTTP/1.1
Authorization: Bearer fara_sk_...
If-Match: "1"
Idempotency-Key: c4d5e6f7-0a1b-4c2d-9e3f-4a5b6c7d8e9f
```

Response `200 OK`:

```json
{ "ok": true, "status": "active", "reviewVersion": 1 }
```

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/approve" \
  -H "Authorization: Bearer $FARA_API_KEY" -H 'If-Match: "1"' -H "Idempotency-Key: $(uuidgen)"
```

Approve uses the Fara already held. The job then makes the audio. Poll every 20 seconds until `completed`.

### 5. Download the MP3

Needs `status: "completed"`, else `409`.

```http
GET /api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/download HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`, `Content-Type: audio/mpeg`, `Accept-Ranges: bytes`, `Content-Disposition: attachment; filename="audiobook-66f5c9a0b1d2e3f4a5b6c7d8-fa.mp3"`. One `Range: bytes=start-end` gives `206` with `Content-Range`; a bad range gives `416`.

```bash
curl -sS -o audiobook-fa.mp3 "https://faraatarjomeh.com/api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/download" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

List jobs: `GET /api/v1/audio/jobs?translationJobId=3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70&feature=audiobook&limit=20&offset=0` → `{ "jobs": [ ... ] }` (no scripts in the list; `limit` at most 50; `feature` must be `podcast` or `audiobook`). Add `q` to search by name: the name you gave the job or its original file name, ignoring case, at most 100 characters.

### The finished audio on the translation

When an audio job completes, its MP3 is also saved on the translation. A newer podcast (or audiobook) replaces the older one on the translation.

| Call | Returns |
|---|---|
| `GET /api/v1/translate/{jobId}/podcast` | The saved podcast for translation `{jobId}`, or `{ "hasPodcast": false, ... }` |
| `GET /api/v1/translate/{jobId}/audiobook` | The saved audiobook, or `{ "hasAudiobook": false, ... }` |
| `GET /api/v1/translate/download/{jobId}/{type}` | The MP3. `type` is `podcast-audio` or `audiobook-audio`. No `Range` support. |
| `DELETE /api/v1/translate/{jobId}/podcast`, `DELETE /api/v1/translate/{jobId}/audiobook` | Removes the saved audio from the translation. Cannot be undone. |
| `DELETE /api/v1/audio/jobs/{id}` | Removes the job's script and audio (see Delete below). Cannot be undone. |

```http
GET /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/audiobook HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK` (trimmed):

```json
{
  "hasAudiobook": true,
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "title": "کتاب صوتی",
  "text": "این کتاب با یک پرسش ساده آغاز می‌شود...",
  "audioFileId": "66f5cb10a9b8c7d6e5f4a3b2",
  "audioDownloadPath": "/api/v1/translate/download/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/audiobook-audio",
  "audioContentType": "audio/mpeg",
  "audioExtension": "mp3",
  "metadata": { "source": "audio_generation", "audioJobId": "66f5c9a0b1d2e3f4a5b6c7d8" },
  "faraCost": 0,
  "billing": "included_in_translation",
  "processedAt": "2026-09-25T11:21:40.000Z",
  "savedAt": "2026-09-25T11:21:40.000Z"
}
```

`metadata` has more keys; ignore them. `faraCost` here is always `0`: the charge is on the audio job (`cost` of `GET /api/v1/audio/jobs/{id}`), not on this record.

```bash
curl -sS -o audiobook.mp3 "https://faraatarjomeh.com/api/v1/translate/download/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/audiobook-audio" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

### Delete

```http
DELETE /api/v1/audio/jobs/{id} HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `204 No Content`. Removes the script and the audio of this job. A podcast or audiobook saved on the translation from this job is removed too from our servers. This cannot be undone. Ledger rows (billing history) stay. Only a finished job (`completed`, `failed` or `cancelled`) can be deleted. A job that is still running or queued, or waiting for review, answers `409` with `JOB_NOT_FINISHED`: cancel it first. After the delete the job answers `404`. Open to every account.

### Cancel

```http
POST /api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/cancel HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`: `{ "ok": true }`. The hold is released. Works in any status except `completed` and `cancelled`, and not once the last step has started (`stage` is `finalizing` or `done`) → `409`.

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8/cancel" -H "Authorization: Bearer $FARA_API_KEY"
```

There is no retry call. After `failed` (hold released), create a new job.

## State machine

| `status` | Terminal? | Meaning | Next action for the client |
|---|---|---|---|
| `pending` | no | Writing the script. | Poll. |
| `awaiting_review` | no | Script ready. Waits for you with no time limit; the hold stays reserved and blocks a second job for the same translation and `feature`. | Edit, then `approve`; or `cancel`. |
| `active` | no | Making the audio. | Poll. |
| `completed` | yes | Done and charged. | Download. |
| `failed` | yes | Stopped. Hold released. `customerErrorCode` says why. | For `SERVICE_BUSY`, `TOOK_TOO_LONG` or `GENERIC`, create a new job once. For `MEDIA_TOO_LONG` (the translation is too long to turn into audio), do not retry. |
| `cancelled` | yes | Cancelled. Hold released. | Nothing. |

Transitions: create → `pending` → `awaiting_review` → (`approve`) → `active` → `completed`. Any error → `failed`. `cancel` → `cancelled`. Treat any other status as still running.

## Billing

1. `POST /api/v1/audio/jobs` holds `holdFara` for the feature (the price of the maximum length plus 20%). `402` if the balance is too low; nothing is held on any `4xx`.
2. While in review, `estimatedCost` shows the price of the current script.
3. When the audio is made, the real cost is charged: it follows the real audio length and the script writing. If it is above the hold, the difference is charged as an extra ledger row when your balance covers it; if it does not, only the hold is charged. Anything held and not used is released (`cost.heldFara`, `cost.refundedFara`).
4. On `failed` or `cancelled` the whole hold is released.

See [Billing](https://faraatarjomeh.com/api/v1/docs/billing.md).

## Webhook events

| Event | When |
|---|---|
| `audio.awaiting_review` | The script is ready for review. |
| `audio.completed` | The MP3 is ready. |
| `audio.failed` | The job failed. GET the job for `customerErrorCode`. |
| `audio.cancelled` | The job was cancelled. |

Payload: `{ "type": "audio.awaiting_review", "timestamp": "...", "id": "evt_...", "data": { "object": "audio", "id": "66f5c9a0b1d2e3f4a5b6c7d8", "status": "awaiting_review", "createdAt": "...", "updatedAt": "...", "links": { "self": "https://faraatarjomeh.com/api/v1/audio/jobs/66f5c9a0b1d2e3f4a5b6c7d8" } } }`. `data.id` is the audio job id. See [Webhooks](https://faraatarjomeh.com/api/v1/docs/webhooks.md).

## Errors and recovery

All errors are `application/problem+json`. Branch on `code`. See [Errors](https://faraatarjomeh.com/api/v1/docs/errors.md).

| HTTP | `code` | When | Retry? | What the client should do |
|---|---|---|---|---|
| 400 | [`BAD_REQUEST`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-bad-request) | `jobId` missing, bad `feature`, voice id, `voiceGender` or `voiceMood`, or the translation is not `completed`/`completed_partial`. | no | Fix the request, or wait for the translation to finish. |
| 402 | [`INSUFFICIENT_CREDITS`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-insufficient-credits) | Balance below `holdFara`. Body has `cost` (`{ faraCharged, minutesBilled }`, the hold) and `balance`. | no | Tell the user; they top up at https://faraatarjomeh.com. After the top-up, send the same request again; the same `Idempotency-Key` is fine (4xx answers are not stored). |
| 402 | [`CHARGEBACK_LIABILITY_OUTSTANDING`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-chargeback-liability-outstanding) | A payment was reversed. | no | Tell the user to settle it on the website. |
| 403 | [`FORBIDDEN`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-forbidden) | The translation belongs to another account. | no | Use your own translation. |
| 404 | [`NOT_FOUND`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-not-found) | No such translation, audio job or segment. | no | Check the ids. |
| 409 | [`DUPLICATE_JOB`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-duplicate-job) | A job for this translation and `feature` is still running. Body has `audioJobId`. | wait | Continue with `audioJobId`. Do not create another. |
| 409 | [`CONFLICT`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-conflict) | Wrong status (edit/approve outside review, empty script, download before `completed`, cancel too late). | refresh | GET the job and decide from `status`. |
| 409 | [`HOLD_NOT_FOUND`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-hold-not-found) | On approve: the hold is gone; the job is cancelled. | no | Create a new job. |
| 409 | [`REVIEW_VERSION_CONFLICT`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-review-version-conflict) | Old `If-Match`. Body has `currentVersion`. | refresh | GET the job, re-apply the edit to the fresh script, send the new version. |
| 400 | [`INVALID_REVIEW_VERSION`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-invalid-review-version) | `If-Match` is not a whole number. | no | Send the number, bare or quoted. |
| 428 | [`REVIEW_VERSION_REQUIRED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-review-version-required) | `If-Match` missing. | yes | Add `If-Match: <reviewVersion>`. |
| 413 | [`PAYLOAD_TOO_LARGE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-payload-too-large) | Segment or whole script too long. Body has `maxChars`. | no | Shorten the text. |
| 409 | [`IDEMPOTENCY_KEY_IN_USE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-idempotency-key-in-use) | First request with this key still running. | yes | Wait `Retry-After`, resend with the same key. |
| 429 | [`RATE_LIMITED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-rate-limited) | Too many requests. | yes | Wait `Retry-After` seconds. |
| 500, 502, 504 | [`INTERNAL_ERROR`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-internal-error), [`UPSTREAM_ERROR`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upstream-error), [`UPSTREAM_TIMEOUT`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upstream-timeout) | Unknown outcome: the job may or may not exist. This answer is stored, so the same `Idempotency-Key` only replays it. | check first | List jobs with `GET /api/v1/audio/jobs?translationJobId=…&feature=…`. (A resend that finds the first job running also answers `409 DUPLICATE_JOB` with its `audioJobId`.) Only if there is none, send the request again with a NEW `Idempotency-Key`. |
| 503 | [`FEATURE_DISABLED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-feature-disabled) | Podcast and audiobook are off on this server. | later | Try again much later. |
| 503 | [`CREDIT_RESERVATION_UNAVAILABLE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-credit-reservation-unavailable) | Could not hold Fara right now. | yes | Wait `Retry-After`, resend with the same `Idempotency-Key`. |
| 503 | [`SERVICE_UNAVAILABLE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-service-unavailable) | Could not queue the job; hold released. | yes | Back off, resend with the same `Idempotency-Key`. |

## Rules for agents

- Read `holdFara` first. Do not create the job if it is above the user's budget, even if the real charge will likely be lower.
- On `409 DUPLICATE_JOB`, continue with `audioJobId`. Never cancel the other job to make room unless the user asked.
- Send a new `Idempotency-Key` on create and on approve; reuse it only when retrying the same call.
- Poll no faster than every 15 seconds. Prefer webhooks.
- The review has no timer. Approve without the user only if they said so; otherwise show the script and wait. A job left in review keeps its hold.
- Branch on `code` and `customerErrorCode`, never on `detail`. Treat unknown statuses as still running.

## Complete script

Both scripts: price → create an audiobook → wait for the script → approve it as is (only do this when the user allowed it) → wait → download. Set `FARA_API_KEY`, `FARA_BASE_URL`, `TRANSLATION_JOB_ID` and `MAX_FARA`.

```python
# Python 3.9+, pip install requests
import os, sys, time, uuid
import requests

BASE = os.environ.get("FARA_BASE_URL", "https://faraatarjomeh.com").rstrip("/")
H = {"Authorization": f"Bearer {os.environ['FARA_API_KEY']}"}
TRANSLATION = os.environ["TRANSLATION_JOB_ID"]
FEATURE = "audiobook"
MAX_FARA = 700

def check(r):
    if r.status_code >= 400:
        p = r.json() if "json" in r.headers.get("Content-Type", "") else {}
        raise SystemExit(f"{r.status_code} {p.get('code')}: {p.get('detail')}")
    return r

def get_job(job_id):
    return check(requests.get(f"{BASE}/api/v1/audio/jobs/{job_id}", headers=H, timeout=60)).json()["job"]

def wait(job_id, stop, every):
    while True:
        job = get_job(job_id)
        print(job["status"], job.get("stage"), job.get("progress"))
        if job["status"] in stop:
            return job
        time.sleep(every)

hold = check(requests.get(f"{BASE}/api/v1/audio/pricing", headers=H, timeout=30)).json()[FEATURE]["holdFara"]
if hold > MAX_FARA:
    sys.exit(f"hold {hold} Fara is above the budget")

r = requests.post(f"{BASE}/api/v1/audio/jobs", timeout=60,
                  headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                  json={"jobId": TRANSLATION, "feature": FEATURE, "voiceGender": "female"})
if r.status_code == 409 and r.json().get("code") == "DUPLICATE_JOB":
    job_id = r.json()["audioJobId"]  # continue the running job
else:
    job_id = check(r).json()["job"]["_id"]
print("audio job:", job_id)

job = wait(job_id, ("awaiting_review", "completed", "failed", "cancelled"), 15)
if job["status"] == "awaiting_review":
    print("script:", len(job["script"]), "segments, about", job["estimatedMinutes"], "min")
    check(requests.post(f"{BASE}/api/v1/audio/jobs/{job_id}/approve", timeout=60,
                        headers={**H, "If-Match": str(job["reviewVersion"]), "Idempotency-Key": str(uuid.uuid4())}))
    job = wait(job_id, ("completed", "failed", "cancelled"), 20)
if job["status"] != "completed":
    sys.exit(f"job ended as {job['status']} ({job.get('customerErrorCode')})")

with requests.get(f"{BASE}/api/v1/audio/jobs/{job_id}/download", headers=H, stream=True, timeout=600) as d:
    check(d)
    with open(f"{FEATURE}-fa.mp3", "wb") as f:
        for chunk in d.iter_content(1 << 20):
            f.write(chunk)
print("charged:", job["cost"]["faraCharged"], "of", job["cost"].get("heldFara"), "held")
```

```js
// Node.js 20+ (ESM: save as audiobook.mjs)
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";

const BASE = (process.env.FARA_BASE_URL ?? "https://faraatarjomeh.com").replace(/\/+$/, "");
const H = { Authorization: `Bearer ${process.env.FARA_API_KEY}` };
const TRANSLATION = process.env.TRANSLATION_JOB_ID;
const FEATURE = "audiobook";
const MAX_FARA = 700;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function call(path, init = {}) {
  const res = await fetch(`${BASE}${path}`, { ...init, headers: { ...H, ...init.headers } });
  if (!res.ok) {
    const p = await res.json().catch(() => ({}));
    const err = new Error(`${res.status} ${p.code}: ${p.detail}`);
    Object.assign(err, { code: p.code, body: p });
    throw err;
  }
  return res;
}
const getJob = async (id) => (await (await call(`/api/v1/audio/jobs/${id}`)).json()).job;
async function wait(id, stop, everyMs) {
  for (;;) {
    const job = await getJob(id);
    console.log(job.status, job.stage, job.progress);
    if (stop.includes(job.status)) return job;
    await sleep(everyMs);
  }
}

const pricing = await (await call("/api/v1/audio/pricing")).json();
if (pricing[FEATURE].holdFara > MAX_FARA) throw new Error(`hold ${pricing[FEATURE].holdFara} Fara is above the budget`);

let jobId;
try {
  const res = await call("/api/v1/audio/jobs", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Idempotency-Key": randomUUID() },
    body: JSON.stringify({ jobId: TRANSLATION, feature: FEATURE, voiceGender: "female" }),
  });
  jobId = (await res.json()).job._id;
} catch (e) {
  if (e.code !== "DUPLICATE_JOB") throw e;
  jobId = e.body.audioJobId; // continue the running job
}
console.log("audio job:", jobId);

let job = await wait(jobId, ["awaiting_review", "completed", "failed", "cancelled"], 15_000);
if (job.status === "awaiting_review") {
  console.log("script:", job.script.length, "segments, about", job.estimatedMinutes, "min");
  await call(`/api/v1/audio/jobs/${jobId}/approve`, {
    method: "POST",
    headers: { "If-Match": String(job.reviewVersion), "Idempotency-Key": randomUUID() },
  });
  job = await wait(jobId, ["completed", "failed", "cancelled"], 20_000);
}
if (job.status !== "completed") throw new Error(`job ended as ${job.status} (${job.customerErrorCode})`);

const mp3 = await call(`/api/v1/audio/jobs/${jobId}/download`);
await writeFile(`${FEATURE}-fa.mp3`, Buffer.from(await mp3.arrayBuffer()));
console.log("charged:", job.cost.faraCharged, "of", job.cost.heldFara, "held");
```
