Last Updated: 2026-02-05 Server: asr_server.py Version: Multi-stage cascade with 24K/58 models
Endpoint: ws://{host}:{port}/
Default Ports:
27002710 (port + 10)2720 (port + 20)Example:
const ws = new WebSocket('ws://localhost:2700/');
Required at connection start.
{
"config": {
"sample_rate": 8000,
"VID": "V1234567890123456789",
"phone": "15551234567",
"country_code": "1"
}
}
Parameters:
sample_rate (integer): Audio sample rate in Hz
(default: 8000)VID (string): Voice ID for tracking/loggingphone (string, optional): Client phone numbercountry_code (string, optional): Country codeNew Parameter (for immediate detection):
immediate_detection (boolean): If true,
return detection at first confident stage without cascadeSend 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)
Signal end of audio stream:
{"eof": 1}
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:
classification (string): "AMD" or
"HUMAN"amd_conf (float): AMD confidence (0.0 - 1.0)human_conf (float): HUMAN confidence (0.0 - 1.0)greeting_class (string, optional): Greeting type if AMD
detectedgreeting_conf (float, optional): Greeting
classification confidencemodel_history (string): Cascade execution trace
(format: stage:class:amd:human:exit)Model History Format:
4k:HUMAN:0.10:0.90:1;8k:HUMAN:0.15:0.85:1;24k:AMD:0.92:0.08:0
4k, 8k,
16k, 24k, 32k)AMD or HUMAN)1 = exited, 0 = continued
to next stage)Current Implementation (Default):
The server runs a multi-stage cascade:
Code Location:
/usr/src/asr_server_new/asr_server.py lines ~1800-2200
Connection Errors:
1000: Normal closure1001: Going away (server shutdown)1006: Abnormal closure (network/proxy issue)1011: Internal server errorEndpoint:
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:
status: ok or errorcpu_percent: Current CPU usage (0-100)avg_proc_ms: Average processing time in
millisecondsdisconnect_rate: Abnormal disconnect rate (0-100)current_rps: Requests per second (last minute)current_cps: Connections per second (last minute)total_requests: Total requests since server starttotal_connections: Total connections since server
startload_factor: Combined load score (0-100, higher = more
loaded)haproxy_weight: Recommended HAProxy weight (1-100,
higher = more capacity)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)
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:
ready <weight>%: Server is ready, use specified
weightup <weight>%: Server is up, use specified
weightdown: Server is down, remove from poolmaint: Server is in maintenanceWeight 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
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.
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.
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)
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)
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).
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};"
No changes needed - response format remains the same.
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())
Without immediate_detection
(default):
With immediate_detection=true:
Latency Reduction:
Accuracy Impact:
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)
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}")
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);
})();
For issues or questions:
/tmp/asr_server.log or
/var/log/amd/http://localhost:2710/healths in server console2026-02-05:
2025-11-27: