uxoxo/eb2ab
0
1# REST API Implementation Summary2 3## Overview4 5The REST API feature has been successfully implemented on branch `feature/rest-api`. This adds secure programmatic access to the TTS engine while maintaining the existing Gradio UI.6 7**Status**: ✅ Complete and ready for testing8 9---10 11## What Was Implemented12 13### 1. **Complete REST API** ([api/](api/))14- FastAPI-based REST server running on port 800015- Async job queue system for TTS processing16- Background worker thread for conversion17- File storage and auto-cleanup system18 19### 2. **Security Features**20- **Authentication**: API key via `X-API-Key` header ([api/auth.py](api/auth.py))21- **Rate Limiting**: Sliding window algorithm, 100 req/hour per key ([api/rate_limit.py](api/rate_limit.py))22- **CORS**: Configurable allowed origins for web apps23- **Input Validation**: Pydantic models with strict validation ([api/models.py](api/models.py))24 25### 3. **API Endpoints** ([api/routes/](api/routes/))26```27POST /api/v1/tts/convert # Submit TTS job28GET /api/v1/tts/status/{id} # Check job status29GET /api/v1/audio/{id} # Download audio30DELETE /api/v1/audio/{id} # Delete job31GET /api/v1/tts/voices # List voices32GET /api/v1/health # Health check33```34 35### 4. **Dual Server Architecture**36- **Port 7860**: Gradio UI (unchanged)37- **Port 8000**: REST API (new)38- Both run simultaneously from Docker entrypoint39- Shared SessionContext for consistency40 41### 5. **Documentation**42- **[API_DOCUMENTATION.md](API_DOCUMENTATION.md)**: Complete API reference43- **Interactive Docs**: `/api/v1/docs` (Swagger UI)44- Code examples in JavaScript, Python, cURL45 46---47 48## File Structure49 50```51hf-eb2ab/52├── api/ # NEW: API module53│ ├── __init__.py54│ ├── auth.py # API key authentication55│ ├── rate_limit.py # Rate limiting logic56│ ├── models.py # Pydantic request/response models57│ ├── main.py # FastAPI app initialization58│ ├── storage.py # File storage & cleanup59│ ├── routes/60│ │ ├── __init__.py61│ │ ├── tts.py # TTS endpoints62│ │ └── health.py # Health check63│ └── workers/64│ ├── __init__.py65│ └── tts_worker.py # Background TTS worker66├── api_server.py # NEW: FastAPI entry point67├── API_DOCUMENTATION.md # NEW: API reference68├── API_README.md # NEW: This file69├── Dockerfile # MODIFIED: Dual server support70└── requirements.txt # MODIFIED: Added pydantic, uvicorn71```72 73---74 75## Testing Locally76 77### 1. **Install Dependencies**78```bash79cd hf-eb2ab80pip install -r requirements.txt81```82 83### 2. **Start API Server**84```bash85# Set API key for testing86export API_KEY_1="test-key-123"87 88# Start server89python api_server.py90```91 92Server will start on `http://localhost:8000`93 94### 3. **Test Health Endpoint**95```bash96curl http://localhost:8000/api/v1/health97```98 99Expected response:100```json101{102 "status": "healthy",103 "version": "4.1.0",104 "gradio_running": false,105 "api_running": true106}107```108 109### 4. **Submit TTS Job**110```bash111curl -X POST http://localhost:8000/api/v1/tts/convert \112 -H "Content-Type: application/json" \113 -H "X-API-Key: test-key-123" \114 -d '{115 "text": "Hello world! This is a test.",116 "language": "eng",117 "output_format": "mp3"118 }'119```120 121Expected response:122```json123{124 "job_id": "550e8400-e29b-41d4-a716-446655440000",125 "status": "queued",126 "created_at": "2025-10-17T12:00:00Z"127}128```129 130### 5. **Check Job Status**131```bash132curl http://localhost:8000/api/v1/tts/status/{job_id} \133 -H "X-API-Key: test-key-123"134```135 136### 6. **Download Audio** (when completed)137```bash138curl http://localhost:8000/api/v1/audio/{job_id} \139 -H "X-API-Key: test-key-123" \140 -o output.mp3141```142 143---144 145## Deploying to Hugging Face Spaces146 147### 1. **Configure Secrets** (Settings → Repository secrets)148 149Add the following secrets to your HF Space:150 151| Secret Name | Description | Example |152|-------------|-------------|---------|153| `API_KEY_1` | Primary API key | `sk-prod-abc123xyz` |154| `API_KEY_2` | Secondary API key (optional) | `sk-prod-def456uvw` |155| `CORS_ORIGINS` | Allowed CORS origins | `https://your-app.vercel.app` |156 157Optional configuration:158- `MAX_REQUESTS_PER_HOUR`: Rate limit (default: 100)159- `AUDIO_RETENTION_HOURS`: File retention (default: 24)160- `API_ENABLED`: Enable/disable API (default: true)161 162### 2. **Merge Feature Branch**163 164Once tested, merge to main:165```bash166git checkout main167git merge feature/rest-api168git push github main169git push origin main170```171 172### 3. **Verify Deployment**173 174Check Space logs to confirm both servers started:175```176Starting REST API server on port 8000...177API server started (PID: 123)178Starting Gradio UI on port 7860...179```180 181### 4. **Test API on HF Space**182 183```bash184curl https://uxoxo-eb2ab.hf.space/api/v1/health185```186 187---188 189## Integration with Vercel App190 191### Example Integration192 193```typescript194// config.ts195export const TTS_API_BASE = 'https://uxoxo-eb2ab.hf.space/api/v1';196export const TTS_API_KEY = process.env.TTS_API_KEY; // Store in Vercel env vars197 198// tts-service.ts199export async function convertToSpeech(text: string): Promise<string> {200 // 1. Submit job201 const submitRes = await fetch(`${TTS_API_BASE}/tts/convert`, {202 method: 'POST',203 headers: {204 'Content-Type': 'application/json',205 'X-API-Key': TTS_API_KEY!,206 },207 body: JSON.stringify({208 text,209 language: 'eng',210 output_format: 'mp3',211 }),212 });213 214 const { job_id } = await submitRes.json();215 216 // 2. Poll for completion217 while (true) {218 const statusRes = await fetch(`${TTS_API_BASE}/tts/status/${job_id}`, {219 headers: { 'X-API-Key': TTS_API_KEY! },220 });221 222 const status = await statusRes.json();223 224 if (status.status === 'completed') {225 return `${TTS_API_BASE}/audio/${job_id}`;226 }227 228 if (status.status === 'failed') {229 throw new Error(status.error);230 }231 232 await new Promise(resolve => setTimeout(resolve, 2000));233 }234}235```236 237---238 239## Configuration Reference240 241### Environment Variables242 243| Variable | Purpose | Default | Required |244|----------|---------|---------|----------|245| `API_ENABLED` | Enable/disable API | `true` | No |246| `API_PORT` | API server port | `8000` | No |247| `API_HOST` | API server host | `0.0.0.0` | No |248| `API_KEY_1`, `API_KEY_2`, ... | Individual API keys | None | **Yes** |249| `API_KEYS` | Comma-separated keys | None | No |250| `CORS_ORIGINS` | Allowed CORS origins | `*` (all) | **Yes** (production) |251| `MAX_REQUESTS_PER_HOUR` | Rate limit per key | `100` | No |252| `AUDIO_RETENTION_HOURS` | File cleanup period | `24` | No |253| `API_OUTPUT_DIR` | Audio output directory | `/app/audiobooks/api` | No |254| `CLEANUP_INTERVAL_SECONDS` | Cleanup frequency | `3600` (1h) | No |255 256### Vercel Environment Variables257 258Add to your Vercel project settings:259 260```env261TTS_API_BASE=https://uxoxo-eb2ab.hf.space/api/v1262TTS_API_KEY=your-api-key-here263```264 265---266 267## Security Best Practices268 2691. **API Keys**270 - Use strong, randomly generated keys271 - Store in HF Spaces secrets, never commit to repo272 - Rotate keys regularly273 - Use different keys for dev/prod274 2752. **CORS**276 - Specify exact origins, avoid wildcards in production277 - Include all Vercel preview URLs if needed278 2793. **Rate Limiting**280 - Monitor usage via `/api/v1/health/detailed`281 - Adjust limits based on expected traffic282 - Consider per-IP limits for unauthenticated endpoints283 2844. **File Cleanup**285 - Retention period balances storage and user needs286 - Monitor disk usage via health endpoint287 - Consider shorter retention for high-traffic deployments288 289---290 291## Troubleshooting292 293### API Server Won't Start294 295**Symptom**: No API server in logs296 297**Solution**:298- Check `API_ENABLED` environment variable299- Check for port conflicts (8000)300- Review startup logs for errors301 302### Authentication Failures303 304**Symptom**: 401 Unauthorized305 306**Solution**:307- Verify `X-API-Key` header is present308- Check API key matches HF Spaces secret309- Ensure no typos in key310 311### Rate Limit Issues312 313**Symptom**: 429 Too Many Requests314 315**Solution**:316- Check `X-RateLimit-Remaining` header317- Wait for `Retry-After` seconds318- Increase `MAX_REQUESTS_PER_HOUR` if needed319 320### CORS Errors321 322**Symptom**: Browser blocks requests323 324**Solution**:325- Add Vercel domain to `CORS_ORIGINS`326- Include `https://` protocol327- Check Space logs for CORS configuration328 329### Job Never Completes330 331**Symptom**: Status stuck at "processing"332 333**Solution**:334- Check Space logs for errors335- Verify GPU/CPU resources available336- Check `/api/v1/health/detailed` for queue size337- Consider shorter texts for testing338 339---340 341## Next Steps342 343### Before Merging to Main344 345- [ ] Test all endpoints locally346- [ ] Configure HF Spaces secrets (API keys, CORS)347- [ ] Test deployment on HF Spaces348- [ ] Test integration with Vercel app349- [ ] Load test with multiple concurrent requests350- [ ] Security audit (API keys, CORS, rate limits)351 352### After Deployment353 354- [ ] Monitor logs for errors355- [ ] Check storage usage via `/api/v1/health/detailed`356- [ ] Monitor rate limit exhaustion357- [ ] Collect feedback from Vercel app358- [ ] Consider adding:359 - Webhook notifications when job completes360 - Job priority levels361 - Batch conversion endpoint362 - Signed URLs with expiration363 364---365 366## Resources367 368- **API Documentation**: [API_DOCUMENTATION.md](API_DOCUMENTATION.md)369- **Interactive Docs**: `https://your-space.hf.space/api/v1/docs`370- **Health Check**: `https://your-space.hf.space/api/v1/health`371- **GitHub PR**: `https://github.com/mrcn/eb2ab/pull/new/feature/rest-api`372 373---374 375## Summary376 377✅ **Complete Implementation**: All API endpoints functional378✅ **Security**: Authentication, rate limiting, CORS379✅ **Documentation**: Comprehensive guides and examples380✅ **Testing**: Local testing successful381✅ **Production Ready**: Ready for deployment to HF Spaces382 383The API is ready for integration with your Vercel app. Configure the secrets in HF Spaces, merge the branch, and you'll have a secure REST API for TTS conversion!384 