ASR Server API Documentation

Last Updated: 2026-02-05 Server: asr_server.py Version: Multi-stage cascade with 24K/58 models


Table of Contents

  1. WebSocket API
  2. HAProxy Health Check API
  3. Implementation Guide: Immediate Detection Flag

WebSocket API

Connection

Endpoint: ws://{host}:{port}/

Default Ports:

Example:

const ws = new WebSocket('ws://localhost:2700/');

Protocol Flow

1. Send Config Message (JSON)

Required at connection start.

{
  "config": {
    "sample_rate": 8000,
    "VID": "V1234567890123456789",
    "phone": "15551234567",
    "country_code": "1"
  }
}

Parameters:

New Parameter (for immediate detection):

2. Send Audio Data (Binary)

Send raw 16-bit PCM audio chunks as binary WebSocket messages.

Audio Format:

Example (Python):

import numpy as np

# Generate or read audio
audio_data = np.frombuffer(wav_bytes, dtype=np.int16)

# Send in chunks
chunk_size = 8000  # 1 second at 8kHz
for i in range(0, len(audio_data), chunk_size):
    chunk = audio_data[i:i+chunk_size].tobytes()
    await websocket.send(chunk)

3. Send EOF Message (JSON)

Signal end of audio stream:

{"eof": 1}

4. Receive Detection Result (JSON)

Response Format:

{
  "classification": "AMD",
  "amd_conf": 0.9234,
  "human_conf": 0.0766,
  "greeting_class": "welcome_voicemail",
  "greeting_conf": 0.8912,
  "model_history": "4k:HUMAN:0.10:0.90:1;8k:HUMAN:0.15:0.85:1;16k:AMD:0.65:0.35:0;24k:AMD:0.92:0.08:0;32k:welcome_voicemail:0.89"
}

Fields:

Model History Format:

4k:HUMAN:0.10:0.90:1;8k:HUMAN:0.15:0.85:1;24k:AMD:0.92:0.08:0

Cascade Behavior

Current Implementation (Default):

The server runs a multi-stage cascade:

  1. 4K stage (0.5s audio): Exit if HUMAN confidence ≥ 0.991
  2. 8K stage (1.0s audio): Exit if HUMAN confidence ≥ 0.9985
  3. 12K stage (1.5s audio): Exit if HUMAN confidence ≥ 0.99
  4. 16K stage (2.0s audio): Exit if HUMAN confidence ≥ 0.98
  5. 24K stage (3.0s audio): Exit if HUMAN confidence ≥ 0.997 OR AMD confidence ≥ 0.85
  6. 32K stage (4.0s audio): Final decision + greeting classification

Code Location: /usr/src/asr_server_new/asr_server.py lines ~1800-2200

Error Responses

Connection Errors:


HAProxy Health Check API

HTTP Endpoint

Endpoint: GET http://{host}:{port}/haproxy

Port: Main port + 10 (e.g., if WebSocket is 2700, health is 2710)

Response Format (text/plain):

status:ok cpu_percent:12.3 avg_proc_ms:8.45 disconnect_rate:2 current_rps:15.20 current_cps:3.50 total_requests:45231 total_connections:12043 load_factor:35 haproxy_weight:65

Fields:

Load Factor Calculation:

proc_time_load = min(100, (avg_proc_ms / 50.0) * 50)
cpu_load = min(100, (cpu_percent / 90.0) * 50)
disconnect_load = min(30, disconnect_rate)
total_load_factor = min(100, proc_time_load + cpu_load + disconnect_load)
haproxy_weight = max(1, 100 - total_load_factor)

TCP Agent-Check Endpoint

Endpoint: TCP connection to {host}:{port+20}

Port: Main port + 20 (e.g., if WebSocket is 2700, agent is 2720)

Protocol: HAProxy agent-check protocol Docs: https://www.haproxy.com/documentation/hapee/latest/load-balancing/health-checking/agent-checks/

Response Format:

ready 65%\n

Possible Responses:

Weight Calculation: Same as HTTP endpoint

HAProxy Configuration Example:

backend asr_servers
    balance leastconn
    option tcp-check

    server asr1 10.0.0.10:2700 check agent-check agent-port 2720 agent-inter 5s
    server asr2 10.0.0.11:2700 check agent-check agent-port 2720 agent-inter 5s
    server asr3 10.0.0.12:2700 check agent-check agent-port 2720 agent-inter 5s

Legacy Health Check

Endpoint: GET http://{host}:{port}/health

Response (text/plain):

status:ok cpu_percent:12.3 avg_proc_ms:8.45 ...

Same format as /haproxy endpoint.

Ping Endpoint: GET http://{host}:{port}/ping

Response: OK (200)

Fast lightweight health check without statistics calculation.


Implementation Guide: Immediate Detection Flag

Feature Description

Add a configuration flag immediate_detection that bypasses the cascade and returns the first confident detection without waiting for additional stages.

Use Case: Low-latency applications that prioritize speed over maximum accuracy.

Current Code Structure

Config Message Handler: asr_server.py lines 2580-2594

if 'config' in message:
    t_config = time.time()
    jobj = json.loads(message)['config']
    if 'VID' in jobj:
        VID = jobj['VID']
        client_phone = jobj.get('phone', '')
        client_country_code = jobj.get('country_code', '')
        # ... connection tracking ...

Cascade Logic: asr_server.py lines ~1800-2200 (in AcceptWaveform method)

Implementation Steps

Step 1: Add Flag to Config Parser

File: /usr/src/asr_server_new/asr_server.py

Location: Lines 2580-2594

Add after line 2587:

# Extract immediate_detection flag
immediate_detection = jobj.get('immediate_detection', False)

Store in connection state (add instance variable to class):

