# PDF translation

> Translate an English PDF into a Persian PDF and DOCX. Sequence: `POST /api/v1/translate/analyze` (free; returns `jobId` and prices) → `POST /api/v1/translate/start/{jobId}` (spends Fara; `202`) → wait for a `translation.*` webhook or poll `GET /api/v1/translate/status/{jobId}` → `GET /api/v1/translate/download/{jobId}/{type}`.

## At a glance

- Base path: `https://faraatarjomeh.com/api/v1/translate` and `https://faraatarjomeh.com/api/v1/jobs`
- Auth: `Authorization: Bearer $FARA_API_KEY`. The owner's email must be verified (`403 EMAIL_NOT_VERIFIED` otherwise).
- Scope: `read` for GET; `write` for POST and DELETE.
- Spends Fara: `POST /api/v1/translate/start/{jobId}`, `POST /api/v1/jobs/{jobId}/retry`, `POST /api/v1/jobs/{jobId}/recover` (when it queues the job again), `POST /api/v1/translate/{jobId}/resend-chunks`, `POST /api/v1/translate/upload`, `POST /api/v1/translate/magazine-translate-pdf`. Everything else on this page is free.
- Async: yes. Start answers `202` at once; the work runs in the background.
- Job id: a UUID, for example `3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70`.
- Terminal statuses: `completed`, `completed_partial`, `failed`, `cancelled`.
- Webhook events: `translation.analyzed`, `translation.images_waiting`, `translation.completed`, `translation.completed_partial`, `translation.failed`, `translation.cancelled`.
- Outputs: PDF (`application/pdf`) and DOCX (`application/vnd.openxmlformats-officedocument.wordprocessingml.document`).
- New here? Start with the [Quickstart](https://faraatarjomeh.com/api/v1/docs/quickstart.md).

## File requirements

| Rule | Value | What happens otherwise |
|---|---|---|
| Format | PDF. The file must start with `%PDF-`. | `400` |
| Content-Type of the file part | `application/pdf` (also accepted: `application/x-pdf`, `application/acrobat`, `applications/vnd.pdf`, `text/pdf`). curl needs `;type=application/pdf` after the file name. When Word and EPUB input is on for the site, `.docx` and EPUB files are accepted too (see below). | `400 BAD_REQUEST`, detail "Only PDF files are allowed" |
| Size | at most 100 MB (104,857,600 bytes) | `400 FILE_TOO_LARGE` |
| Form field name | `file` | `400 BAD_REQUEST`, detail "No PDF file provided" |
| Text | Scanned or image-only pages are read from the page images when translation starts. Their price is estimated from the page count. | analyze: `400`; stream: `error` event `EXTRACTION_EMPTY_OR_SCANNED` |
| Encryption | no password protection | `400 INVALID_PDF` |
| Page count | at most 1,000 pages | `422 TOO_MANY_PAGES` |
| Upload time | the whole request body must arrive within 15 minutes | connection closed |
| Upload rate | 300 uploads per hour per account (analyze, analyze-stream, upload, magazine, page-range) | `429 RATE_LIMITED` |

## Step 1: Analyze (get the price)

Analysis reads the PDF, counts pages and words, stores the file, and prices the translation. It is free. The result is a job with status `analyzed`. Nothing is held.

Two routes exist. For API clients use the synchronous one.

| | `POST /api/v1/translate/analyze` (recommended) | `POST /api/v1/translate/analyze-stream` + progress stream |
|---|---|---|
| Calls | 1 | 2 (upload, then open a Server-Sent Events stream) |
| When the reading starts | at once | only when you open the progress stream |
| Answer | JSON with `jobId` and prices | `complete` event with the same JSON in `analysis` |
| Waiting | one long request (set a 15-minute client timeout) | a stream with a keep-alive every 15 s; closed after 20 minutes without events |
| Good for | servers and scripts | showing live progress and queue position to a person |

### Synchronous analysis

`POST /api/v1/translate/analyze`, `multipart/form-data`:

| Field | Type | Required | Default | Allowed values | Notes |
|---|---|---|---|---|---|
| `file` | file | yes | — | PDF, ≤ 100 MB (or Word `.docx` and EPUB when the site has them on) | part `Content-Type: application/pdf` |
| `quality` | string | no | — | `simple`, `medium`, `highest` | Deprecated. Still accepted; it no longer changes the result. Wrong values: `400` "Invalid quality value". |

```http
POST /api/v1/translate/analyze HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 0f8c6a52-2d7e-4b8e-9d0a-51e3b6f2c4a1
Content-Type: multipart/form-data; boundary=----fara

------fara
Content-Disposition: form-data; name="file"; filename="book.pdf"
Content-Type: application/pdf

<PDF bytes>
------fara--
```

Response `200 OK`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "filename": "book.pdf",
  "fileSize": 4823311,
  "pageCount": 212,
  "wordCount": 68450,
  "charCount": 402113,
  "totalChunks": 46,
  "paragraphCount": 1420,
  "quality": "medium",
  "workflow": "chunk_4stage",
  "availableWorkflows": ["chunk_4stage"],
  "imageCount": 14,
  "estimatedMinutes": 32,
  "estimatedPrice": 380,
  "timeEstimate": {
    "totalMinutes": 32,
    "minutesPerChunk": 8,
    "minutesPerBatch": 8,
    "chunksPerBatch": 15,
    "estimatedBatches": 4,
    "sampleCount": 0,
    "isDefault": true,
    "source": "fallback",
    "quality": null,
    "lastUpdatedAt": null
  },
  "qualityPreviews": {
    "sourceExcerpt": {
      "text": "Leaders rarely fail for lack of vision. They fail because the vision never reaches the people who do the work.",
      "sourceChunkNumber": 23,
      "totalChunks": 46,
      "charCount": 112,
      "wordCount": 20,
      "filename": "book.pdf",
      "selectedFrom": "middle_chunk"
    },
    "variants": [
      { "quality": "simple", "status": "ok", "text": "رهبران به‌ندرت به دلیل نداشتن چشم‌انداز شکست می‌خورند...", "processingTimeMs": 18250, "isEmpty": false },
      { "quality": "medium", "status": "ok", "text": "رهبران به‌ندرت به دلیل نداشتن چشم‌انداز شکست می‌خورند...", "processingTimeMs": 19870, "isEmpty": false },
      { "quality": "highest", "status": "ok", "text": "رهبران به‌ندرت به دلیل نداشتن چشم‌انداز شکست می‌خورند...", "processingTimeMs": 18990, "isEmpty": false }
    ],
    "generatedAt": "2026-09-25T10:11:58.412Z"
  },
  "qualityEstimates": [
    { "quality": "simple", "estimatedCost": 380, "estimatedCostEconomy": 380, "estimatedMinutes": 32 },
    { "quality": "medium", "estimatedCost": 380, "estimatedCostEconomy": 380, "estimatedMinutes": 32 },
    { "quality": "highest", "estimatedCost": 380, "estimatedCostEconomy": 380, "estimatedMinutes": 32 }
  ],
  "status": "analyzed"
}
```

```bash
curl -s --max-time 900 -X POST "https://faraatarjomeh.com/api/v1/translate/analyze" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)" \
  -F "file=@book.pdf;type=application/pdf"
```

**From a link instead of an upload** (any account): send JSON with `fileUrl`, an https link to the document. We download it (up to 100 MB, at most 3 redirects, private addresses refused); the file's bytes decide its type. The same works for `POST /api/v1/translate/upload` and `POST /api/v1/translate/analyze-stream`. A bad link answers `400 INVALID_FILE_URL`; a download that fails answers `422 FILE_URL_FETCH_FAILED`.

```bash
curl -s --max-time 900 -X POST "https://faraatarjomeh.com/api/v1/translate/analyze" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Content-Type: application/json" \
  -d '{"fileUrl":"https://example.com/report.pdf"}'
