File size: 13,240 Bytes
c27ae8d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
# API Design
## Overview
The Rescored API provides REST endpoints for job submission and status tracking, plus WebSocket connections for real-time progress updates.
## Base URL
- **Development**: `http://localhost:8000`
- **Production**: `https://api.rescored.com` (future)
## Authentication
**MVP**: No authentication (local development only)
**Future**: JWT-based authentication
```http
Authorization: Bearer <jwt_token>
```
---
## REST Endpoints
### 1. Submit Transcription Job
**Endpoint**: `POST /api/v1/transcribe`
**Purpose**: Submit a YouTube URL for transcription processing.
**Request**:
```json
{
"youtube_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
"options": {
"instruments": ["piano"], // MVP: only "piano", future: ["drums", "bass", "guitar", etc.]
"tempo_override": null, // Optional: override detected tempo (BPM)
"key_override": null // Optional: override detected key (e.g., "C", "Gm")
}
}
```
**Response** (201 Created):
```json
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "queued",
"created_at": "2025-01-15T10:30:00Z",
"estimated_duration_seconds": 120,
"websocket_url": "ws://localhost:8000/api/v1/jobs/550e8400-e29b-41d4-a716-446655440000/stream"
}
```
**Errors**:
```json
// 400 Bad Request - Invalid URL
{
"error": "Invalid YouTube URL format"
}
// 422 Unprocessable Entity - Video unavailable
{
"error": "Video is age-restricted or private"
}
// 429 Too Many Requests - Rate limit exceeded
{
"error": "Rate limit exceeded. Max 10 jobs per hour.",
"retry_after_seconds": 3600
}
```
**Implementation**:
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, HttpUrl
from uuid import uuid4
from datetime import datetime
app = FastAPI()
class TranscribeRequest(BaseModel):
youtube_url: HttpUrl
options: dict = {"instruments": ["piano"]}
class TranscribeResponse(BaseModel):
job_id: str
status: str
created_at: datetime
estimated_duration_seconds: int
websocket_url: str
@app.post("/api/v1/transcribe", response_model=TranscribeResponse, status_code=201)
async def submit_transcription(request: TranscribeRequest):
# Validate YouTube URL
is_valid, video_id_or_error = validate_youtube_url(str(request.youtube_url))
if not is_valid:
raise HTTPException(status_code=400, detail=video_id_or_error)
# Check video availability
availability = check_video_availability(video_id_or_error)
if not availability['available']:
raise HTTPException(status_code=422, detail=availability['reason'])
# Create job
job_id = str(uuid4())
job_data = {
"job_id": job_id,
"status": "queued",
"youtube_url": str(request.youtube_url),
"video_id": video_id_or_error,
"options": request.options,
"created_at": datetime.utcnow().isoformat(),
"progress": 0,
}
# Store in Redis
redis_client.hset(f"job:{job_id}", mapping=job_data)
# Queue Celery task
process_transcription_task.delay(job_id)
return TranscribeResponse(
job_id=job_id,
status="queued",
created_at=datetime.utcnow(),
estimated_duration_seconds=120,
websocket_url=f"ws://localhost:8000/api/v1/jobs/{job_id}/stream"
)
```
---
### 2. Get Job Status
**Endpoint**: `GET /api/v1/jobs/{job_id}`
**Purpose**: Poll job status (alternative to WebSocket).
**Response**:
```json
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "processing", // "queued" | "processing" | "completed" | "failed"
"progress": 65, // 0-100
"current_stage": "transcription", // "download" | "separation" | "transcription" | "musicxml"
"created_at": "2025-01-15T10:30:00Z",
"started_at": "2025-01-15T10:30:05Z",
"completed_at": null,
"error": null,
"result_url": null // Available when status="completed"
}
```
**Completed Job**:
```json
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "completed",
"progress": 100,
"current_stage": "musicxml",
"created_at": "2025-01-15T10:30:00Z",
"started_at": "2025-01-15T10:30:05Z",
"completed_at": "2025-01-15T10:32:15Z",
"duration_seconds": 130,
"result_url": "/api/v1/scores/550e8400-e29b-41d4-a716-446655440000"
}
```
**Failed Job**:
```json
{
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"status": "failed",
"progress": 35,
"current_stage": "separation",
"error": {
"message": "GPU out of memory",
"retryable": true
},
"created_at": "2025-01-15T10:30:00Z",
"started_at": "2025-01-15T10:30:05Z",
"failed_at": "2025-01-15T10:31:20Z"
}
```
**Implementation**:
```python
@app.get("/api/v1/jobs/{job_id}")
async def get_job_status(job_id: str):
job_data = redis_client.hgetall(f"job:{job_id}")
if not job_data:
raise HTTPException(status_code=404, detail="Job not found")
return job_data
```
---
### 3. Download MusicXML
**Endpoint**: `GET /api/v1/scores/{job_id}`
**Purpose**: Download the generated MusicXML file.
**Response**: `application/vnd.recordare.musicxml+xml`
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 4.0 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd">
<score-partwise version="4.0">
<part-list>
<score-part id="P1">
<part-name>Piano</part-name>
</score-part>
</part-list>
<part id="P1">
<!-- measures, notes, etc. -->
</part>
</score-partwise>
```
**Headers**:
```
Content-Type: application/vnd.recordare.musicxml+xml
Content-Disposition: attachment; filename="score_550e8400.musicxml"
```
**Errors**:
```json
// 404 Not Found
{
"error": "Job not found or not yet completed"
}
```
**Implementation**:
```python
from fastapi.responses import FileResponse
@app.get("/api/v1/scores/{job_id}")
async def download_score(job_id: str):
job_data = redis_client.hgetall(f"job:{job_id}")
if not job_data or job_data['status'] != 'completed':
raise HTTPException(status_code=404, detail="Score not available")
file_path = Path(job_data['output_path'])
if not file_path.exists():
raise HTTPException(status_code=404, detail="Score file not found")
return FileResponse(
path=file_path,
media_type="application/vnd.recordare.musicxml+xml",
filename=f"score_{job_id}.musicxml"
)
```
---
### 4. Download MIDI
**Endpoint**: `GET /api/v1/scores/{job_id}/midi`
**Purpose**: Download MIDI version of the score.
**Response**: `audio/midi`
**Headers**:
```
Content-Type: audio/midi
Content-Disposition: attachment; filename="score_550e8400.mid"
```
**Implementation**:
```python
@app.get("/api/v1/scores/{job_id}/midi")
async def download_midi(job_id: str):
# Similar to MusicXML download, but serve .mid file
pass
```
---
## WebSocket Endpoint
### Real-Time Progress Updates
**Endpoint**: `WS /api/v1/jobs/{job_id}/stream`
**Purpose**: Stream real-time progress updates to the client.
**Connection**:
```javascript
// Frontend code
const ws = new WebSocket(`ws://localhost:8000/api/v1/jobs/${jobId}/stream`);
ws.onmessage = (event) => {
const update = JSON.parse(event.data);
console.log(update);
};
```
**Message Types**:
**1. Progress Update**:
```json
{
"type": "progress",
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"progress": 45,
"stage": "separation",
"message": "Separated drums stem",
"timestamp": "2025-01-15T10:30:45Z"
}
```
**2. Completion**:
```json
{
"type": "completed",
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"progress": 100,
"result_url": "/api/v1/scores/550e8400-e29b-41d4-a716-446655440000",
"timestamp": "2025-01-15T10:32:15Z"
}
```
**3. Error**:
```json
{
"type": "error",
"job_id": "550e8400-e29b-41d4-a716-446655440000",
"error": {
"message": "Failed to download audio: Network error",
"retryable": true
},
"timestamp": "2025-01-15T10:31:00Z"
}
```
**Implementation**:
```python
from fastapi import WebSocket
from fastapi.websockets import WebSocketDisconnect
import asyncio
class ConnectionManager:
def __init__(self):
self.active_connections: dict[str, list[WebSocket]] = {}
async def connect(self, websocket: WebSocket, job_id: str):
await websocket.accept()
if job_id not in self.active_connections:
self.active_connections[job_id] = []
self.active_connections[job_id].append(websocket)
def disconnect(self, websocket: WebSocket, job_id: str):
self.active_connections[job_id].remove(websocket)
async def send_update(self, job_id: str, message: dict):
if job_id in self.active_connections:
for connection in self.active_connections[job_id]:
await connection.send_json(message)
manager = ConnectionManager()
@app.websocket("/api/v1/jobs/{job_id}/stream")
async def websocket_endpoint(websocket: WebSocket, job_id: str):
await manager.connect(websocket, job_id)
try:
# Keep connection alive and send updates
while True:
# Check for updates in Redis
job_data = redis_client.hgetall(f"job:{job_id}")
if job_data:
message = {
"type": "progress",
"job_id": job_id,
"progress": int(job_data.get('progress', 0)),
"stage": job_data.get('current_stage', ''),
"message": job_data.get('status_message', ''),
"timestamp": datetime.utcnow().isoformat(),
}
await websocket.send_json(message)
# Check if job completed or failed
if job_data['status'] in ['completed', 'failed']:
break
await asyncio.sleep(1) # Poll every second
except WebSocketDisconnect:
manager.disconnect(websocket, job_id)
```
**Alternative: Redis Pub/Sub for Efficiency**
Instead of polling Redis every second, use pub/sub:
```python
# Worker publishes updates
redis_client.publish(f"job:{job_id}:updates", json.dumps(message))
# WebSocket subscribes
pubsub = redis_client.pubsub()
pubsub.subscribe(f"job:{job_id}:updates")
for message in pubsub.listen():
await websocket.send_json(json.loads(message['data']))
```
---
## Data Models
### Job Status
```python
from enum import Enum
class JobStatus(str, Enum):
QUEUED = "queued"
PROCESSING = "processing"
COMPLETED = "completed"
FAILED = "failed"
class JobStage(str, Enum):
DOWNLOAD = "download"
SEPARATION = "separation"
TRANSCRIPTION = "transcription"
MUSICXML = "musicxml"
```
### Job Schema (Redis)
```python
job_data = {
"job_id": str,
"status": JobStatus,
"youtube_url": str,
"video_id": str,
"progress": int, # 0-100
"current_stage": JobStage,
"status_message": str, # e.g., "Separated drums stem"
"created_at": str, # ISO 8601
"started_at": str | None,
"completed_at": str | None,
"failed_at": str | None,
"output_path": str | None, # Path to .musicxml file
"error": dict | None,
}
```
---
## Error Handling
### HTTP Error Codes
| Code | Meaning | Example |
|------|---------|---------|
| 400 | Bad Request | Invalid URL format |
| 404 | Not Found | Job ID doesn't exist |
| 422 | Unprocessable Entity | Video unavailable or age-restricted |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Unexpected server error |
### Error Response Format
```json
{
"error": "Human-readable error message",
"details": {
"field": "youtube_url",
"issue": "Invalid format"
}
}
```
---
## Rate Limiting
**MVP**: Simple in-memory rate limiting
**Production**: Redis-based rate limiting with sliding window
**Limits**:
- 10 jobs per IP per hour (unauthenticated)
- 100 jobs per user per hour (authenticated, future)
**Implementation**:
```python
from fastapi import Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.post("/api/v1/transcribe")
@limiter.limit("10/hour")
async def submit_transcription(request: Request, transcribe_request: TranscribeRequest):
# ... implementation
pass
```
---
## CORS Configuration
**Development**:
```python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5173"], # Vite dev server
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
```
**Production**:
```python
allow_origins=["https://rescored.com", "https://www.rescored.com"]
```
---
## API Versioning
**Current**: `/api/v1/`
**Future**: `/api/v2/` for breaking changes
**Deprecation Policy**: Support old version for 6 months after new version release
---
## Next Steps
1. Implement [Celery workers](workers.md) to process jobs
2. Test WebSocket connections with frontend
3. Add monitoring for API latency and error rates
4. Implement proper authentication for production
See [WebSocket Protocol](../integration/websocket-protocol.md) for detailed message specs.
|