uxoxo/eb2ab
0
1# ebook2audiobook TTS REST API Documentation2 3## Overview4 5The ebook2audiobook TTS REST API provides programmatic access to the text-to-speech conversion capabilities. This API allows you to submit text for conversion, monitor job progress, and download generated audio files.6 7**Base URL**: `https://your-space.hf.space/api/v1`8 9**Authentication**: All endpoints (except `/health`) require an API key via the `X-API-Key` header.10 11**Rate Limiting**: 100 requests per hour per API key (configurable).12 13**File Retention**: Generated audio files are automatically deleted after 24 hours (configurable).14 15---16 17## Authentication18 19All API requests must include an API key in the header:20 21```http22X-API-Key: your-api-key-here23```24 25### Obtaining an API Key26 27API keys are configured by the server administrator through environment variables. Contact your administrator for an API key.28 29---30 31## Endpoints32 33### 1. Submit TTS Conversion34 35Convert text to speech asynchronously.36 37**Endpoint**: `POST /api/v1/tts/convert`38 39**Headers**:40```http41Content-Type: application/json42X-API-Key: your-api-key-here43```44 45**Request Body**:46```json47{48 "text": "Hello world! This is a test of the text-to-speech API.",49 "language": "eng",50 "voice": "Morgan Freeman",51 "engine": "XTTSv2",52 "output_format": "m4b",53 "speed": 1.0,54 "temperature": 0.7555}56```57 58**Parameters**:59- `text` (string, required): Text to convert to speech (max 50KB)60- `language` (string, optional): Language code, default "eng"61 - Available: eng, fra, spa, deu, jpn, ara, rus, kor, zho, and more62- `voice` (string, optional): Voice name for cloning or null for default63 - Use `/api/v1/tts/voices` to list available voices64- `engine` (string, optional): TTS engine, default "XTTSv2"65 - Options: "XTTSv2", "Bark", "VITS"66- `output_format` (string, optional): Audio format, default "m4b"67 - Options: "m4b", "mp3", "wav", "m4a", "aac", "flac", "ogg"68- `speed` (float, optional): Speech speed (0.5-2.0), XTTSv2 only69- `temperature` (float, optional): Generation temperature (0.1-1.0), XTTSv2 only70 71**Response** (202 Accepted):72```json73{74 "job_id": "550e8400-e29b-41d4-a716-446655440000",75 "status": "queued",76 "created_at": "2025-10-17T12:00:00Z"77}78```79 80**Response Headers**:81```http82X-RateLimit-Limit: 10083X-RateLimit-Remaining: 9584X-RateLimit-Reset: 169754760085```86 87**Error Responses**:88- `400 Bad Request`: Invalid request parameters89- `401 Unauthorized`: Missing or invalid API key90- `422 Unprocessable Entity`: Validation error91- `429 Too Many Requests`: Rate limit exceeded92- `503 Service Unavailable`: Job queue is full93 94---95 96### 2. Check Job Status97 98Check the status of a TTS conversion job.99 100**Endpoint**: `GET /api/v1/tts/status/{job_id}`101 102**Headers**:103```http104X-API-Key: your-api-key-here105```106 107**Response** (200 OK):108```json109{110 "job_id": "550e8400-e29b-41d4-a716-446655440000",111 "status": "completed",112 "progress": 100,113 "error": null,114 "audio_url": "/api/v1/audio/550e8400-e29b-41d4-a716-446655440000",115 "created_at": "2025-10-17T12:00:00Z",116 "expires_at": "2025-10-18T12:00:00Z"117}118```119 120**Status Values**:121- `queued`: Job is waiting in the queue122- `processing`: TTS conversion in progress123- `completed`: Audio file is ready for download124- `failed`: Conversion failed (check `error` field)125 126**Error Responses**:127- `401 Unauthorized`: Missing or invalid API key128- `404 Not Found`: Job not found129 130---131 132### 3. Download Audio File133 134Download the generated audio file for a completed job.135 136**Endpoint**: `GET /api/v1/audio/{job_id}`137 138**Headers**:139```http140X-API-Key: your-api-key-here141```142 143**Response** (200 OK):144- Content-Type: `audio/{format}`145- Content-Disposition: `attachment; filename="tts_output.{format}"`146- Body: Audio file binary data147 148**Error Responses**:149- `401 Unauthorized`: Missing or invalid API key150- `404 Not Found`: Job not found or not completed151- `410 Gone`: Audio file has expired and been deleted152 153---154 155### 4. Delete Audio File (Optional)156 157Manually delete audio file and job data before expiration.158 159**Endpoint**: `DELETE /api/v1/audio/{job_id}`160 161**Headers**:162```http163X-API-Key: your-api-key-here164```165 166**Response** (200 OK):167```json168{169 "message": "Job 550e8400-e29b-41d4-a716-446655440000 deleted successfully"170}171```172 173**Error Responses**:174- `401 Unauthorized`: Missing or invalid API key175- `404 Not Found`: Job not found176- `500 Internal Server Error`: Failed to delete files177 178---179 180### 5. List Available Voices181 182Get a list of available voice cloning options.183 184**Endpoint**: `GET /api/v1/tts/voices`185 186**Headers**:187```http188X-API-Key: your-api-key-here189```190 191**Response** (200 OK):192```json193{194 "voices": [195 {196 "name": "Morgan Freeman",197 "path": "eng/adult/male/morgan_freeman.wav",198 "language": "eng"199 },200 {201 "name": "David Attenborough",202 "path": "eng/elder/male/david_attenborough.wav",203 "language": "eng"204 }205 ],206 "total": 245207}208```209 210---211 212### 6. Health Check213 214Check API service health (no authentication required).215 216**Endpoint**: `GET /api/v1/health`217 218**Response** (200 OK):219```json220{221 "status": "healthy",222 "version": "4.1.0",223 "gradio_running": true,224 "api_running": true225}226```227 228**Detailed Health Check**:229 230**Endpoint**: `GET /api/v1/health/detailed`231 232**Response** (200 OK):233```json234{235 "status": "healthy",236 "version": "4.1.0",237 "gradio_running": true,238 "api_running": true,239 "queue_size": 2,240 "total_jobs": 15,241 "storage": {242 "total_jobs": 12,243 "total_size_bytes": 52428800,244 "total_size_mb": 50.0,245 "output_directory": "/app/audiobooks/api"246 }247}248```249 250---251 252## Complete Workflow Example253 254### 1. Submit Conversion Request255 256```bash257curl -X POST https://your-space.hf.space/api/v1/tts/convert \258 -H "Content-Type: application/json" \259 -H "X-API-Key: your-api-key" \260 -d '{261 "text": "Welcome to the ebook2audiobook TTS API. This text will be converted to speech.",262 "language": "eng",263 "voice": "Morgan Freeman",264 "output_format": "mp3"265 }'266```267 268**Response**:269```json270{271 "job_id": "abc123",272 "status": "queued",273 "created_at": "2025-10-17T12:00:00Z"274}275```276 277### 2. Poll for Status278 279```bash280curl https://your-space.hf.space/api/v1/tts/status/abc123 \281 -H "X-API-Key: your-api-key"282```283 284**Response** (processing):285```json286{287 "job_id": "abc123",288 "status": "processing",289 "progress": 45,290 "error": null,291 "audio_url": null,292 "created_at": "2025-10-17T12:00:00Z",293 "expires_at": null294}295```296 297**Response** (completed):298```json299{300 "job_id": "abc123",301 "status": "completed",302 "progress": 100,303 "error": null,304 "audio_url": "/api/v1/audio/abc123",305 "created_at": "2025-10-17T12:00:00Z",306 "expires_at": "2025-10-18T12:00:00Z"307}308```309 310### 3. Download Audio311 312```bash313curl https://your-space.hf.space/api/v1/audio/abc123 \314 -H "X-API-Key: your-api-key" \315 -o output.mp3316```317 318---319 320## JavaScript/TypeScript Example321 322```typescript323const API_BASE = 'https://your-space.hf.space/api/v1';324const API_KEY = 'your-api-key';325 326async function convertTextToSpeech(text: string): Promise<Blob> {327 // 1. Submit conversion request328 const submitResponse = await fetch(`${API_BASE}/tts/convert`, {329 method: 'POST',330 headers: {331 'Content-Type': 'application/json',332 'X-API-Key': API_KEY,333 },334 body: JSON.stringify({335 text: text,336 language: 'eng',337 voice: 'Morgan Freeman',338 output_format: 'mp3',339 }),340 });341 342 if (!submitResponse.ok) {343 throw new Error(`Failed to submit: ${submitResponse.statusText}`);344 }345 346 const { job_id } = await submitResponse.json();347 console.log(`Job submitted: ${job_id}`);348 349 // 2. Poll for completion350 while (true) {351 const statusResponse = await fetch(`${API_BASE}/tts/status/${job_id}`, {352 headers: { 'X-API-Key': API_KEY },353 });354 355 if (!statusResponse.ok) {356 throw new Error(`Failed to check status: ${statusResponse.statusText}`);357 }358 359 const status = await statusResponse.json();360 console.log(`Status: ${status.status} (${status.progress}%)`);361 362 if (status.status === 'completed') {363 // 3. Download audio file364 const audioResponse = await fetch(`${API_BASE}/audio/${job_id}`, {365 headers: { 'X-API-Key': API_KEY },366 });367 368 if (!audioResponse.ok) {369 throw new Error(`Failed to download: ${audioResponse.statusText}`);370 }371 372 return await audioResponse.blob();373 }374 375 if (status.status === 'failed') {376 throw new Error(`Conversion failed: ${status.error}`);377 }378 379 // Wait 2 seconds before next poll380 await new Promise(resolve => setTimeout(resolve, 2000));381 }382}383 384// Usage385convertTextToSpeech('Hello world!')386 .then(audioBlob => {387 const url = URL.createObjectURL(audioBlob);388 const audio = new Audio(url);389 audio.play();390 })391 .catch(console.error);392```393 394---395 396## Python Example397 398```python399import requests400import time401 402API_BASE = 'https://your-space.hf.space/api/v1'403API_KEY = 'your-api-key'404 405def convert_text_to_speech(text: str) -> bytes:406 """Convert text to speech and return audio bytes."""407 408 # 1. Submit conversion request409 response = requests.post(410 f'{API_BASE}/tts/convert',411 headers={'X-API-Key': API_KEY},412 json={413 'text': text,414 'language': 'eng',415 'voice': 'Morgan Freeman',416 'output_format': 'mp3'417 }418 )419 response.raise_for_status()420 job_id = response.json()['job_id']421 print(f'Job submitted: {job_id}')422 423 # 2. Poll for completion424 while True:425 response = requests.get(426 f'{API_BASE}/tts/status/{job_id}',427 headers={'X-API-Key': API_KEY}428 )429 response.raise_for_status()430 status = response.json()431 432 print(f"Status: {status['status']} ({status['progress']}%)")433 434 if status['status'] == 'completed':435 # 3. Download audio436 response = requests.get(437 f"{API_BASE}/audio/{job_id}",438 headers={'X-API-Key': API_KEY}439 )440 response.raise_for_status()441 return response.content442 443 if status['status'] == 'failed':444 raise Exception(f"Conversion failed: {status['error']}")445 446 time.sleep(2)447 448# Usage449audio_data = convert_text_to_speech('Hello world!')450with open('output.mp3', 'wb') as f:451 f.write(audio_data)452```453 454---455 456## Rate Limiting457 458The API enforces rate limits to prevent abuse:459 460- **Limit**: 100 requests per hour per API key (default)461- **Window**: Sliding 1-hour window462- **Headers**: Rate limit info returned in response headers463 464**Response Headers**:465```http466X-RateLimit-Limit: 100467X-RateLimit-Remaining: 95468X-RateLimit-Reset: 1697547600469```470 471**Rate Limit Exceeded** (429):472```json473{474 "error": "Rate limit exceeded. Maximum 100 requests per hour.",475 "detail": null476}477```478 479**Headers**:480```http481Retry-After: 3456482```483 484---485 486## Error Handling487 488### Standard Error Response489 490```json491{492 "error": "Error message",493 "detail": "Additional error details (optional)"494}495```496 497### Common HTTP Status Codes498 499- `200 OK`: Request successful500- `202 Accepted`: Job accepted for processing501- `400 Bad Request`: Invalid request502- `401 Unauthorized`: Missing or invalid API key503- `404 Not Found`: Resource not found504- `410 Gone`: Resource expired505- `422 Unprocessable Entity`: Validation error506- `429 Too Many Requests`: Rate limit exceeded507- `500 Internal Server Error`: Server error508- `503 Service Unavailable`: Service temporarily unavailable509 510---511 512## Configuration513 514### Environment Variables515 516Server administrators can configure the following:517 518| Variable | Description | Default |519|----------|-------------|---------|520| `API_ENABLED` | Enable/disable API | `true` |521| `API_PORT` | API server port | `8000` |522| `API_HOST` | API server host | `0.0.0.0` |523| `API_KEY_1`, `API_KEY_2`, ... | Individual API keys | None |524| `API_KEYS` | Comma-separated API keys | None |525| `CORS_ORIGINS` | Allowed CORS origins | `*` |526| `MAX_REQUESTS_PER_HOUR` | Rate limit | `100` |527| `AUDIO_RETENTION_HOURS` | File retention period | `24` |528| `API_OUTPUT_DIR` | Output directory | `/app/audiobooks/api` |529| `CLEANUP_INTERVAL_SECONDS` | Cleanup frequency | `3600` |530 531---532 533## Interactive Documentation534 535The API provides interactive documentation powered by OpenAPI (Swagger):536 537- **Swagger UI**: `https://your-space.hf.space/api/v1/docs`538- **ReDoc**: `https://your-space.hf.space/api/v1/redoc`539- **OpenAPI JSON**: `https://your-space.hf.space/api/v1/openapi.json`540 541---542 543## Support544 545For issues, questions, or feature requests:546 547- GitHub Issues: https://github.com/DrewThomasson/ebook2audiobook/issues548- Documentation: https://github.com/DrewThomasson/ebook2audiobook/wiki549 