```

`Idempotency-Key` is optional here (analysis is free) but useful: if the connection drops, send the same request with the same key. You get `409 IDEMPOTENCY_KEY_IN_USE` while the first request still runs, then its stored answer. For uploads the key covers only the method and path, not the file: **use a new key for every file**, or you get the answer for the earlier file.

#### Analysis fields

| Field | Type | Meaning |
|---|---|---|
| `jobId` | string (UUID) | Id for every later call. |
| `status` | string | Always `analyzed`. |
| `filename` | string | The uploaded file name. |
| `fileSize` | integer | Bytes. |
| `pageCount` | integer or null | Pages in the PDF. |
| `wordCount` | integer or null | English words found. The price is based on the text. |
| `charCount` | integer or null | Characters found. |
| `paragraphCount` | integer or null | Paragraphs found. |
| `totalChunks` | integer | Number of translation sections. Progress is counted in sections (`completedChunks` / `totalChunks`). |
| `imageCount` | integer | Images found so far. `0` does not mean the output has no figures. |
| `quality` | string | Kept for old clients. It no longer changes the translation. |
| `workflow` | string | `chunk_4stage`, the only value today. |
| `availableWorkflows` | string[] | Values you may send as `workflow` at start. Leave `workflow` out. |
| `estimatedPrice` | integer | Fara for **fast** delivery. |
| `estimatedMinutes` | integer | Estimated minutes. Every translation runs fast. |
| `timeEstimate` | object | How `estimatedMinutes` was computed. For display only. |
| `qualityEstimates` | array | One entry per quality level, all with the same price: `quality`, `estimatedCost` (Fara), `estimatedCostEconomy` (kept for old clients; the same as `estimatedCost`), `estimatedMinutes`. **Use this as the quote.** |
| `qualityPreviews` | object or null | Short sample translations of one passage, one entry per quality level. The entries have the same text now. `null` when previews are off or failed. A variant with `status: "error"` has no text. |
| `sourceLanguageNotice` | string | Only present, as `"persian"`, when the PDF text is already mostly Persian. The job still runs and can be started, but `qualityPreviews` is `null`, because no sample translation is made for it. Missing for every other file. |

#### Quality

`quality` is still accepted so old clients keep working. It no longer changes the result: the translation keeps the tone of the source text.

#### Prices

- `estimatedCost` (same as `estimatedPrice`) is the price. `estimatedCostEconomy` is kept for old clients and is the same number.
- Every translation runs fast. A start without `executionMode` runs fast too.
- `GET /api/v1/translate/status/{jobId}` also shows both prices while the job is `analyzed` (`estimatedPrice` and `estimatedPriceEconomy`, which is kept for old clients). They are computed from the word count only and can differ slightly from `qualityEstimates`. The balance check at start is computed like `qualityEstimates`.
- All prices are estimates. The final charge is the actual cost (see [Billing](#billing)).

### Streaming analysis

Use this only if you want to show progress. Steps:

1. `POST /api/v1/translate/analyze-stream` with the same form fields as above. It stores the file and answers at once:

   ```json
   {
     "analysisId": "8a41c9d2-5b7e-4f10-9c3a-6d2e8f1b7a45",
     "filename": "book.pdf",
     "fileSize": 4823311,
     "sseUrl": "/api/v1/translate/analyze-stream/8a41c9d2-5b7e-4f10-9c3a-6d2e8f1b7a45/progress"
   }
   ```

2. Open `GET /api/v1/translate/analyze-stream/{analysisId}/progress` with the same `Authorization` header, **within 30 minutes**. The reading starts only when this stream is opened. After 30 minutes the upload expires and the stream answers `404`.
3. Read `data:` lines. Each holds one JSON event. Lines that start with `:` are keep-alives (every 15 s).
4. The stream ends after a `complete` or an `error` event. On `complete`, `analysis.jobId` (equal to `analysisId`) is the job id to start.

| Event `type` | Fields | Meaning |
|---|---|---|
| `phase` | `phase`, `progress` (0–100), `message.en`, `message.fa`, `timestamp`; `position` when `phase` is `queued` | Progress. `phase` values: `queued`, `upload`, `initialize`, `extract`, `analyze`, `chunk`, `finalize`, `ready`. |
| `micro` | `progress`, `message` | Small progress step. Display only. |
| `preview` | preview data | Display only. |
| `complete` | `analysis` (same object as the synchronous answer), `timestamp` | Done. |
| `error` | `code`, `message.en`, `message.fa`, `details`, `retryable`, `timestamp` | Failed. Codes: `INVALID_PDF`, `EXTRACTION_EMPTY_OR_SCANNED`, `EXTRACTION_CAPACITY_EXCEEDED`, `EXTRACTOR_RESOURCE_EXHAUSTED`, `EXTRACTOR_RUNTIME_DEPENDENCY`, `EXTRACTION_TIMEOUT`, `SERVICE_UNAVAILABLE`, `EXTRACTION_FAILED`, `SESSION_EXPIRED`, `CONNECTION_TIMEOUT`, `CONNECTION_LOST`. Upload again only if `retryable` is `true`. |

```bash
curl -sN "https://faraatarjomeh.com/api/v1/translate/analyze-stream/$ANALYSIS_ID/progress" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

If the stream drops, the reading goes on. Open the stream again: you get the last event. If it answers `404` after the analysis finished, read the result with `GET /api/v1/translate/{id}/analysis`. To stop a running analysis, call `DELETE /api/v1/translate/analyze-stream/{analysisId}`. To continue a saved analysis without sending the PDF again, call `POST /api/v1/translate/analyze-stream/{analysisId}/resume` (free): it answers the same `analysisId` and `sseUrl` to open, or the finished `analysis` when it is already done (`409 ANALYSIS_IN_PROGRESS` while it still runs: open its stream instead).

### Read an analysis again

- `GET /api/v1/translate/{id}/analysis` returns the same object as the analysis answer, for a job that is still `analyzed`.
- `GET /api/v1/translate/resumable` lists your uploads that are analyzed but not started (`kind: "analyzed"`, with `jobId`) and analyses still running (`kind: "extracting"`, with `analysisId`, `progress`, `phase`). Use it to find a job after a dropped connection.

An analyzed job can still be started after 24 hours; `GET /api/v1/translate/{id}/analysis` keeps working. Discard jobs you will not start.

## Step 2: Start the translation

`POST /api/v1/translate/start/{jobId}`, JSON body (optional):

| Field | Type | Required | Default | Allowed values | Notes |
|---|---|---|---|---|---|
| `executionMode` | string | no | `realtime` | `realtime`, `economy_batch` | Deprecated. Every translation runs fast, and `economy_batch` runs as `realtime`. Any other non-empty value: `400 INVALID_EXECUTION_MODE`, nothing started. |
| `quality` | string | no | — | `simple`, `medium`, `highest` | Deprecated. Still accepted; it no longer changes the result. Other values: `400` "Invalid quality value". |
| `workflow` | string | no | `chunk_4stage` | values in `availableWorkflows` | Leave it out. |
| `translateImages` | boolean | no | `true` | `true`, `false` | Translates the text inside images (charts, diagrams, infographics). Each image with text adds about `imageTranslation.pricePerImage` Fara (from the analysis) to the charge. `false` keeps every image as it is, at no extra cost. |

Image translation is charged on top of the translation, from the balance that is left after the translation's own hold. The number of images with text is known only once the document has been read, so the analysis gives a price per image, not a total. If the balance does not cover every image, the job waits for your choice (`images_waiting`); see [When the balance does not cover the images](#when-the-balance-does-not-cover-the-images).

Every translation starts as soon as a worker is free and runs fast. The price is `estimatedCost`, and the time is about `estimatedMinutes`. Jobs started before economy delivery was removed may still show the `batch_*` and `validating` statuses.

Send an `Idempotency-Key` (a new UUID) and keep it. If the request fails with a network error or a timeout, send it again with the **same** key: you get the first answer back with `Idempotent-Replayed: true`, and the job is never started or charged twice.

```http
POST /api/v1/translate/start/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70 HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 7d4e1f0a-93c2-4b5e-8a61-2f0c9e7b3d58
Content-Type: application/json

{"executionMode": "realtime"}
```

Response `202 Accepted`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "quality": "medium",
  "workflow": "chunk_4stage",
  "executionMode": "realtime",
  "availableWorkflows": ["chunk_4stage"],
  "message": "Translation started",
  "totalChunks": 46,
  "status": "pending"
}
```

```bash
START_KEY=$(uuidgen)   # store it with the task; reuse it on a resend
curl -s -X POST "https://faraatarjomeh.com/api/v1/translate/start/$JOB_ID" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $START_KEY" \
  -H "Content-Type: application/json" \
  -d '{"executionMode":"realtime"}'