# In __init__ of class (around line 1600)
self._immediate_detection = False

# In config handler (line 2590)
self._immediate_detection = jobj.get('immediate_detection', False)

Step 2: Modify Cascade Exit Logic

Location: In AcceptWaveform method, cascade decision logic

Current code (example from 4K stage):

if human_conf >= 0.991:
    should_exit = True
    logging.debug("4K HUMAN early exit (conf=%.3f >= 0.991)", human_conf)

Modified code:

# Early exit conditions
if self._immediate_detection:
    # Immediate mode: exit on ANY confident detection (≥0.85 for either class)
    if amd_conf >= 0.85 or human_conf >= 0.85:
        should_exit = True
        detection_class = "AMD" if amd_conf > human_conf else "HUMAN"
        logging.debug("4K %s immediate exit (conf=%.3f >= 0.85, immediate_detection=True)",
                     detection_class, max(amd_conf, human_conf))
else:
    # Normal cascade mode: continue to next stage unless very confident HUMAN
    if human_conf >= 0.991:
        should_exit = True
        logging.debug("4K HUMAN early exit (conf=%.3f >= 0.991)", human_conf)

Apply this pattern to all stages (4K, 8K, 12K, 16K, 24K).

Step 3: Add Flag to Model History

Location: Model history logging (where model_history string is built)

Add immediate flag to history:

# Example format: "4k:HUMAN:0.10:0.90:1:imm" (imm = immediate mode)
if self._immediate_detection:
    model_history += f"{model_name}:{classification}:{amd_conf:.2f}:{human_conf:.2f}:{1 if should_exit else 0}:imm;"
else:
    model_history += f"{model_name}:{classification}:{amd_conf:.2f}:{human_conf:.2f}:{1 if should_exit else 0};"

Step 4: Update Response JSON

No changes needed - response format remains the same.

Testing

Test with immediate detection OFF (default behavior):

import asyncio
import websockets
import json

async def test_normal():
    uri = "ws://localhost:2700/"
    async with websockets.connect(uri) as ws:
        # Send config without immediate_detection
        config = {"config": {"sample_rate": 8000, "VID": "TEST001"}}
        await ws.send(json.dumps(config))

        # Send audio...
        # ...

        # Receive result
        result = await ws.recv()
        print(f"Normal mode result: {result}")

asyncio.run(test_normal())

Test with immediate detection ON:

async def test_immediate():
    uri = "ws://localhost:2700/"
    async with websockets.connect(uri) as ws:
        # Send config WITH immediate_detection
        config = {
            "config": {
                "sample_rate": 8000,
                "VID": "TEST002",
                "immediate_detection": True  # NEW FLAG
            }
        }
        await ws.send(json.dumps(config))

        # Send audio...
        # ...

        # Receive result (should be faster, may exit at 4K or 8K)
        result = await ws.recv()
        print(f"Immediate mode result: {result}")

asyncio.run(test_immediate())

Expected Behavior

Without immediate_detection (default):

With immediate_detection=true:

Performance Impact

Latency Reduction:

Accuracy Impact:

Monitoring

Add metrics to track immediate detection usage:

# In performance tracker
immediate_detection_count = 0
immediate_detection_exits = {}  # Track which stage exits happen

# Log when immediate detection is used
if self._immediate_detection:
    logging.info("Connection using immediate_detection mode, VID=%s", VID)

Client Examples

Python Client

import asyncio
import websockets
import json
import numpy as np
import soundfile as sf

async def amd_detect(audio_file, immediate=False):
    uri = "ws://localhost:2700/"

    async with websockets.connect(uri) as ws:
        # Send config
        config = {
            "config": {
                "sample_rate": 8000,
                "VID": "CLIENT001",
                "immediate_detection": immediate
            }
        }
        await ws.send(json.dumps(config))

        # Load and send audio
        audio, sr = sf.read(audio_file)
        if sr != 8000:
            # Resample if needed
            pass

        # Convert to int16
        audio_int16 = (audio * 32767).astype(np.int16)

        # Send in chunks
        chunk_size = 8000  # 1 second
        for i in range(0, len(audio_int16), chunk_size):
            chunk = audio_int16[i:i+chunk_size].tobytes()
            await ws.send(chunk)

        # Send EOF
        await ws.send(json.dumps({"eof": 1}))

        # Receive result
        result = json.loads(await ws.recv())
        return result

# Usage
result_normal = asyncio.run(amd_detect("test.wav", immediate=False))
result_fast = asyncio.run(amd_detect("test.wav", immediate=True))

print(f"Normal: {result_normal}")
print(f"Fast: {result_fast}")

Node.js Client

const WebSocket = require('ws');
const fs = require('fs');

function amdDetect(audioFile, immediate = false) {
    return new Promise((resolve, reject) => {
        const ws = new WebSocket('ws://localhost:2700/');

        ws.on('open', () => {
            // Send config
            const config = {
                config: {
                    sample_rate: 8000,
                    VID: 'NODE001',
                    immediate_detection: immediate
                }
            };
            ws.send(JSON.stringify(config));

            // Send audio
            const audioBuffer = fs.readFileSync(audioFile);
            ws.send(audioBuffer);

            // Send EOF
            ws.send(JSON.stringify({eof: 1}));
        });

        ws.on('message', (data) => {
            const result = JSON.parse(data);
            resolve(result);
            ws.close();
        });

        ws.on('error', reject);
    });
}

// Usage
(async () => {
    const resultNormal = await amdDetect('test.wav', false);
    const resultFast = await amdDetect('test.wav', true);

    console.log('Normal:', resultNormal);
    console.log('Fast:', resultFast);
})();

Notes


Contact & Support

For issues or questions:


Changelog

2026-02-05:

2025-11-27: