# Examples

From the Lero API docs: https://lero.studio/docs/en#exemplos. Everything in one file: https://lero.studio/docs/en/llms-full.txt.

A complete client, with a timeout and waits on `429` and `503`:

JavaScript:

```javascript
import { writeFile } from "node:fs/promises";

const espera = s => new Promise(ok => setTimeout(ok, s * 1000));

// generates the speech and returns the MP3; waits Retry-After on 429 and 503
async function falar(texto, voz = "rio", tentativas = 3) {
  for (let i = 0; i < tentativas; i++) {
    const res = await fetch("https://app.lero.studio/api/v1/tts", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${process.env.LERO_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ texto, voz }),
      signal: AbortSignal.timeout(300_000),
    });
    if (res.status === 429 || res.status === 503) {
      await espera(Number(res.headers.get("Retry-After")) || 10);
      continue;
    }
    if (!res.ok) {
      const { erro, mensagem } = await res.json();
      throw new Error(`${res.status} ${erro}: ${mensagem}`);
    }
    return Buffer.from(await res.arrayBuffer());
  }
  throw new Error("the voice stayed busy");
}

await writeFile("fala.mp3", await falar("Bom dia! Seu pedido saiu pra entrega.", "sp"));
```

Python:

```python
import os
import time

import requests


def falar(texto, voz="rio", tentativas=3):
    """Generates the speech and returns the MP3; waits Retry-After on 429 and 503."""
    for _ in range(tentativas):
        r = requests.post(
            "https://app.lero.studio/api/v1/tts",
            headers={"Authorization": f"Bearer {os.environ['LERO_API_KEY']}"},
            json={"texto": texto, "voz": voz},
            timeout=300,
        )
        if r.status_code in (429, 503):
            time.sleep(int(r.headers.get("Retry-After", "10")))
            continue
        if not r.ok:
            e = r.json()
            raise RuntimeError(f"{r.status_code} {e['erro']}: {e['mensagem']}")
        return r.content
    raise RuntimeError("the voice stayed busy")


with open("fala.mp3", "wb") as f:
    f.write(falar("Oi! Aqui é o Lero, de Niterói.", voz="niteroi"))
```