```

Not enough Fara — response `402 Payment Required` (nothing is held; the job stays `analyzed`):

```json
{
  "type": "https://faraatarjomeh.com/api/v1/docs/errors#error-insufficient-credits",
  "title": "Payment Required",
  "status": 402,
  "detail": "Insufficient credits",
  "instance": "/api/v1/translate/start/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "code": "INSUFFICIENT_CREDITS",
  "request_id": "b7c1e0f4-2a9d-4e61-8c3b-5f0a7d9e1c26",
  "balance": 120,
  "estimatedCost": 190
}
```

Error answers `4xx` (including this `402`) are not stored under your `Idempotency-Key`. After the user tops up, send the start again; the same key is fine.

Other start errors: `executionMode` not `economy_batch` or `realtime` → `400 INVALID_EXECUTION_MODE`; job not `analyzed` (already started, cancelled or deleted) → `400 BAD_REQUEST` ("Cannot start job with status '…'"); two starts at the same moment → `409 CONFLICT`; balance could not be checked → `503 SERVICE_UNAVAILABLE` (retry with the same key); translation switched off → `503 TRANSLATION_NOT_CONFIGURED`.

## Step 3: Wait for the result

### Webhooks (preferred)

Register an endpoint once with `POST /api/v1/webhook-endpoints` ([Webhooks](https://faraatarjomeh.com/api/v1/docs/webhooks.md)). Translation jobs send:

| Event | Sent when the job reaches |
|---|---|
| `translation.analyzed` | `analyzed` (analysis finished) |
| `translation.images_waiting` | `images_waiting` (the balance does not cover the pictures; see [When the balance does not cover the images](#when-the-balance-does-not-cover-the-images)) |
| `translation.completed` | `completed` |
| `translation.completed_partial` | `completed_partial` |
| `translation.failed` | `failed` |
| `translation.cancelled` | `cancelled` (also sent when an analyzed job is discarded) |

Example body of `translation.completed`:

```json
{
  "type": "translation.completed",
  "timestamp": "2026-09-25T21:40:14.902Z",
  "id": "evt_5b0e9c2d7a4f81e36c9d0b2a4e7f1c38",
  "data": {
    "object": "translation",
    "id": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
    "status": "completed",
    "createdAt": "2026-09-25T10:11:58.000Z",
    "updatedAt": "2026-09-25T21:40:11.000Z",
    "links": {
      "self": "https://faraatarjomeh.com/api/v1/translate/status/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70"
    }
  }
}
```

Only `translation.failed` adds `data.errorCode` (the job's `customerErrorCode`, for example `"SERVICE_BUSY"`). After an event, fetch `data.links.self` (`GET /api/v1/translate/status/{jobId}`) for the current state and the outputs. Events are delivered at least once and not always in order: drop duplicates by `id` (same as the `webhook-id` header) and trust the status you fetch.

### Poll the status

Poll `GET /api/v1/translate/status/{jobId}`. Intervals:

| Status | Poll every |
|---|---|
| `pending`, `processing`, `translating` | 30 s |
| `batch_submitted`, `batch_waiting`, `batch_results_received`, `validating` (older economy jobs) | 5 min |
| terminal | stop |

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

Response `200 OK`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "status": "completed_partial",
  "filename": "book.pdf",
  "pageCount": 212,
  "outputPageCount": 238,
  "wordCount": 68450,
  "charCount": 402113,
  "paragraphCount": 1420,
  "quality": "medium",
  "workflow": "chunk_4stage",
  "availableWorkflows": ["chunk_4stage"],
  "estimatedPrice": 190,
  "estimatedPriceEconomy": null,
  "executionMode": "realtime",
  "totalChunks": 46,
  "completedChunks": 46,
  "processingStage": null,
  "translationStep": null,
  "progress": 100,
  "createdAt": "2026-09-25T10:11:58.000Z",
  "completedAt": "2026-09-25T21:40:11.000Z",
  "error": null,
  "errorCode": null,
  "customerErrorCode": null,
  "userRetryCount": 0,
  "retryLocked": false,
  "adminReviewRequired": false,
  "reviewReasonCode": null,
  "outputs": { "docx": "66f2a1c3d4e5f60718293a4b", "pdf": "66f2a1c3d4e5f60718293a4c" },
  "hasEmptyChunks": false,
  "emptyChunkCount": 0,
  "emptyChunkNumbers": [],
  "hasFailedChunks": true,
  "failedChunkCount": 2,
  "failedChunkNumbers": [17, 31],
  "retryableChunkCount": 2,
  "retryableChunkNumbers": [17, 31],
  "failedChunksDetail": [
    { "chunkNumber": 17, "isTimeout": false, "isCircuitOpen": false, "retryable": true },
    { "chunkNumber": 31, "isTimeout": false, "isCircuitOpen": false, "retryable": true }
  ],
  "hasQualityWarnings": false,
  "qualitySummary": null,
  "qualityFlaggedChunkNumbers": [],
  "outputWarnings": [],
  "outputWarningCount": 0
}
```

```bash
curl -s "https://faraatarjomeh.com/api/v1/translate/status/$JOB_ID" -H "Authorization: Bearer $FARA_API_KEY"
```

