# Article to Speech (callback API)

> POST https://api.moknah.io/process-text turns an article into an MP3 narration and an SRT file, delivered to your callback URL. Fields, callback payload, signature, idempotency, billing and errors.

## Endpoint

`POST https://api.moknah.io/process-text`

Accepts the text of an article and produces an MP3 narration with a synchronized subtitle file (`.srt`). The work is asynchronous: the request is answered at once with `202`, and the finished files are sent to the `callbackURL` you provide. This is the service behind the Moknah WordPress plugin.

Do not wait on the HTTP response for the audio. It arrives at your callback URL.

## Authentication

`Authorization: Bearer YOUR_COMPANY_API_KEY`

This endpoint uses the **company API key** of an account with the Article to Speech service, not a dashboard API key from **API**, **Manage API Keys**. The company key has a voice type (Standard or Advanced), chosen when it is generated.

## Request body

JSON.

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `text` | string | yes | The full article text. Must not be blank. Billed on its length, so it is not trimmed. |
| `postData` | object | yes | Request metadata, below. |

### postData

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | string | yes | | Title of the article. `null` is accepted. |
| `articleId` | string | yes | | Your identifier for the article, up to 255 characters. It is the idempotency key and is returned in the callback. |
| `voiceId` | string | yes | | A voice id from [List voices](voices.md), of the same voice type as the company key. |
| `callbackURL` | string | yes | | `http` or `https` URL, up to 500 characters, that receives the result. The latest value is stored for the company. |
| `preprocessType` | string or number | no | `0` | `0` narrates the text as it is. `2` applies Arabic Tashkeel (diacritics, numbers spelled out) and costs more per character. `2` is for Arabic only. |
| `language` | string | no | `auto` | `auto` or an ISO 639-1 code such as `ar` or `en`. With `auto`, `preprocessType` `2` is applied only when the text is Arabic; otherwise the article is narrated as `0` and charged as `0`. |
| `regenerate` | boolean | no | `false` | `true` forces a new generation for an `articleId` that was generated before. |

`preprocessType` `2` with a language other than Arabic is rejected with `422 VALIDATION_ERROR`.

## Example request

```bash
curl -X POST "https://api.moknah.io/process-text" \
  -H "Authorization: Bearer YOUR_COMPANY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "الذكاء الاصطناعي يتطور بسرعة كبيرة في كل المجالات.",
    "postData": {
      "name": "AI is evolving fast",
      "articleId": "post-123",
      "voiceId": "12",
      "callbackURL": "https://your-site.com/wp-json/ats/v1/callback",
      "preprocessType": "0",
      "language": "auto",
      "regenerate": false
    }
  }'
```

```python
import requests

response = requests.post(
    "https://api.moknah.io/process-text",
    headers={"Authorization": "Bearer YOUR_COMPANY_API_KEY"},
    json={
        "text": "الذكاء الاصطناعي يتطور بسرعة كبيرة في كل المجالات.",
        "postData": {
            "name": "AI is evolving fast",
            "articleId": "post-123",
            "voiceId": "12",
            "callbackURL": "https://your-site.com/wp-json/ats/v1/callback",
        },
    },
)
print(response.status_code, response.text)  # 202 and a plain text message
```

## Immediate response

`202 Accepted` with the plain text body:

```text
Processing started. Results will be sent to the callback URL.
```

The `202` body is text, not JSON. Error responses are JSON, except `429`, which is plain text.

## Callback payload

When generation finishes, Moknah sends a `POST` to your `callbackURL`:

```json
{
  "articleId": "post-123",
  "response": {
    "audioFile": "https://api-storage.moknah.io/example/post-123.mp3",
    "srtFile": "https://api-storage.moknah.io/example/post-123.srt",
    "signature": "9f2c0c1e5b7a4d3e8f6a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60"
  }
}
```

| Field | Description |
| --- | --- |
| `articleId` | The `articleId` you sent. |
| `response.audioFile` | Public URL of the MP3, or `null` when generation failed. |
| `response.srtFile` | Public URL of the SRT file, or `null` when generation failed. |
| `response.signature` | HMAC-SHA256 signature of the payload, below. |

A callback is also sent when generation produces no audio. Treat any callback whose `audioFile` or `srtFile` is `null` as a failure: do not mark the article as done, and send it again with `regenerate` set to `true`.

### Verifying the signature

The signature is the HMAC-SHA256, as hex, of the string `articleId|audioFile|srtFile`, keyed with the SHA-256 hex digest of your API key. For a failed generation the string is `articleId|null|null`.

```python
import hashlib
import hmac

key_hash = hashlib.sha256(API_KEY.encode()).hexdigest()
payload = f"{article_id}|{audio_file}|{srt_file}"
expected = hmac.new(key_hash.encode(), payload.encode(), hashlib.sha256).hexdigest()
is_valid = hmac.compare_digest(expected, signature)
```

```javascript
import crypto from "crypto";

const keyHash = crypto.createHash("sha256").update(API_KEY).digest("hex");
const payload = `${articleId}|${audioFile}|${srtFile}`;
const expected = crypto.createHmac("sha256", keyHash).update(payload).digest("hex");
const isValid = crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
```

## Idempotency and regeneration

- Requests are keyed by `articleId` per company. A new `articleId` starts a new generation.
- While an article is being generated, repeated requests for it return `409 ALREADY_PROCESSING`.
- If an article was already generated and `regenerate` is `false`, the existing files are delivered to the callback again, with no new generation and no charge.
- `regenerate` `true` forces a new generation for an existing `articleId`.
- If an earlier attempt failed, sending the same `articleId` again generates it again. No new id is needed.

## Throughput

Articles are generated from a queue in which every client gets a fair share. You can submit many articles at once: all are accepted, a few are generated at a time, and each is delivered as soon as it is ready. A large batch therefore completes gradually.

The endpoint is rate limited per client IP address; requests above the limit get `429`. Current values are in [Limits](../limits/index.md).

## Billing

Credits = characters of `text` multiplied by the rate of the preprocessing type (`2` costs more than `0`), with the Advanced engine multiplier for Advanced voices. Current rates are in [Pricing](../pricing/index.md).

- Credits are taken only when a generation actually runs.
- Delivering an already generated article again is free.
- If generation or delivery fails, the credits are refunded automatically.

## Errors

Error bodies are JSON of the form `{"code": "...", "error": "..."}`.

| Status | Code | When |
| --- | --- | --- |
| 400 | `INVALID_VOICE_ID` | `voiceId` does not exist. |
| 400 | `UNSUPPORTED_VOICE` | The voice is not of the key's voice type, or is not available right now. |
| 401 | `AUTH_FAILED` | Missing `Authorization` header, invalid key, or a key without the Article to Speech service. |
| 409 | `ALREADY_PROCESSING` | This article is being generated. Retry after it completes. |
| 422 | `VALIDATION_ERROR` | Missing or blank `text`, missing or invalid `postData` fields, or text too short to narrate. |
| 422 | `CONTENT_REJECTED` | The text was refused by the content policy check. |
| 422 | `PROCESSING_ERROR` | Generation could not start or failed. Credits taken are refunded. |
| 422 | `REFUND_FAILED` | Processing failed and the automatic refund did not complete. Contact api@moknah.io. |
| 429 | (plain text) | Too many requests from this IP address. |
