# NLP Kurdî Speech API

Kurmancî **text-to-speech** (TTS) and **speech-to-text** (STT) for partner apps.

Base URL: `https://nlpkurdi.com/v1`. Every request needs an API key. Answers are JSON unless noted.

## Authentication

Each partner app gets one API key from the NLP Kurdî team. It looks like `nlpk_live_…` (53 characters). Send it on every request:

```http
Authorization: Bearer nlpk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

`X-API-Key: nlpk_live_…` works too. Never put the key in a URL.

**About the key in a mobile app:**

- Keep the key in the build configuration, not in the source repository.
- Assume a determined person can extract it from the app package. All users of the app share the key's quota, so the API also limits each user (each network address) on its own. One user cannot use up everyone's quota.
- If the key leaks, tell us. We issue a new key for the next app release, then revoke the old one once old versions have stopped calling.

## Endpoints

| Method | Path | Service | What it does |
|---|---|---|---|
| POST | `/v1/tts` | tts | Text → speech |
| GET | `/v1/tts/voices` | tts | The voices you can choose |
| POST | `/v1/stt/transcribe` | stt | Audio file → text |
| GET | `/v1/stt/jobs/{job_id}` | stt | Status and result of a background transcription |
| GET | `/v1/stt/health` | stt | Whether speech-to-text can take work right now |
| GET | `/v1/me` | – | Your limits and today's usage |

## Text-to-speech

`POST /v1/tts` with a JSON body:

| Field | Type | Required | Meaning |
|---|---|---|---|
| `text` | string | yes | Kurmancî text, at most 1000 characters |
| `format` | `wav` / `mp3` / `opus` | no | Audio format, default `wav`. **Use `mp3` or `opus` in mobile apps**: about ten times smaller than WAV |
| `voice` | string | no | A voice id from `/v1/tts/voices`, default `female-1`. An unknown id is a `422` |
| `speed` | number | no | 0.25 – 4.0, default 1.0 |
| `include_timestamps` | boolean | no | Also return the start and end time of each word (for highlighting) |

### Raw audio (recommended for playback)

Send `Accept: audio/*` and the answer is the audio file itself (`audio/mpeg`, `audio/ogg` or `audio/wav`). It can go straight into a player or a file.

```bash
curl https://nlpkurdi.com/v1/tts \
  -H "Authorization: Bearer $NLPKURDI_KEY" \
  -H "Accept: audio/*" \
  -H "Content-Type: application/json" \
  -d '{"text": "Spas dikim.", "format": "mp3"}' -o spas.mp3
```

### JSON (when you need word timings)

Without `Accept: audio/*` the answer is JSON with the audio base64-encoded:

```bash
curl https://nlpkurdi.com/v1/tts \
  -H "Authorization: Bearer $NLPKURDI_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Ez bi kurdî dipeyivim.", "include_timestamps": true}'
```

```json
{
  "audio": "UklGRiQAAABXQVZFZm10IBAAAAABAAEA…",
  "format": "wav",
  "content_type": "audio/wav",
  "sample_rate": 24000,
  "duration": 2.421,
  "characters": 22,
  "voice": "female-1",
  "timestamps": {
    "method": "ctc_forced_alignment",
    "words": [
      { "word": "Ez", "start": 1.009, "end": 1.211, "score": 0.995 },
      { "word": "bi", "start": 1.332, "end": 1.412, "score": 1.0 },
      { "word": "kurdî", "start": 1.453, "end": 1.735, "score": 0.992 },
      { "word": "dipeyivim.", "start": 1.776, "end": 2.3, "score": 0.973 }
    ]
  }
}
```

- `duration` and `sample_rate` are only known when `include_timestamps` is on; otherwise they are `null`.
- Word times are in seconds from the start of the audio. `score` is the alignment confidence (0–1).
- Use `wav` together with timestamps: an MP3 decoder adds a few milliseconds of silence at the start, which shifts the highlighting.

Response headers: `X-Characters` (characters counted), `X-Cache` (`HIT` when the same text, voice, speed and format was synthesised recently; still counted as usage), `X-Audio-Duration` when known.

### Voices

`GET /v1/tts/voices`:

```json
{
  "default": "female-1",
  "voices": [
    { "id": "female-1", "name": "Wahdet", "gender": "female", "description": "Studio voice, the speaker with the most training data (8.3 h)" },
    { "id": "female-2", "name": "Female 2", "gender": "female", "description": "Common Voice speaker, slightly faster delivery" },
    { "id": "male-1", "name": "Male 1", "gender": "male", "description": "Common Voice speaker" }
  ]
}
```

The list changes rarely. Cache it in the app for a day.

## Speech-to-text

`POST /v1/stt/transcribe` with `multipart/form-data`:

| Field | Type | Required | Meaning |
|---|---|---|---|
| `file` | file | yes | wav, mp3, flac, ogg, m4a, webm or mp4; at most 5 MB (about 5 minutes) |
| `language` | string | no | Default `ku` |
| `timestamps` | `1` / `0` | no | Segment and word times, default `1` |
| `force_async` | `1` / `0` | no | Always answer with a background job (see below), default `0` |

```bash
curl https://nlpkurdi.com/v1/stt/transcribe \
  -H "Authorization: Bearer $NLPKURDI_KEY" \
  -F "file=@recording.m4a"
```

**Short audio: `200`** with the transcript right away:

```json
{
  "text": "ez bi kurdî dipeyivim",
  "duration_seconds": 2.42,
  "processing_time_seconds": 0.17,
  "processing_mode": "sync",
  "segments": [
    { "id": 0, "text": "ez bi kurdî dipeyivim", "start": 1.01, "end": 2.3,
      "words": [ { "word": "ez", "start": 1.01, "end": 1.21 }, { "word": "bi", "start": 1.33, "end": 1.41 } ] }
  ]
}
```

The transcript is lower-case and has no punctuation. `segments` is `null` when `timestamps=0`.

**Long audio (or `force_async=1`): `202`** with a job. Poll the `poll_url` (also in the `Location` header):

```json
{
  "job_id": "9c352f2d-8c75-4af8-a8f5-dcd2caee4dce",
  "status": "pending",
  "message": "Processing 2.4s audio asynchronously",
  "estimated_time": "0m 00s",
  "poll_url": "/v1/stt/jobs/9c352f2d-8c75-4af8-a8f5-dcd2caee4dce"
}
```

### Background jobs

`GET /v1/stt/jobs/{job_id}`. Poll every **3 seconds** until `status` is `completed` or `failed`. Treat any other status (`pending`, `processing`, …) as "not ready yet". `progress` (0–100) may be missing.

```json
{ "job_id": "9c35…", "status": "processing", "progress": 40 }
{ "job_id": "9c35…", "status": "completed", "progress": 100, "result": { "text": "…", "duration_seconds": 2.42, "processing_mode": "async", "segments": [ … ] } }
{ "job_id": "9c35…", "status": "failed", "error": "…" }
```

You only see jobs started with your own key. Results expire after a while, so fetch them as soon as they are ready. Polling does not count against the daily quota.

### Health

`GET /v1/stt/health` → `{ "status": "healthy", "model_loaded": true, "gpu": true }`. If the service is down, `status` is `"unavailable"`; the HTTP status is still `200`.

## Your usage

`GET /v1/me`:

```json
{
  "client": "Ferhengo",
  "scopes": ["tts", "stt"],
  "limits": {
    "requests_per_minute": 600, "concurrent_requests": 5,
    "daily_requests": 50000, "daily_tts_characters": 2000000, "daily_stt_minutes": 600,
    "per_device_requests_per_minute": 60, "per_device_daily_requests": null, "per_device_concurrent_requests": 2,
    "tts_max_characters": 1000, "stt_max_file_megabytes": 5
  },
  "usage_today": { "requests": 812, "tts_characters": 40213, "stt_minutes": 37.4, "stt_megabytes": 21.9 }
}
```

`null` means no limit. Days run midnight to midnight, Europe/Istanbul time.

## Limits

The whole app shares the client limits. The per-device limits apply to each network address on its own: an IPv4 address, or an IPv6 /64 network (the block a provider gives one subscriber).

| Limit | Applies to | Answer |
|---|---|---|
| Requests per minute | `/v1/tts`, `/v1/stt/transcribe` (whole app) | `429 rate_limited` |
| Status calls per minute (separate budget, twice the above, at least 120) | jobs, health, voices, `/v1/me` | `429 rate_limited` |
| Requests running at the same time | TTS + STT in progress (whole app) | waits up to 8 s for a free slot, then `429 too_many_concurrent` |
| Requests running at the same time, one device | a third of the above, at least 2 (only while per-device limits are set) | waits up to 8 s, then `429 too_many_concurrent` |
| Requests, TTS characters, STT minutes per day | whole app | `429 quota_exceeded` |
| Requests per minute and per day | each device / network address | `429 rate_limited` / `429 quota_exceeded` |

Every 429 carries `Retry-After` (seconds). For a daily quota that is the time until midnight. Answers also carry `X-RateLimit-Limit` and `X-RateLimit-Remaining` for the per-minute budget the request used.

## Errors

Every error has the same shape, and the code is repeated in the `X-Error-Code` header:

```json
{ "error": { "code": "invalid_request", "message": "The given data was invalid.", "fields": { "text": "The text field is required." } } }
```

| HTTP | `code` | Meaning | What the app should do |
|---|---|---|---|
| 400 | `invalid_request` | Body is not JSON / not multipart | Fix the request |
| 401 | `unauthorized` | Key missing, wrong, expired or revoked | Update the app / key |
| 403 | `forbidden` | Access paused, or the key has no access to this service | Show "service unavailable"; contact us |
| 403 | `blocked` | This device's network was blocked for abuse | Show the message |
| 404 | `not_found` | Unknown or expired job | Start a new transcription |
| 413 | `payload_too_large` | Text body over 16 KB, or audio over 5 MB | Send less |
| 422 | `invalid_request` | A field is invalid; see `fields` | Fix the field |
| 422 | `upstream_rejected` | The speech engine could not use the input, e.g. `"Could not decode audio file."` | Check the input |
| 429 | `rate_limited`, `too_many_concurrent`, `quota_exceeded` | A limit was hit | Wait `Retry-After` seconds |
| 502 | `upstream_error` | The speech engine failed | Retry later with backoff |
| 503 | `service_unavailable` | The speech engine is busy (it synthesises one request at a time), down or timed out. Not counted as usage | Wait `Retry-After` seconds and retry; use `force_async=1` for long audio |

Retry only on `429`, `502` and `503`: honour `Retry-After`, otherwise back off exponentially (2 s, 4 s, 8 s, at most 3 tries). Never retry other `4xx` errors.

## Calling from your own server

A website's backend can call the API for its visitors. Ask for a **server** key: it only works from the server addresses registered for it, so a leaked key is useless elsewhere.

- Send `X-End-User` with every request: an anonymous, stable id of the visitor (for example a hash of your session or user id, at most 128 visible ASCII characters). Never send names, e-mail addresses or IP addresses. The per-user limits and blocks use this id; without it, all your visitors share one per-user budget.
- Use a timeout of at least 90 seconds for `/v1/tts` and 120 seconds for `/v1/stt/transcribe`: a request may wait up to 8 seconds in line before the speech engine starts.
- On `503` or `429`, wait `Retry-After` seconds and retry once. Do not fall back to another speech service address.
- A server key may be allowed longer texts (up to 2000 characters) and a longer cache (for example fixed book pages); `GET /v1/me` shows the values.

```bash
curl https://nlpkurdi.com/v1/tts \
  -H "Authorization: Bearer $NLPKURDI_SERVER_KEY" \
  -H "X-End-User: 3f9a1c0e" \
  -H "Accept: audio/mpeg" -H "Content-Type: application/json" \
  -d '{"text": "pirtûk", "format": "mp3"}' -o pirtuk.mp3
```

## Recommendations for mobile apps

- **Cache audio on the device.** A dictionary plays the same words again and again. Store the MP3 per (text, voice, speed) and play it from the cache next time. It is faster for the user and saves your quota.
- **Expect about a second per new word**, more when many people listen at once (the engine synthesises one request at a time; requests wait in line for up to 8 seconds). Words heard before come back at once from our cache. Show a short loading state, and on `503` retry once after `Retry-After`.
- **Use `format: "mp3"` and `Accept: audio/*`** for playback. Use WAV + `include_timestamps` only when you highlight words.
- **Send a clear `User-Agent`**, e.g. `Ferhengo/2.3.0 (iOS 18.1)`. It shows up in our logs and helps us find problems with one app version.
- **Record speech at 16 kHz mono** (m4a/AAC is fine). One minute is well under 1 MB, far from the 5 MB limit.
- **Use `force_async=1` for recordings over about 30 seconds** and poll the job, so a slow mobile connection never holds a request open for minutes.

## Privacy

nlpkurdi.com does not store the text you send or the audio you upload. For each request it keeps the time, endpoint, status, size (characters / bytes), app User-Agent, a masked network address (`85.105.x.x`) and a keyed hash of it (for per-device limits and blocking) for 30 days, for limits and troubleshooting. Daily totals are kept longer. Synthesised audio is cached so repeated requests are answered without the speech engine: in server memory for a short time, and for short texts (up to 100 characters, e.g. dictionary words) on the server's disk, under a hash of the text, voice, speed and format; the text itself is not written down. The results of background transcriptions stay on the speech server for 24 hours.

## Contact

Questions, new keys, higher limits or a problem with the API: write to [osman@nlpkurdi.com](mailto:osman@nlpkurdi.com) (NLP Kurdî, Weqfa Mezopotamyayê). Please include your client name and, for a failed request, its time and `X-Error-Code`.