| Field | Type | Meaning |
|---|---|---|
| `status` | string | See [State machine](#state-machine). |
| `progress` | integer 0–100 | `completedChunks` / `totalChunks`. |
| `processingStage` | string or null | `extracting`, `preparing`, `translating`, or `null`. Display only. |
| `translationStep` | integer or null | Rough progress marker while translating. Display only; use `progress` for how far the job is. |
| `executionMode` | string | `realtime` (every translation runs fast). Older jobs may show `economy_batch`. |
| `estimatedPrice` | integer | Before start: the fast price. After start: the price of the chosen mode. |
| `estimatedPriceEconomy` | integer or null | Only while `analyzed`. Kept for old clients; use `estimatedPrice`. |
| `outputs` | object or null | Set when `status` is `completed` or `completed_partial`. `outputs.pdf` / `outputs.docx` are non-null when that file exists. |
| `customerErrorCode` | string or null | Why the job failed. Set only when `status` is `failed`. See [State machine](#state-machine). |
| `userRetryCount` | integer | Retries you used (0 or 1). |
| `retryLocked` | boolean | `true`: no more retries from your side. |
| `adminReviewRequired`, `reviewReasonCode` | boolean, string or null | `true`: our team is looking at the job. |
| `hasFailedChunks`, `failedChunkCount`, `failedChunkNumbers` | | Sections that did not translate. |
| `retryableChunkCount`, `retryableChunkNumbers` | | Sections that failed for a temporary reason. |
| `hasEmptyChunks`, `emptyChunkCount`, `emptyChunkNumbers` | | Sections that came back empty. |
| `failedChunksDetail` | array | Per failed section: `chunkNumber`, `retryable`, `isTimeout`, `isCircuitOpen`; sometimes `error` (text for logs; do not parse) and `failedAt`. |
| `hasQualityWarnings`, `qualitySummary`, `qualityFlaggedChunkNumbers` | | Quality notes. Informational. |
| `error`, `errorCode`, `outputWarnings`, `outputWarningCount` | | Always `null` / empty for API keys. |
| `translationMode`, `keepLayout`, `summary`, `noSummary`, `expectedBy` | | Economy tier: the type (`economy` or `standard`), the page-design and summary ticks, and for Economy jobs the promised time in ms since 1970. Absent on jobs from before the Economy tier. |
| `canSwitchToStandard` | boolean | Economy tier: present for jobs that stored options. `true` when a failed Economy job can be switched to Standard (send `translationMode: "standard"` to the retry call). `false` while the job is locked for retry, for anyone but an admin. |
| `economyFailure` | string or null | Economy tier: why a failed Economy job failed. `incomplete` (part of the text could not be read), `extraction` (the file could not be read in full) or `unavailable` (Economy was not available). `null` for every other job, and for a job with no stored options. |
| `source` | string | Internal detail (not shown above). Ignore it. |

### `GET /api/v1/jobs/{jobId}` or `GET /api/v1/translate/status/{jobId}`?

Use `GET /api/v1/translate/status/{jobId}`. `GET /api/v1/jobs/{jobId}` was removed for API keys on 2026-09-29 (it answers `410 GONE`; the website still uses it). What the status endpoint gives that it did not:

| | `GET /api/v1/translate/status/{jobId}` | `GET /api/v1/jobs/{jobId}` |
|---|---|---|
| Prices | `estimatedPrice`, `estimatedPriceEconomy` | none |
| Failed section numbers | yes (`failedChunkNumbers`, `retryableChunkNumbers`, `failedChunksDetail`) | counts only |
| Extra fields | — | `fileId`, `updatedAt`, `economyBatchStage`, `economyBatchStatus` (display only) |
| Old jobs | reads the long-lived job record, so it answers for every job you have not deleted | reads short-lived data first; an analyzed job older than 24 hours, or a failed or cancelled job with no output after its short-lived data expired, answers `404` |
| Bad id format | `404` | `400` (must be a UUID) |
| Used by webhooks as | `data.links.self` | — |

### When the balance does not cover the images

When the balance does not cover the images, the job stops with status `images_waiting` and sends `translation.images_waiting`. The status response has `images` with the exact count and price. Call `POST /api/v1/jobs/{jobId}/images` with `choice` `all`, `part` or `none`. With no choice, the job continues without translating images after 24 hours.

## Step 4: Download

`GET /api/v1/translate/download/{jobId}/{type}`. Free, and can be repeated.

| `type` | Content-Type | Needs |
|---|---|---|
| `pdf` | `application/pdf` | status `completed` or `completed_partial`, and `outputs.pdf` not null |
| `docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | status `completed` or `completed_partial`, and `outputs.docx` not null |
| `slides-pptx`, `slides-pdf`, `podcast-audio`, `audiobook-audio` | see [Translation tools](https://faraatarjomeh.com/api/v1/docs/guides/translation-tools.md) | — |

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

Response `200 OK`: the file bytes, with `Content-Type`, `Content-Length`, and `Content-Disposition: attachment` with a suggested file name (the Persian title of the document).

```bash
curl -sf -o book-fa.pdf "https://faraatarjomeh.com/api/v1/translate/download/$JOB_ID/pdf" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

Errors: job not finished → `400` ("Job is not completed yet"); file missing → `404` (rebuild it with `POST /api/v1/translate/{jobId}/regenerate`); `type` not listed → `400`.

## State machine

```text
analyzed ──start──▶ pending ──▶ processing ──▶ (older economy jobs only) batch_submitted ▶ batch_waiting ▶ batch_results_received ▶ validating
                                     │                                                                                       │
                                     └──────────────────────────────▶ completed | completed_partial | failed ◀────────────────┘
any running status ──DELETE /api/v1/jobs/{jobId}──▶ cancelled
failed | cancelled ──POST /api/v1/jobs/{jobId}/retry──▶ pending
analyzed ──DELETE /api/v1/translate/analyze/{jobId}──▶ (discarded)
```

Running statuses can repeat or be skipped. Do not depend on their order.

| status | terminal? | meaning | next action for the client |
|---|---|---|---|
| `analyzed` | no | Priced, not started. Nothing held. | `POST /api/v1/translate/start/{jobId}`, or discard with `DELETE /api/v1/translate/analyze/{jobId}`. |
| `persisting` | no | The analysis is being saved (seconds). | Wait. |
| `pending` | no | Queued. The balance was checked; the hold is not taken yet. | Wait. Cancel is possible. |
| `processing` | no | Running. Fara is held. | Wait (poll every 30 s). Cancel is possible. |
| `translating` | no | Running. | Wait. |
| `batch_submitted` | no | Older economy job: queued for translation. | Wait (poll every 10 min). Cancel is possible. |
| `batch_waiting` | no | Older economy job: waiting for its turn. | Wait (poll every 10 min). Cancel is possible. |
| `batch_results_received` | no | Older economy job: translation received, being applied. | Wait. Cancel is possible. |
| `validating` | no | Older economy job: checking and building the files. | Wait. Cancel is possible. |
| `images_waiting` | no | The text is translated. Waiting for your choice on the pictures with text. | Choose with `POST /api/v1/jobs/{jobId}/images`, or wait. Cancel is possible. |
| `completed` | yes | Done. Actual cost charged. | Download. |
| `completed_partial` | yes | Done, but some sections stayed in English (`hasFailedChunks`). Files exist. | Download. Optional: `POST /api/v1/translate/{jobId}/resend-chunks`. |
| `failed` | yes | Stopped. Hold released. | Act on `customerErrorCode` (table below). |
| `cancelled` | yes | Cancelled by you, or an analyzed job was discarded. Hold released. | Nothing. `POST /api/v1/jobs/{jobId}/retry` restarts it. |
| any other value | no | Still running. | Wait. |

`customerErrorCode` on a `failed` job:

| `customerErrorCode` | Meaning | What the client should do |
|---|---|---|
| `NO_TEXT_LAYER` | No text could be read, even from the page images. Nothing was charged. | Do not retry the same file. Ask for a clearer scan or the original file. |
| `FILE_TOO_LARGE` | The document is too large to process. | Do not retry. Split the PDF and translate the parts. |
| `TOOK_TOO_LONG` | The job ran past its time limit. | Retry once with `POST /api/v1/jobs/{jobId}/retry`, or split the PDF. |
| `PARTIAL_SECTIONS` | Most of it worked; some sections did not. | `POST /api/v1/translate/{jobId}/resend-chunks`. |
| `INSUFFICIENT_CREDITS` | The balance dropped below the price before the hold was taken. Nothing charged. | Ask the user to top up, then `POST /api/v1/jobs/{jobId}/retry`. |
| `SERVICE_BUSY` | Our side was overloaded or a service was down. | Wait 10 minutes, then `POST /api/v1/jobs/{jobId}/retry`. |
| `RETRY_LIMIT_REACHED` | The one retry for this job is used. | Do not retry. A new analysis and start is a new, separately charged job. |
| `UNDER_REVIEW` | Our team is looking at the job. | Wait. Do not retry. |
| `GENERIC` | Anything else. | Retry once. If it fails again, contact support with the job id. |

## Billing

| When | What happens | Ledger |
|---|---|---|
| Start (`POST /api/v1/translate/start/{jobId}`) | Balance checked against the price of the chosen mode. Nothing held. `402` if too low. | — |
| The job begins running (leaves `pending`) | The estimate is held. If the balance is too low now, the job fails with `customerErrorCode: "INSUFFICIENT_CREDITS"` and nothing is charged. | `credit_hold` |
| `completed` / `completed_partial` | The actual cost is charged. It can be lower or higher than the estimate; the difference is refunded or charged. | hold → `charged`, plus `credit_refund` or `translation_charge` |
| Mostly English result | If more than half of the source words are delivered untranslated, the hold is released and nothing is charged. The files are still delivered. | `credit_refund` |
| `failed` or `cancelled` | The hold is released in full. | `credit_refund` |

The summary made with the translation is included in its price. See every row of one job with `GET /api/v1/account/transactions` and `?jobId=`. More: [Billing](https://faraatarjomeh.com/api/v1/docs/billing.md).

## Fix a finished job

A job has **one retry from your side**. `POST /api/v1/jobs/{jobId}/retry`, `POST /api/v1/translate/{jobId}/resend-chunks` and a re-queue by `POST /api/v1/jobs/{jobId}/recover` all use the same one retry. When it is used, `userRetryCount` is `1` and further tries answer `423 RETRY_LIMIT_REACHED`.

### Translate failed sections again

`POST /api/v1/translate/{jobId}/resend-chunks` re-translates only the sections that failed, then rebuilds the PDF and DOCX. Use it on `completed_partial` jobs (and `failed` jobs that have output). It spends Fara: the estimate is held first, then the actual cost of what was re-translated is charged; if nothing was re-translated, nothing is charged and the retry is not used. The call is synchronous and can take several minutes.

| Parameter | In | Type | Default | Allowed values | Notes |
|---|---|---|---|---|---|
| `type` | query | string | `all` | `all`, `failed`, `empty` | Use `all`. `empty` re-translates nothing on current jobs. |
| `retryableOnly` | query | string | `false` | `true`, `false` | `true`: only sections that failed for a temporary reason. |
| `revision` | JSON body | integer | — | `revision` from `GET /api/v1/translate/{jobId}/bilingual` | If the translation changed since, `409 STALE_REVISION`. |

```http
POST /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/resend-chunks?type=all HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: c2a9e7d1-4f3b-4a86-b0e5-9d1f7c3a2e64
```

Response `200 OK`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "type": "all",
  "retryableOnly": false,
  "totalResent": 2,
  "successCount": 2,
  "stillEmptyCount": 0,
  "failedCount": 0,
  "stillEmpty": [],
  "stillFailed": [],
  "regenerated": true,
  "regenerationError": null,
  "warnings": [],
  "results": [
    { "blockId": "b000417", "success": true },
    { "blockId": "b000752", "success": true }
  ]
}
```

```bash
curl -s --max-time 1800 -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/resend-chunks?type=all" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Idempotency-Key: $(uuidgen)"
```

If `failedCount` or `stillEmptyCount` is above 0, or `regenerated` is `false` with a `regenerationError`, the job is locked for our team: the answer adds `retryLocked: true`, `adminReviewRequired: true` and `reviewReasonCode`. Stop and wait.

Errors: job not `completed`, `completed_partial` or `failed` → `400`; no output yet → `409`; retry used → `423 RETRY_LIMIT_REACHED`; locked → `423 ADMIN_REVIEW_REQUIRED`; another fix is running → `409 DEGRADED_RETRY_IN_PROGRESS` or `409 JOB_BUSY`; very old job → `410 LEGACY_PIPELINE_REMOVED` (upload again). `POST /api/v1/translate/{jobId}/resend-empty` is an old name: it answers `307` to `resend-chunks` with `type=empty`, which does nothing now. Do not use it.

### Retry a failed or cancelled job

`POST /api/v1/jobs/{jobId}/retry` translates the whole document again, with the same settings. No body. It spends Fara like a new start: balance check now, hold when it runs, actual cost when it finishes.

```http
POST /api/v1/jobs/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/retry HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 5e8b2c4a-1d7f-4e93-a6c0-8b3f9d2e7a15
```

Response `200 OK`:

```json
{ "message": "Job queued for retry", "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70", "status": "pending" }
```

```bash
curl -s -X POST "https://faraatarjomeh.com/api/v1/jobs/$JOB_ID/retry" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Idempotency-Key: $(uuidgen)"
```

Rules: only `failed` or `cancelled` jobs (`400` otherwise). Available for 3 days after a failure and 1 day after a cancel; later it answers `404`. `423 RETRY_LIMIT_REACHED` when the retry is used, `423 ADMIN_REVIEW_REQUIRED` when locked, `409 ALREADY_QUEUED_OR_PROCESSING` or `409 RESEND_IN_PROGRESS` when something is already running, `402 INSUFFICIENT_CREDITS` when the balance is too low. Cancelling a retry after it started locks the job for our team.

### Recover a stuck job

`POST /api/v1/jobs/{jobId}/recover` looks at what is stored and does the safe thing. Use it only when a job has not changed for a long time (fast: over 2 hours; economy: over 26 hours), or when a finished job has no files. For a plain `failed` job, prefer retry.

| Field | Type | Required | Default | Notes |
|---|---|---|---|---|
| `forceRegenerate` | boolean | no | `false` | Rebuild the files even if they exist. |
| `forceRequeue` | boolean | no | `false` | Not allowed for API keys: `403 ADMIN_REVIEW_REQUIRED`. |

The body is optional. The answer also carries internal fields not shown below; ignore them. Works on `analyzed`, `pending`, `processing`, `failed` and `cancelled` jobs (`400` otherwise), for 3 days after a failure and 1 day after a cancel (`404` later). The answer has `recovery.action`:

| `recovery.action` | Meaning | Costs |
|---|---|---|
| `reattached_running_execution` | The job is still running. | nothing |
| `update_status` | The files existed; the status was fixed. | nothing |
| `regenerate_outputs` | The files were rebuilt from the stored translation. | nothing |
| `requeue_job` | The job was queued again. Uses the one retry. | like a retry |
| `no_data` | Nothing can be recovered. `recovery.suggestion` says: delete and upload again. | nothing |

```http
POST /api/v1/jobs/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/recover HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 9a3d7c1e-2b5f-4e80-9f16-4c8a0e2d7b93
Content-Type: application/json

{}
```

Response `200 OK`:

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "currentStatus": "failed",
  "hasBilingualContent": true,
  "hasChunks": true,
  "chunkCount": 46,
  "totalChunks": 46,
  "hasDocxFile": false,
  "hasPdfFile": false,
  "completedChunks": 46,
  "recovery": {
    "success": true,
    "action": "regenerate_outputs",
    "newStatus": "completed",
    "docxFileId": "66f2b0e1a3c4d5e6f7081920",
    "pdfFileId": "66f2b0e1a3c4d5e6f7081921",
    "pdfGenerated": true,
    "warnings": [],
    "message": "Outputs regenerated from bilingual content"
  }
}
```

```bash
curl -s -X POST "https://faraatarjomeh.com/api/v1/jobs/$JOB_ID/recover" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" -d '{}'
```

Only an admin can re-queue a `pending` or `processing` job: `409 ADMIN_REVIEW_REQUIRED`. `409 RUN_JUST_ENDED`: call recover again.

### Rebuild the files

`POST /api/v1/translate/{jobId}/regenerate` rebuilds the PDF and DOCX from the stored translation. Free. Synchronous. Only for `completed` and `completed_partial` jobs (`400` otherwise). Optional body `{"revision": <integer>}`; a mismatch gives `409 STALE_REVISION`.

```json
{
  "success": true,
  "docxFileId": "66f2b0e1a3c4d5e6f7081920",
  "pdfFileId": "66f2b0e1a3c4d5e6f7081921",
  "pdfGenerated": true,
  "warnings": [],
  "regeneratedAt": "2026-09-26T08:02:44.117Z"
}
```

`409 JOB_BUSY` or `409 JOB_LEASE_LOST`: another change runs on this job; wait 30 s and read the job again.

## Custom-styled PDF

`GET /api/v1/translate/pdf-styles` returns `defaults` and `options` (ranges and choices for each style field). `POST /api/v1/translate/{jobId}/custom-pdf` makes a new PDF of a `completed` or `completed_partial` job with your styles and returns it directly. It is free and not stored. The answer is a file, so do not send an `Idempotency-Key` (a repeat with the same key gets `409 IDEMPOTENCY_KEY_ALREADY_USED`).

| Body field | Type | Default | Notes |
|---|---|---|---|
| `styles` | object | `{}` | Fields below. |
| `title` | string | the document title | Shown on the cover and in the header. |
| `showHeader` | boolean | `true` | |
| `printQuality` | boolean | `false` | `true`: figures at full resolution (bigger file). Only the value `true` counts. |

| `styles` field | Accepted (else `400`) | Used range | Default when left out |
|---|---|---|---|
| `fontSize` | number 8–72 | 8–18 pt | 11 |
| `lineHeight` | number 1–3 | 1.4–2.4 | 1.6 |
| `textAlign` | `left`, `right`, `justify` | `right`, `justify` (`left` becomes `justify`) | `right` |
| `paragraphIndent` | number 0–20 | 0–20 mm | 0 |
| `headingScale` | number 0.6–1.4 | 0.6–1.4 | 0.8 |
| `coverStyle` | `quarto`, `atlas`, `plate`, `ledger` | same | `quarto` |
| `marginTop`, `marginBottom`, `marginInner`, `marginOuter` | number 0–100 | mm | 22, 18, 25, 18 |
| `headerText` | string ≤ 500 characters | | the title |
| `headerAlign` | `left`, `center`, `right` | | `left` |

```http
POST /api/v1/translate/3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70/custom-pdf HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json

{"styles": {"fontSize": 12, "lineHeight": 1.8, "textAlign": "justify", "coverStyle": "atlas"}, "title": "رهبری در عمل", "printQuality": true}
```

Response `200 OK`: the PDF bytes (`Content-Type: application/pdf`). Invalid styles → `400` with `details` (a list of the problems).

```bash
curl -sf -o custom.pdf -X POST "https://faraatarjomeh.com/api/v1/translate/$JOB_ID/custom-pdf" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Content-Type: application/json" \
  -d '{"styles":{"fontSize":12,"textAlign":"justify"},"printQuality":true}'
```

## Bilingual text

`GET /api/v1/translate/{jobId}/bilingual` returns the English and Persian text side by side, once the translation is stored (`404` before).

```json
{
  "jobId": "3f1c2b7e-9a4d-4c1e-8f7a-2b9c4d5e6f70",
  "filename": "book.pdf",
  "createdAt": "2026-09-25T21:39:50.000Z",
  "updatedAt": "2026-09-25T21:40:11.000Z",
  "revision": 0,
  "status": "completed",
  "paragraphs": [
    { "sequenceNumber": 1, "english": "Leading in Practice", "farsi": "رهبری در عمل", "farsiEdited": null, "lastEditedAt": null, "isHeading": true, "headingLevel": 1 },
    { "sequenceNumber": 2, "english": "Leaders rarely fail for lack of vision.", "farsi": "رهبران به‌ندرت به دلیل نداشتن چشم‌انداز شکست می‌خورند.", "farsiEdited": null, "lastEditedAt": null, "isHeading": false, "headingLevel": null }
  ],
  "metadata": { "price": { "totalPrice": 188 } },
  "detectedSections": [],
  "documentTitle": "رهبری در عمل"
}
```

`revision` changes when the translation changes; send it to `regenerate` and `resend-chunks` to avoid overwriting newer work. `metadata` holds document details and `price.totalPrice` (Fara); its other keys can change, so do not depend on them.

## Cancel, delete, discard

| Call | On status | Effect |
|---|---|---|
| `DELETE /api/v1/translate/analyze/{jobId}` | `analyzed` | Discards the analysis and the stored file. Status becomes `cancelled` (a `translation.cancelled` event is sent). `400` on other statuses. |
| `DELETE /api/v1/jobs/{jobId}` | `analyzed` | Same as above (`409` if the job's short-lived data expired; use the call above). |
| `DELETE /api/v1/jobs/{jobId}` | `pending`, `processing`, `images_waiting`, `batch_submitted`, `batch_waiting`, `batch_results_received`, `validating` | Cancels. The hold is released. Answer `{"message": "Job cancelled", "jobId": "…"}`. `503 CANCEL_NOT_PERSISTED`: nothing changed; send again. |
| `POST /api/v1/jobs/{jobId}/cancel` | `analyzed`, `pending`, `processing`, `images_waiting`, `batch_submitted`, `batch_waiting`, `batch_results_received`, `validating` | Cancels, like `DELETE` above, but never deletes a finished job (that answers `409`). The same verb as every other product. |
| `DELETE /api/v1/jobs/{jobId}` | `completed`, `completed_partial`, `failed`, `cancelled` | Deletes the job from your lists and downloads. Cannot be undone. Answer `{"message": "Job deleted", "jobId": "…"}`. |

```bash
curl -s -X DELETE "https://faraatarjomeh.com/api/v1/jobs/$JOB_ID" -H "Authorization: Bearer $FARA_API_KEY"
```

## Lists

- `GET /api/v1/jobs` — every translation job (any status), newest first. Query: `page` (≥ 1, default 1), `limit` (1–100, default 20). Answer: `jobs`, `total`, `page`, `totalPages`, `limit`. Finished jobs also carry which extras exist. `q` searches by name, as above (`GET /api/v1/jobs?q=…`).
- `GET /api/v1/translate/history` — every translation of the account in every state (queued, running, economy wait, priced but not started, failed, cancelled, completed); deleted ones are not listed. Analyzed uploads that were never started are listed for 7 days. Query: `page` (≥ 1, default 1), `limit` (1–100, default 20), `status` (`all`, `pending`, `processing`, `completed`, `failed`, `completed_partial`; default `all`), `sortBy` (`createdAt`, `filename`), `sortOrder` (`asc`, `desc`). Each item has `jobId`, `filename`, `status`, `executionMode`, `totalChunks`, `completedChunks`, `pageCount` (null when not known), word counts, and `hasSlides`, `hasMindmap`, `hasLinkedInPosts`, `hasPodcast`, `hasAudiobook`. Its `hasSummary` does not reflect the summary made with the translation; read `GET /api/v1/translate/{jobId}/summary` instead.

## One-call endpoints

### Upload and start at once (fast only)

`POST /api/v1/translate/upload` analyzes and starts in one call. It **always runs fast** (`realtime`) at the fast price, and you do not see the price first. Prefer analyze + start. Form fields: `file` (required), `quality` (deprecated; still accepted, and it does not change the result), `workflow`. Answer `202`:

```json
{
  "jobId": "d5a8e3f1-6b2c-4e97-8a14-0c7f9b3d2e61",
  "workflow": "chunk_4stage",
  "availableWorkflows": ["chunk_4stage"],
  "message": "Translation job started",
  "totalChunks": 46,
  "status": "pending"
}
```

The balance is checked against the fast price (`402` if too low). Use a new `Idempotency-Key` for every file: the key does not cover the file itself.

### Magazine layout (synchronous, returns a PDF)

`POST /api/v1/translate/magazine-translate-pdf` translates a PDF in place, keeping its layout, and returns the translated PDF in the same response. No job is created and nothing appears in your lists. It spends Fara: a hold is taken from the page count (350 words per page), then the charge is set from the words actually translated; on failure the hold is released.

| Form field | Type | Required | Default | Allowed values |
|---|---|---|---|---|
| `file` | file | yes | — | PDF ≤ 100 MB |
| `mode` | string | no | `phase1` | `phase1`, `phase2`; other values mean `phase1` |
| `quality` | string | no | `medium` | `simple`, `medium`, `highest`; other values mean `medium`. Deprecated: still accepted, and it no longer changes the result. |

Response `200 OK`: the PDF bytes, plus headers `X-Magazine-Mode`, `X-Magazine-Used-Ocr`, `X-Magazine-Page-Count`, `X-Magazine-Block-Count`, `X-Magazine-Blocks-Replaced`. It can take many minutes: set a client timeout of at least 30 minutes. Send an `Idempotency-Key`; because the answer is a file, a repeat with the same key answers `409 IDEMPOTENCY_KEY_ALREADY_USED` with `originalStatus` instead of the file. If `originalStatus` is `200`, the translation was made and charged once; you cannot download it again, so run it again with a new key only if the user agrees to pay again.

### Reformat a Persian PDF (no translation)

`POST /api/v1/translate/extract-farsi-book-pdf` takes a PDF that is already in Persian and returns a clean, formatted Persian PDF in the same answer. Free; no job is created. Form fields: `file` (required, PDF ≤ 100 MB), `title`, `showHeader` (`true` or `false`), `styles` (a JSON string of style options from `GET /api/v1/translate/pdf-styles`).

## Translate part of a file

Translating part of a file is ONE site-wide switch: it is either on for everyone or off for everyone, not per account. When it is on, you can translate some pages of a file instead of all of it.

- **After an upload:** `POST /api/v1/translate/upload` takes `pageFrom` and `pageTo` (1-based, both included) with the PDF. The file is cut to those pages before analysis, and the job is a part of the file. Both fields must be whole numbers. Without them the whole file is translated.
- **Resuming an upload:** send the same `operationId` again with the same `pageFrom` and `pageTo` as the first request. A different range (or none) is refused with 409 `DOCUMENT_OPERATION_SOURCE_MISMATCH`.
- **From an analyzed or finished job:** `POST /api/v1/translate/{jobId}/page-range` takes `pageFrom` and `pageTo`, or `chapters` (indexes from the job's `pageRangeOffer.chapters`, which the analysis gives when the PDF has an outline). The answer is the same as the streaming analysis (`analysisId`, `sseUrl`). The part is priced by its own analysis; the parent job is not charged.

When the switch is off, the page-range route answers 404 `FEATURE_DISABLED` and `pageFrom` / `pageTo` on upload are ignored.

## Errors and recovery

Every error is `application/problem+json`. Branch on `code`. Each code has an entry in the [error catalog](https://faraatarjomeh.com/api/v1/docs/errors.md); the problem's `type` links to it, for example [insufficient credits](https://faraatarjomeh.com/api/v1/docs/errors.md#error-insufficient-credits).

What is stored under your `Idempotency-Key`: success answers (`2xx`, `3xx`) and `500`, `502`, `504`. Not stored: every `4xx` and `503` — fix the cause (or top up, or wait) and resend with the **same** key. After a `500`, `502` or `504` the outcome is unknown and the same key replays that error: check whether the work happened (read the job), then resend with a **new** key.

| HTTP | code | when | retry? | what the client should do |
|---|---|---|---|---|
| 400 | `BAD_REQUEST` | not a PDF, over 100 MB, no text, invalid `quality`, wrong job status for the call | no | Fix the input or read the job status first. |
| 400 | `INVALID_PDF` | broken, encrypted or password-protected PDF | no | Ask the user for another file. |
| 400 | `INVALID_PAGE_RANGE` | page range is not whole numbers, is backwards, or covers the whole file | no | Send a smaller range, or translate the whole file. |
| 400 | `PAGE_RANGE_OUT_OF_BOUNDS` | a page is outside the file | no | Use pages from 1 to the page count. |
| 400 | `PAGE_RANGE_NOT_CONTIGUOUS` | chapters picked are not next to each other | no | Pick chapters in one run. |
| 409 | `PAGE_RANGE_PARENT_IS_PART` | the job is already a part of a file | no | Start from the whole file. |
| 409 | `PAGE_RANGE_BUSY` | the same range is still being prepared by another request | yes | Retry the same call after a few seconds. |
| 409 | `JOB_NOT_READY` | the job is not analysed yet | yes | Wait until its status is `analyzed`, then retry. |
| 410 | `PAGE_RANGE_SOURCE_GONE` | the original file is no longer stored | no | Upload the file again. |
| 422 | `PAGE_RANGE_EMPTY` | no readable text on the pages in the range | no | Try another range. |
| 422 | `PAGE_RANGE_UNAVAILABLE` | the pages could not be cut from the file | no | Try again later or upload the file again. The whole file is not used instead. |
| 422 | `TOO_MANY_PAGES` | the PDF has more than 1,000 pages | no | Ask the user to split the book into parts of up to 1,000 pages. |
| 400 | `INVALID_EXECUTION_MODE` | start with an `executionMode` other than `economy_batch` / `realtime` | no | Send one of the two values (same key is fine). |
| 400 | `EXTRACTION_EMPTY_OR_SCANNED` | (stream) no readable text | no | Ask for a clearer scan or the original file. |
| 401 | `INVALID_API_KEY`, `API_KEY_EXPIRED` | key problem | no | Get a valid key from the owner. |
| 402 | `INSUFFICIENT_CREDITS` | balance below the price; body has `balance`, `estimatedCost` | no | Stop. Tell the user to top up at https://faraatarjomeh.com. Then resend (the same key is fine). |
| 402 | `CHARGEBACK_LIABILITY_OUTSTANDING` | reversed payment not settled | no | Tell the user to contact support. |
| 403 | `EMAIL_NOT_VERIFIED` | owner's email not verified | no | The owner verifies it on the website. |
| 403 | `INSUFFICIENT_SCOPE` | key lacks `read`/`write` | no | Use a key with `requiredScope`. |
| 403 | `FORBIDDEN` | job belongs to another account | no | Check the job id. |
| 404 | `NOT_FOUND` | unknown, deleted or expired job; no file | no | Check the id; for a missing file, `regenerate`. |
| 409 | `IDEMPOTENCY_KEY_IN_USE` | first request with this key still runs | yes | Wait `Retry-After` (2 s), resend with the same key. |
| 409 | `IDEMPOTENCY_KEY_ALREADY_USED` | first answer was a file | no | Check `originalStatus`. Use a new key only to do the work again. |
| 409 | `ALREADY_QUEUED_OR_PROCESSING`, `RESEND_IN_PROGRESS`, `DEGRADED_RETRY_IN_PROGRESS` | work already runs on this job | no | Poll the job. |
| 409 | `STALE_REVISION`, `JOB_LEASE_LOST`, `DEGRADED_RETRY_CONFLICT`, `RUN_JUST_ENDED` | the job changed | yes | Read the job (and `revision`) again, rebuild the request, send once more. |
| 409 | `JOB_BUSY` | another change runs | yes | Wait 30 s, resend (same key is fine). |
| 409 | `CONFLICT` | two starts at once | no | Poll the job; it is starting. |
| 410 | `LEGACY_PIPELINE_REMOVED` | very old job | no | Upload the file again. |
| 422 | `IDEMPOTENCY_KEY_REUSED` | same key, different request | no | Use a new key per action. |
| 423 | `RETRY_LIMIT_REACHED` | the one retry is used | no | Tell the user; a new job is a new charge. |
| 423 | `ADMIN_REVIEW_REQUIRED` | our team is looking at the job | no | Wait; poll every 30 min. |
| 429 | `RATE_LIMITED` | 120 requests per 60 s per key, or 300 uploads per hour | yes | Wait `Retry-After`, resend with the same key. |
| 500 | `INTERNAL_ERROR` | server error; stored under the key | once | Read the job; if nothing happened, resend with a **new** key after 30 s. |
| 503 | `EXTRACTION_CAPACITY_EXCEEDED` | too many documents being read | yes | Wait `Retry-After` (30–60 s), resend with the same key. |
| 503 | `EXTRACTOR_RESOURCE_EXHAUSTED`, `EXTRACTOR_RUNTIME_DEPENDENCY`, `SERVICE_UNAVAILABLE`, `CANCEL_NOT_PERSISTED`, `RETRY_STATE_PERSIST_FAILED` | temporary | yes | Back off (30 s, 1 min, 2 min … 10 min), same key. Give up after 30 minutes. |
| 503 | `TRANSLATION_NOT_CONFIGURED` | translation switched off | yes | Retry after 10 minutes. |
| 504 | `EXTRACTION_TIMEOUT` | reading the PDF took too long; stored under the key | once | Check `GET /api/v1/translate/resumable` for the job; if it is not there, resend with a **new** key after 5 minutes. If it fails again, ask for a smaller file. |

## Rules for agents

- Analyze first. Quote the price from `qualityEstimates` (`estimatedCost`). Do not start if the price is above what the user approved or above `credits.balance` from `GET /api/v1/account`.
- Every translation runs fast. Send `executionMode` as `realtime`, or leave it out (anything else is `400 INVALID_EXECUTION_MODE`).
- Send an `Idempotency-Key` on every POST that spends Fara. Store it with the task and reuse it on every resend of that POST. Use a new key for each new file or action.
- Prefer webhooks. If polling, poll `GET /api/v1/translate/status/{jobId}` no faster than every 30 s, and every 10 min in the older economy waiting statuses.
- Treat unknown statuses as running. Stop only at `completed`, `completed_partial`, `failed`, `cancelled`.
- Never start a second job for a document whose job is still running.
- Use the one retry only when `customerErrorCode` says a retry can help (table in [State machine](#state-machine)).
- Never parse `detail`; branch on `code` and `customerErrorCode`.
- Do not call `DELETE` on a finished job unless the user asked; it cannot be undone.

## Complete script

Both scripts: analyze, check the budget and balance, start, wait, download PDF and DOCX, and re-translate failed sections once on `completed_partial` if the user allows it. Network errors, `409 IDEMPOTENCY_KEY_IN_USE`, `429` and `503` are retried with the same `Idempotency-Key`.

Python 3.9+ (`pip install requests`). Run: `python pdf_translate.py book.pdf --max-fara 500 --fix-partial`

```python
# pdf_translate.py
import argparse
import os
import sys
import time
import uuid

import requests

BASE_URL = "https://faraatarjomeh.com"
API_KEY = os.environ["FARA_API_KEY"]
TERMINAL = {"completed", "completed_partial", "failed", "cancelled"}


class ApiError(Exception):
    def __init__(self, status, problem):
        super().__init__(f"{status} {problem.get('code')}: {problem.get('detail')}")
        self.status = status
        self.problem = problem


def api(method, path, key=None, json_body=None, files=None, stream=False, read_timeout=900):
    headers = {"Authorization": f"Bearer {API_KEY}"}
    if key:
        headers["Idempotency-Key"] = key
    for attempt in range(1, 61):
        for part in (files or {}).values():
            part[1].seek(0)
        try:
            res = requests.request(method, BASE_URL + path, headers=headers, json=json_body,
                                   files=files, stream=stream, timeout=(10, read_timeout))
        except requests.RequestException:
            time.sleep(min(2 ** attempt, 60))
            continue
        if res.ok:
            return res if stream else res.json()
        try:
            problem = res.json()
        except ValueError:
            problem = {}
        if res.status_code in (429, 503) or problem.get("code") == "IDEMPOTENCY_KEY_IN_USE":
            time.sleep(max(int(res.headers.get("Retry-After") or 0), 10))
            continue
        raise ApiError(res.status_code, problem)
    raise RuntimeError(f"{method} {path}: gave up after retries")


def wait_for(job_id):
    while True:
        job = api("GET", f"/api/v1/translate/status/{job_id}")
        print(f"  {job['status']} {job['progress']}%")
        if job["status"] in TERMINAL:
            return job
        time.sleep(30)


def download(job_id, job):
    for file_type, value in (job.get("outputs") or {}).items():
        if not value:
            continue
        res = api("GET", f"/api/v1/translate/download/{job_id}/{file_type}", stream=True)
        with open(f"{job_id}.{file_type}", "wb") as out:
            for block in res.iter_content(chunk_size=1 << 16):
                out.write(block)
        print(f"Saved {job_id}.{file_type}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("pdf")
    parser.add_argument("--max-fara", type=float, default=float("inf"))
    parser.add_argument("--fix-partial", action="store_true")
    args = parser.parse_args()

    balance = api("GET", "/api/v1/account")["credits"]["balance"]
    with open(args.pdf, "rb") as fh:
        files = {"file": (os.path.basename(args.pdf), fh, "application/pdf")}
        analysis = api("POST", "/api/v1/translate/analyze", key=str(uuid.uuid4()), files=files)
    job_id = analysis["jobId"]
    price = analysis["estimatedPrice"]
    print(f"{job_id}: {analysis['pageCount']} pages, price {price} Fara, balance {balance} Fara")
    if price > args.max_fara or price > balance:
        api("DELETE", f"/api/v1/translate/analyze/{job_id}")
        sys.exit("Not started: over budget or balance")

    try:
        api("POST", f"/api/v1/translate/start/{job_id}", key=str(uuid.uuid4()),
            json_body={"executionMode": "realtime"})
    except ApiError as err:
        if err.problem.get("code") == "INSUFFICIENT_CREDITS":
            sys.exit(f"Top up at {BASE_URL}: balance {err.problem.get('balance')}, "
                     f"needed {err.problem.get('estimatedCost')}")
        raise

    job = wait_for(job_id)
    if job["status"] == "completed_partial" and args.fix_partial and job["userRetryCount"] == 0:
        result = api("POST", f"/api/v1/translate/{job_id}/resend-chunks?type=all",
                     key=str(uuid.uuid4()), read_timeout=1800)
        print(f"Re-translated {result['successCount']} of {result['totalResent']} sections")
        job = api("GET", f"/api/v1/translate/status/{job_id}")

    if job["status"] in ("completed", "completed_partial"):
        download(job_id, job)
    else:
        sys.exit(f"Job ended as {job['status']} ({job.get('customerErrorCode')})")


if __name__ == "__main__":
    main()
```

Node.js 20+ (no packages). Run: `node pdf-translate.mjs book.pdf 500`

```js
// pdf-translate.mjs
import { openAsBlob } from "node:fs";
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { basename } from "node:path";
import { setTimeout as sleep } from "node:timers/promises";

const BASE_URL = "https://faraatarjomeh.com";
const API_KEY = process.env.FARA_API_KEY;
if (!API_KEY) throw new Error("Set FARA_API_KEY");

const [pdfPath, maxFaraArg, fixPartialArg] = process.argv.slice(2);
if (!pdfPath) throw new Error("Usage: node pdf-translate.mjs book.pdf [maxFara] [fix-partial]");
const maxFara = maxFaraArg ? Number(maxFaraArg) : Infinity;
const fixPartial = fixPartialArg === "fix-partial";
const TERMINAL = new Set(["completed", "completed_partial", "failed", "cancelled"]);

class ApiError extends Error {
  constructor(status, problem) {
    super(`${status} ${problem.code}: ${problem.detail}`);
    this.status = status;
    this.problem = problem;
  }
}

async function api(method, path, { json, form, key, raw = false } = {}) {
  const headers = { Authorization: `Bearer ${API_KEY}` };
  if (key) headers["Idempotency-Key"] = key;
  let body = form;
  if (json !== undefined) {
    headers["Content-Type"] = "application/json";
    body = JSON.stringify(json);
  }
  for (let attempt = 1; attempt <= 60; attempt++) {
    let res;
    try {
      res = await fetch(BASE_URL + path, { method, headers, body });
    } catch {
      await sleep(Math.min(2 ** attempt, 60) * 1000); // network error or timeout: same key
      continue;
    }
    if (res.ok) return raw ? res : res.json();
    const problem = await res.json().catch(() => ({}));
    if (res.status === 429 || res.status === 503 || problem.code === "IDEMPOTENCY_KEY_IN_USE") {
      await sleep(Math.max(Number(res.headers.get("retry-after")) || 0, 10) * 1000);
      continue;
    }
    throw new ApiError(res.status, problem);
  }
  throw new Error(`${method} ${path}: gave up after retries`);
}

async function waitFor(jobId) {
  for (;;) {
    const job = await api("GET", `/api/v1/translate/status/${jobId}`);
    console.log(`  ${job.status} ${job.progress}%`);
    if (TERMINAL.has(job.status)) return job;
    await sleep(30 * 1000);
  }
}

const { credits } = await api("GET", "/api/v1/account");
const form = new FormData();
form.append("file", await openAsBlob(pdfPath, { type: "application/pdf" }), basename(pdfPath));
const analysis = await api("POST", "/api/v1/translate/analyze", { form, key: randomUUID() });
const jobId = analysis.jobId;
const price = analysis.estimatedPrice;
console.log(`${jobId}: ${analysis.pageCount} pages, price ${price} Fara, balance ${credits.balance} Fara`);
if (price > maxFara || price > credits.balance) {
  await api("DELETE", `/api/v1/translate/analyze/${jobId}`);
  throw new Error("Not started: over budget or balance");
}

try {
  await api("POST", `/api/v1/translate/start/${jobId}`, { json: { executionMode: "realtime" }, key: randomUUID() });
} catch (err) {
  if (err instanceof ApiError && err.problem.code === "INSUFFICIENT_CREDITS") {
    throw new Error(`Top up at ${BASE_URL}: balance ${err.problem.balance}, needed ${err.problem.estimatedCost}`);
  }
  throw err;
}

let job = await waitFor(jobId);
if (job.status === "completed_partial" && fixPartial && job.userRetryCount === 0) {
  const result = await api("POST", `/api/v1/translate/${jobId}/resend-chunks?type=all`, { key: randomUUID() });
  console.log(`Re-translated ${result.successCount} of ${result.totalResent} sections`);
  job = await api("GET", `/api/v1/translate/status/${jobId}`);
}

if (job.status !== "completed" && job.status !== "completed_partial") {
  throw new Error(`Job ended as ${job.status} (${job.customerErrorCode})`);
}
for (const [type, value] of Object.entries(job.outputs ?? {})) {
  if (!value) continue;
  const res = await api("GET", `/api/v1/translate/download/${jobId}/${type}`, { raw: true });
  await writeFile(`${jobId}.${type}`, Buffer.from(await res.arrayBuffer()));
  console.log(`Saved ${jobId}.${type}`);
}
```
