Spaces:
Sleeping
Sleeping
File size: 12,063 Bytes
24dc421 |
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 |
# WebSocket Protocol
## Overview
The Voice-to-Voice Translator uses a WebSocket-based protocol for real-time bidirectional communication between clients and the server. Messages are exchanged in JSON format (text) and raw audio data (binary).
## Connection Endpoint
```
ws://host:port/ws
```
### Connection Parameters
Query parameters (optional):
- `token`: JWT authentication token (if auth enabled)
- `client_id`: Unique client identifier
Example:
```
ws://localhost:8000/ws?token=eyJhbGc...&client_id=client123
```
## Message Types
All text messages follow this structure:
```json
{
"type": "message_type",
"payload": { ... },
"timestamp": "2025-12-17T10:30:00Z",
"message_id": "uuid-v4"
}
```
### Client โ Server Messages
#### 1. JOIN_ROOM
Join or create a translation room.
```json
{
"type": "join_room",
"payload": {
"room_id": "room123",
"user_id": "user1",
"username": "John Doe",
"source_lang": "en",
"target_lang": "hi"
}
}
```
**Fields**:
- `room_id`: Unique room identifier
- `user_id`: Unique user identifier
- `username`: Display name
- `source_lang`: User's speaking language (ISO 639-1 code)
- `target_lang`: Desired translation language
**Response**: `ROOM_JOINED` or `ERROR`
#### 2. LEAVE_ROOM
Leave current room.
```json
{
"type": "leave_room",
"payload": {
"room_id": "room123",
"user_id": "user1"
}
}
```
**Response**: `ROOM_LEFT` or `ERROR`
#### 3. AUDIO_START
Signal start of audio stream.
```json
{
"type": "audio_start",
"payload": {
"room_id": "room123",
"user_id": "user1",
"audio_config": {
"sample_rate": 16000,
"channels": 1,
"format": "PCM16",
"chunk_size": 4096
}
}
}
```
**Response**: `AUDIO_START_ACK`
#### 4. AUDIO_STOP
Signal end of audio stream.
```json
{
"type": "audio_stop",
"payload": {
"room_id": "room123",
"user_id": "user1"
}
}
```
**Response**: `AUDIO_STOP_ACK`
#### 5. TEXT_MESSAGE
Send text message (for chat or corrections).
```json
{
"type": "text_message",
"payload": {
"room_id": "room123",
"user_id": "user1",
"text": "Hello, how are you?",
"lang": "en"
}
}
```
**Response**: `TEXT_MESSAGE` (broadcast to room)
#### 6. PING
Heartbeat message.
```json
{
"type": "ping",
"payload": {}
}
```
**Response**: `PONG`
#### 7. GET_ROOM_INFO
Request current room state.
```json
{
"type": "get_room_info",
"payload": {
"room_id": "room123"
}
}
```
**Response**: `ROOM_INFO`
### Server โ Client Messages
#### 1. ROOM_JOINED
Confirmation of room join.
```json
{
"type": "room_joined",
"payload": {
"room_id": "room123",
"user_id": "user1",
"users": [
{
"user_id": "user1",
"username": "John Doe",
"source_lang": "en",
"target_lang": "hi"
},
{
"user_id": "user2",
"username": "Jane Smith",
"source_lang": "hi",
"target_lang": "en"
}
]
}
}
```
#### 2. ROOM_LEFT
Confirmation of room leave.
```json
{
"type": "room_left",
"payload": {
"room_id": "room123",
"user_id": "user1"
}
}
```
#### 3. USER_JOINED
Broadcast when another user joins.
```json
{
"type": "user_joined",
"payload": {
"room_id": "room123",
"user": {
"user_id": "user2",
"username": "Jane Smith",
"source_lang": "hi",
"target_lang": "en"
}
}
}
```
#### 4. USER_LEFT
Broadcast when another user leaves.
```json
{
"type": "user_left",
"payload": {
"room_id": "room123",
"user_id": "user2",
"username": "Jane Smith"
}
}
```
#### 5. TRANSCRIPTION
Intermediate transcription result (from STT).
```json
{
"type": "transcription",
"payload": {
"room_id": "room123",
"user_id": "user1",
"text": "Hello how are you",
"lang": "en",
"is_final": false,
"confidence": 0.85
}
}
```
#### 6. TRANSLATION
Translation result.
```json
{
"type": "translation",
"payload": {
"room_id": "room123",
"source_user_id": "user1",
"target_user_id": "user2",
"original_text": "Hello, how are you?",
"translated_text": "เคจเคฎเคธเฅเคคเฅ, เคเคช เคเฅเคธเฅ เคนเฅเค?",
"source_lang": "en",
"target_lang": "hi",
"confidence": 0.92
}
}
```
#### 7. AUDIO_START_ACK
Acknowledgment of audio start.
```json
{
"type": "audio_start_ack",
"payload": {
"room_id": "room123",
"user_id": "user1",
"ready": true
}
}
```
#### 8. AUDIO_STOP_ACK
Acknowledgment of audio stop.
```json
{
"type": "audio_stop_ack",
"payload": {
"room_id": "room123",
"user_id": "user1"
}
}
```
#### 9. PONG
Heartbeat response.
```json
{
"type": "pong",
"payload": {
"timestamp": "2025-12-17T10:30:00Z"
}
}
```
#### 10. ROOM_INFO
Room state information.
```json
{
"type": "room_info",
"payload": {
"room_id": "room123",
"created_at": "2025-12-17T10:00:00Z",
"users": [ ... ],
"active_speakers": ["user1"],
"supported_languages": ["en", "hi"]
}
}
```
#### 11. ERROR
Error notification.
```json
{
"type": "error",
"payload": {
"code": "INVALID_ROOM",
"message": "Room does not exist",
"details": "Room 'room123' not found",
"recoverable": true
}
}
```
**Error Codes**:
- `INVALID_ROOM`: Room not found
- `ROOM_FULL`: Maximum users reached
- `INVALID_MESSAGE`: Malformed message
- `AUTH_FAILED`: Authentication failed
- `RATE_LIMIT`: Too many requests
- `INTERNAL_ERROR`: Server error
- `UNSUPPORTED_LANGUAGE`: Language not available
- `AUDIO_ERROR`: Audio processing error
## Binary Audio Messages
Audio data is sent as binary WebSocket frames.
### Client โ Server (Audio Input)
Binary message structure:
```
[Header (16 bytes)][Audio Data (variable)]
```
**Header Format**:
- Bytes 0-7: User ID (UTF-8, padded)
- Bytes 8-11: Sequence number (uint32, big-endian)
- Bytes 12-15: Timestamp (uint32, milliseconds)
**Audio Data**:
- Format: PCM16 (16-bit signed integer)
- Sample Rate: 16000 Hz (configurable)
- Channels: 1 (mono)
- Byte Order: Little-endian
### Server โ Client (Translated Audio)
Binary message structure:
```
[Header (24 bytes)][Audio Data (variable)]
```
**Header Format**:
- Bytes 0-7: Source User ID (UTF-8, padded)
- Bytes 8-15: Target User ID (UTF-8, padded)
- Bytes 16-19: Sequence number (uint32, big-endian)
- Bytes 20-23: Timestamp (uint32, milliseconds)
**Audio Data**:
- Same format as input
## Connection Lifecycle
### 1. Connection Establishment
```
Client Server
โ โ
โโโโโโโโ WebSocket Connect โโโโโบโ
โ โ
โโโโโโโโ Connection Open โโโโโโโโค
โ โ
```
### 2. Room Join
```
Client Server
โ โ
โโโโโโโโโโโ JOIN_ROOM โโโโโโโโโโบโ
โ โ
โโโโโโโโโโโ ROOM_JOINED โโโโโโโโโค
โ โ
โโโโโโโโโโโ USER_JOINED โโโโโโโโโค (broadcast to others)
โ โ
```
### 3. Audio Streaming
```
Client Server Other Client
โ โ โ
โโโโโโ AUDIO_START โโโโโโโโโโโโโบโ โ
โ โ โ
โโโโโโ AUDIO_START_ACK โโโโโโโโโโค โ
โ โ โ
โโโโ Binary Audio Chunk 1 โโโโโโบโ โ
โโโโ Binary Audio Chunk 2 โโโโโโบโ โ
โ โ โ
โโโโโโโโโ TRANSCRIPTION โโโโโโโโโค โ
โ โ โ
โโโโโโโโโ TRANSLATION โโโโโโโโโโโค โ
โ โ โ
โ โโโโโบ Binary Audio Chunk โโโโโโบโ
โ โ โ
โโโโโโ AUDIO_STOP โโโโโโโโโโโโโโบโ โ
โ โ โ
โโโโโโ AUDIO_STOP_ACK โโโโโโโโโโโค โ
โ โ โ
```
### 4. Disconnection
```
Client Server
โ โ
โโโโโโโโโโโ LEAVE_ROOM โโโโโโโโโบโ
โ โ
โโโโโโโโโโโ ROOM_LEFT โโโโโโโโโโโค
โ โ
โโโโโโโโ Close Connection โโโโโโบโ
โ โ
โโโโโโโโโ Close Confirm โโโโโโโโโค
โ โ
```
## Rate Limiting
Default limits:
- Join room: 10 requests per minute
- Audio streaming: Unlimited (quality-based throttling)
- Text messages: 30 per minute
- Room info requests: 60 per minute
## Reconnection Strategy
1. **Exponential Backoff**: 1s, 2s, 4s, 8s, 16s, 30s (max)
2. **Session Recovery**: Send previous `room_id` and `user_id` on reconnect
3. **State Sync**: Server sends current room state after reconnection
## Best Practices
### Client Implementation
1. **Always send AUDIO_START before binary audio**
2. **Buffer audio before sending** (minimum 100ms chunks)
3. **Include sequence numbers** for ordering
4. **Handle ERROR messages** gracefully
5. **Implement heartbeat** (PING every 30 seconds)
6. **Reconnect automatically** on disconnect
### Server Implementation
1. **Validate all messages** before processing
2. **Broadcast state changes** to all room members
3. **Clean up resources** on disconnect
4. **Log all errors** with context
5. **Rate limit** per connection and IP
## Example Client Flow (JavaScript)
```javascript
const ws = new WebSocket('ws://localhost:8000/ws');
// Connect
ws.onopen = () => {
// Join room
ws.send(JSON.stringify({
type: 'join_room',
payload: {
room_id: 'room123',
user_id: 'user1',
username: 'John',
source_lang: 'en',
target_lang: 'hi'
}
}));
};
// Handle messages
ws.onmessage = (event) => {
if (event.data instanceof Blob) {
// Binary audio data
handleAudio(event.data);
} else {
// JSON message
const msg = JSON.parse(event.data);
handleMessage(msg);
}
};
// Send audio
function sendAudio(audioBuffer) {
ws.send(audioBuffer);
}
```
## Security Considerations
1. **Always use WSS (WebSocket Secure)** in production
2. **Validate JWT tokens** if authentication enabled
3. **Sanitize user inputs** (usernames, room IDs)
4. **Implement rate limiting** to prevent abuse
5. **Monitor connection count** to prevent DoS
6. **Encrypt sensitive data** in messages
|