import os
import numpy as np
import torch
import wave
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from collections import deque
import librosa
import time
import threading
# Constants
INPUT_SAMPLE_RATE = 48000
VAD_SAMPLE_RATE = 16000
CHANNELS = 1
CHUNK_SIZE = 512 # 60 ms at 16 kHz
UPLOAD_FOLDER = 'audio_files'
TEMP_AUDIO_FOLDER = 'test_audio_temp'
PROCESSED_AUDIO_FOLDER = 'processed_audio_chunks'
PROCESSING_INTERVAL = 0.1 # 100 ms
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['TEMP_AUDIO_FOLDER'] = TEMP_AUDIO_FOLDER
app.config['PROCESSED_AUDIO_FOLDER'] = PROCESSED_AUDIO_FOLDER
socketio = SocketIO(app, async_mode='threading')
# Device selection (CPU or GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Initialize Silero VAD
vad_model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad',
model='silero_vad',
force_reload=True)
vad_model = vad_model.to(device)
vad_model.eval()
# Global variables
audio_buffer = deque(maxlen=CHUNK_SIZE)
speech_detected = False
previous_speech_detected = False
last_processed_time = 0
processing_lock = threading.Lock()
# Buffer to store all audio chunks for testing
processed_audio_chunks = []
def ensure_folder_exists(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def int2float(sound):
abs_max = np.abs(sound).max()
sound = sound.astype('float32')
if abs_max > 0:
sound *= 1 / 32768
sound = sound.squeeze()
return sound
def save_audio_chunk_to_file(audio_chunk, folder, filename):
file_path = os.path.join(folder, filename)
int_data = np.int16(audio_chunk * 32767)
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(VAD_SAMPLE_RATE)
wf.writeframes(int_data.tobytes())
print(f"Saved chunk to {file_path}")
def save_processed_audio_chunks():
print(f"---save_processed_audio_chunks")
global processed_audio_chunks
if processed_audio_chunks:
filename = f'processed_chunks_{int(time.time())}.wav'
file_path = os.path.join(app.config['PROCESSED_AUDIO_FOLDER'], filename)
# Concatenate all chunks
all_chunks = np.concatenate(processed_audio_chunks)
int_data = np.int16(all_chunks * 32767)
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(VAD_SAMPLE_RATE)
wf.writeframes(int_data.tobytes())
print(f"Processed audio saved to {file_path}")
processed_audio_chunks.clear()
else:
print("No processed audio chunks to save.")
def detect_speech(audio_chunk):
global speech_detected, vad_model, device, processed_audio_chunks
# Convert to float
audio_float32 = int2float(audio_chunk)
# Save the chunk for debugging
save_audio_chunk_to_file(audio_float32, app.config['TEMP_AUDIO_FOLDER'], f'vad_input_{int(time.time())}.wav')
# Store the chunk in the processed audio buffer
processed_audio_chunks.append(audio_float32)
try:
with torch.no_grad():
tensor = torch.from_numpy(audio_float32).to(device).unsqueeze(0)
speech_prob = vad_model(tensor, VAD_SAMPLE_RATE).item()
print(f"speech_prob = {speech_prob}")
except RuntimeError as e:
if "out of memory" in str(e):
print("CUDA out of memory. Falling back to CPU.")
torch.cuda.empty_cache()
device = torch.device('cpu')
vad_model = vad_model.to(device)
tensor = torch.from_numpy(audio_float32).to(device).unsqueeze(0)
speech_prob = vad_model(tensor, VAD_SAMPLE_RATE).item()
else:
raise e
speech_detected = speech_prob > 0.5
return speech_detected
@app.route('/')
def index():
return render_template('index.html')
@app.route('/save_processed_audio', methods=['POST'])
def save_processed_audio():
save_processed_audio_chunks()
return "Processed audio saved."
def process_audio_buffer():
global audio_buffer, speech_detected, previous_speech_detected, last_processed_time
with processing_lock:
current_time = time.time()
if current_time - last_processed_time < PROCESSING_INTERVAL:
return
if len(audio_buffer) == CHUNK_SIZE:
audio_data = np.array(list(audio_buffer))
is_speech = detect_speech(audio_data)
if is_speech != previous_speech_detected:
print(f"SWITCH TO: {is_speech}")
socketio.emit('speech_status', {'is_speech': is_speech})
previous_speech_detected = is_speech
# Clear the buffer after processing
audio_buffer.clear()
last_processed_time = current_time
@socketio.on('audio_data')
def handle_audio_data(data):
global audio_buffer
audio_chunk = np.frombuffer(data, dtype=np.float32)
if audio_chunk.ndim > 1:
audio_chunk = np.mean(audio_chunk, axis=1)
# Resample to 16 kHz
resampled_chunk = librosa.resample(audio_chunk, orig_sr=INPUT_SAMPLE_RATE, target_sr=VAD_SAMPLE_RATE)
# Add resampled data to buffer
audio_buffer.extend(resampled_chunk)
# Process audio in a separate thread to avoid blocking
threading.Thread(target=process_audio_buffer).start()
@socketio.on('stop_recording')
def handle_stop_recording():
save_processed_audio_chunks()
global audio_buffer
if audio_buffer:
save_audio_to_file(list(audio_buffer))
audio_buffer.clear()
def save_audio_to_file(audio_data):
filename = f'recording_{int(time.time())}.wav'
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
int_data = np.int16(np.array(audio_data) * 32767)
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(VAD_SAMPLE_RATE)
wf.writeframes(int_data.tobytes())
print(f"Audio saved to {file_path}")
if __name__ == '__main__':
ensure_folder_exists(app.config['UPLOAD_FOLDER'])
ensure_folder_exists(app.config['TEMP_AUDIO_FOLDER'])
ensure_folder_exists(app.config['PROCESSED_AUDIO_FOLDER'])
socketio.run(app, debug=True, host='0.0.0.0', port=8081, allow_unsafe_werkzeug=True)
audio_handler.py
py
import wave
import os
import numpy as np
from pydub import AudioSegment
audio_data = []
def save_audio(data):
global audio_data
audio_data.append(np.frombuffer(data, dtype=np.int16))
def finalize_audio():
global audio_data
if audio_data:
audio_array = np.concatenate(audio_data)
audio_segment = AudioSegment(
audio_array.tobytes(),
frame_rate=44100,
sample_width=2,
channels=1
)
output_path = os.path.join('static', 'output.wav')
audio_segment.export(output_path, format="wav")
audio_data = []
return output_path
return None
main.py
py
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
Это мой проект для создания ConversationalAI.
Сейчас проблема с VAD. В момент речи очень большая задержка на определении VAD и сохранение.
Можешь полностью пересмотреть способ доставки чанков на сервер и определение там VAD.
Главное: VAD работает только с фиксированной длиной чанка, а также с фиксированной частотой. Это не меняй.
To address the high latency in your Voice Activity Detection (VAD) process and optimize the delivery and handling of audio chunks, we'll need to make several improvements to both the server-side and client-side components of your Conversational AI project. Below, I'll outline the key optimizations along with updated code snippets to help you achieve lower latency and more efficient processing.
Overview of Optimizations
Faster Resampling: Replace librosa resampling with a more efficient method.
Avoid Blocking Operations: Remove or make optional the disk I/O for debugging to prevent delays.
Efficient Thread Management: Use a dedicated worker thread with a queue for processing audio chunks instead of spawning a new thread for each chunk.
Optimize Flask-SocketIO Configuration: Use an asynchronous worker model like eventlet for better concurrency.
Streamline VAD Processing: Ensure the VAD model processes data as quickly as possible, leveraging GPU acceleration if available.
Let's go through each of these optimizations in detail.
1. Faster Resampling
Issue: librosa.resample is known to be slower compared to other resampling methods, which can introduce latency.
Solution: Use scipy.signal.resample_poly for faster resampling.
Updated app.py
python
import os
import numpy as np
import torch
import wave
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from collections import deque
import time
import threading
from scipy.signal import resample_poly # Faster resampling
from queue import Queue
# Constants
INPUT_SAMPLE_RATE = 48000
VAD_SAMPLE_RATE = 16000
CHANNELS = 1
CHUNK_SIZE = 512 # 60 ms at 16 kHz
UPLOAD_FOLDER = 'audio_files'
TEMP_AUDIO_FOLDER = 'test_audio_temp'
PROCESSED_AUDIO_FOLDER = 'processed_audio_chunks'
PROCESSING_INTERVAL = 0.05 # 50 ms for increased responsiveness
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['TEMP_AUDIO_FOLDER'] = TEMP_AUDIO_FOLDER
app.config['PROCESSED_AUDIO_FOLDER'] = PROCESSED_AUDIO_FOLDER
# Use eventlet for better concurrency
socketio = SocketIO(app, async_mode='eventlet', cors_allowed_origins="*")
# Device selection (CPU or GPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Initialize Silero VAD
vad_model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad',
model='silero_vad',
force_reload=True)
vad_model = vad_model.to(device)
vad_model.eval()
# Global variables
audio_buffer = deque()
processing_queue = Queue()
speech_detected = False
previous_speech_detected = False
last_processed_time = 0
processing_lock = threading.Lock()
# Buffer to store all audio chunks for testing
processed_audio_chunks = []
def ensure_folder_exists(folder):
if not os.path.exists(folder):
os.makedirs(folder)
def int2float(sound):
abs_max = np.abs(sound).max()
sound = sound.astype('float32')
if abs_max > 0:
sound *= 1 / 32768
sound = sound.squeeze()
return sound
def save_audio_chunk_to_file(audio_chunk, folder, filename):
file_path = os.path.join(folder, filename)
int_data = np.int16(audio_chunk * 32767)
os.makedirs(folder, exist_ok=True)
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(VAD_SAMPLE_RATE)
wf.writeframes(int_data.tobytes())
print(f"Saved chunk to {file_path}")
def save_processed_audio_chunks():
global processed_audio_chunks
if processed_audio_chunks:
filename = f'processed_chunks_{int(time.time())}.wav'
file_path = os.path.join(app.config['PROCESSED_AUDIO_FOLDER'], filename)
# Concatenate all chunks
all_chunks = np.concatenate(processed_audio_chunks)
int_data = np.int16(all_chunks * 32767)
os.makedirs(app.config['PROCESSED_AUDIO_FOLDER'], exist_ok=True)
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(VAD_SAMPLE_RATE)
wf.writeframes(int_data.tobytes())
print(f"Processed audio saved to {file_path}")
processed_audio_chunks.clear()
else:
print("No processed audio chunks to save.")
def detect_speech(audio_chunk):
global speech_detected, vad_model, device, processed_audio_chunks
# Convert to float
audio_float32 = int2float(audio_chunk)
# Optionally save the chunk for debugging
# Uncomment the following line if you need to save chunks
# save_audio_chunk_to_file(audio_float32, app.config['TEMP_AUDIO_FOLDER'], f'vad_input_{int(time.time())}.wav')
# Store the chunk in the processed audio buffer
processed_audio_chunks.append(audio_float32)
try:
with torch.no_grad():
tensor = torch.from_numpy(audio_float32).to(device).unsqueeze(0)
speech_prob = vad_model(tensor, VAD_SAMPLE_RATE).item()
print(f"speech_prob = {speech_prob}")
except RuntimeError as e:
if "out of memory" in str(e):
print("CUDA out of memory. Falling back to CPU.")
torch.cuda.empty_cache()
device = torch.device('cpu')
vad_model = vad_model.to(device)
tensor = torch.from_numpy(audio_float32).to(device).unsqueeze(0)
speech_prob = vad_model(tensor, VAD_SAMPLE_RATE).item()
else:
raise e
speech_detected = speech_prob > 0.5
return speech_detected
def audio_processing_worker():
global audio_buffer, speech_detected, previous_speech_detected, last_processed_time
while True:
audio_chunk = processing_queue.get()
if audio_chunk is None:
break
current_time = time.time()
with processing_lock:
if current_time - last_processed_time < PROCESSING_INTERVAL:
# Not enough time has passed; requeue and wait
processing_queue.put(audio_chunk)
time.sleep(PROCESSING_INTERVAL - (current_time - last_processed_time))
continue
is_speech = detect_speech(audio_chunk)
if is_speech != previous_speech_detected:
print(f"SWITCH TO: {is_speech}")
socketio.emit('speech_status', {'is_speech': is_speech})
previous_speech_detected = is_speech
last_processed_time = current_time
processing_queue.task_done()
# Start audio processing worker thread
processing_thread = threading.Thread(target=audio_processing_worker, daemon=True)
processing_thread.start()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/save_processed_audio', methods=['POST'])
def save_processed_audio():
save_processed_audio_chunks()
return "Processed audio saved."
@socketio.on('audio_data')
def handle_audio_data(data):
# Assuming data is sent as ArrayBuffer
audio_chunk = np.frombuffer(data, dtype=np.float32)
if audio_chunk.ndim > 1:
audio_chunk = np.mean(audio_chunk, axis=1)
# Resample to 16 kHz using resample_poly for faster resampling
resampled_chunk = resample_poly(audio_chunk, VAD_SAMPLE_RATE, INPUT_SAMPLE_RATE)
processing_queue.put(resampled_chunk)
@socketio.on('stop_recording')
def handle_stop_recording():
save_processed_audio_chunks()
# No need to save buffer here since we are processing via queue
def save_audio_to_file(audio_data):
filename = f'recording_{int(time.time())}.wav'
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
int_data = np.int16(np.array(audio_data) * 32767)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
with wave.open(file_path, 'wb') as wf:
wf.setnchannels(CHANNELS)
wf.setsampwidth(2)
wf.setframerate(VAD_SAMPLE_RATE)
wf.writeframes(int_data.tobytes())
print(f"Audio saved to {file_path}")
if __name__ == '__main__':
ensure_folder_exists(app.config['UPLOAD_FOLDER'])
ensure_folder_exists(app.config['TEMP_AUDIO_FOLDER'])
ensure_folder_exists(app.config['PROCESSED_AUDIO_FOLDER'])
socketio.run(app, debug=True, host='0.0.0.0', port=8081)
Explanation of Changes
Faster Resampling:
Replaced librosa.resample with scipy.signal.resample_poly, which is significantly faster and more suitable for real-time applications.
Implemented a dedicated worker thread that continuously processes audio chunks from a Queue. This avoids the overhead of creating a new thread for each incoming audio chunk.
The worker thread uses a PROCESSING_INTERVAL of 50 ms to increase responsiveness.
Switched the async_mode to 'eventlet' for better concurrency handling.
Ensure that eventlet is installed in your environment:
bash
pip install eventlet
Adjusted the socketio initialization accordingly.
2. Client-Side Optimizations
While the primary optimizations are server-side, ensuring efficient client-side audio capture and transmission can further reduce latency.
Updated static/js/script.js
javascript
let isRecording = false;
let audioContext;
let socket;
let analyser;
let dataArray;
const voiceButton = document.getElementById('voice-button');
const voiceDetectPoint = document.querySelector('.voice-detect-point');
voiceButton.addEventListener('click', toggleRecording);
function initSocket() {
socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
// Handler for speech status
socket.on('speech_status', function(data) {
if (data.is_speech) {
voiceDetectPoint.style.opacity = '1';
} else {
voiceDetectPoint.style.opacity = '0';
}
});
}
async function toggleRecording() {
if (!isRecording) {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
startRecording(stream);
} catch (err) {
console.error('Error accessing the microphone:', err);
}
} else {
stopRecording();
}
}
async function startRecording(stream) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
await audioContext.audioWorklet.addModule('/static/js/worklet.js');
const source = audioContext.createMediaStreamSource(stream);
// Create an analyser node
analyser = audioContext.createAnalyser();
analyser.fftSize = 256;
const bufferLength = analyser.frequencyBinCount;
dataArray = new Uint8Array(bufferLength);
const audioWorkletNode = new AudioWorkletNode(audioContext, 'audio-processor');
source.connect(audioWorkletNode);
source.connect(analyser);
audioWorkletNode.port.onmessage = (event) => {
if (!isRecording) return;
const buf = new Float32Array(event.data);
socket.emit('audio_data', buf.buffer);
};
isRecording = true;
voiceButton.classList.add('listening');
// Disable transition during recording for smoother animation
voiceButton.style.transition = 'none';
updateButtonSize();
}
function stopRecording() {
isRecording = false;
voiceButton.classList.remove('listening');
if (audioContext) {
audioContext.close();
}
socket.emit('stop_recording');
}
function updateButtonSize() {
if (!isRecording) return;
analyser.getByteFrequencyData(dataArray);
const average = dataArray.reduce((acc, val) => acc + val, 0) / dataArray.length;
const volume = average / 255; // Normalize to 0-1 range
// Scale button size based on volume (min 100px, max 200px)
const size = 130 + ((volume * 100) * 2.5);
voiceButton.style.width = `${size}px`;
voiceButton.style.height = `${size}px`;
requestAnimationFrame(updateButtonSize);
}
document.addEventListener('DOMContentLoaded', initSocket);
Explanation of Changes
Avoid Redundant Code:
Removed duplicated code within the speech_status handler.
Smooth Animation:
Ensured that button size updates are smooth by disabling transitions only during recording.
3. Optimize Audio Worklet
Ensure that the Audio Worklet is optimized to send only necessary data.
Updated static/js/worklet.js
javascript
class AudioProcessor extends AudioWorkletProcessor {
process(inputs, outputs, parameters) {
const input = inputs[0];
const output = outputs[0];
for (let channel = 0; channel < input.length; ++channel) {
const inputChannel = input[channel];
const outputChannel = output[channel];
for (let i = 0; i < inputChannel.length; ++i) {
outputChannel[i] = inputChannel[i];
}
}
// Send downsampled data to main thread
// Assuming the server expects float32 data
this.port.postMessage(input[0].buffer);
return true;
}
}
registerProcessor('audio-processor', AudioProcessor);
Explanation of Changes
Efficient Data Transmission:
Sent only the necessary buffer (input[0].buffer) to the main thread without unnecessary conversions.
4. Optional: Asynchronous File Saving
If you still need to save audio chunks for debugging without blocking the main processing, handle file I/O asynchronously.
Example Using a Separate Thread for File Saving
python
import queue
# Add a queue for file saving
file_saving_queue = Queue()
def file_saving_worker():
while True:
task = file_saving_queue.get()
if task is None:
break
audio_chunk, folder, filename = task
save_audio_chunk_to_file(audio_chunk, folder, filename)
file_saving_queue.task_done()
# Start file saving worker thread
file_saving_thread = threading.Thread(target=file_saving_worker, daemon=True)
file_saving_thread.start()
def detect_speech(audio_chunk):
global speech_detected, vad_model, device, processed_audio_chunks
# Convert to float
audio_float32 = int2float(audio_chunk)
# Enqueue file saving task for debugging
# Uncomment the following line if you need to save chunks
# file_saving_queue.put((audio_float32, app.config['TEMP_AUDIO_FOLDER'], f'vad_input_{int(time.time())}.wav'))
# Store the chunk in the processed audio buffer
processed_audio_chunks.append(audio_float32)
try:
with torch.no_grad():
tensor = torch.from_numpy(audio_float32).to(device).unsqueeze(0)
speech_prob = vad_model(tensor, VAD_SAMPLE_RATE).item()
print(f"speech_prob = {speech_prob}")
except RuntimeError as e:
if "out of memory" in str(e):
print("CUDA out of memory. Falling back to CPU.")
torch.cuda.empty_cache()
device = torch.device('cpu')
vad_model = vad_model.to(device)
tensor = torch.from_numpy(audio_float32).to(device).unsqueeze(0)
speech_prob = vad_model(tensor, VAD_SAMPLE_RATE).item()
else:
raise e
speech_detected = speech_prob > 0.5
return speech_detected
Explanation of Changes
Asynchronous File I/O:
Introduced a separate file_saving_queue and file_saving_worker thread to handle file saving without blocking the main processing thread.
You can enqueue file-saving tasks as needed, keeping the main processing flow uninterrupted.
5. Additional Recommendations
Profile Your Application:
Use profiling tools like cProfile or line_profiler to identify other potential bottlenecks in your application.
Optimize the VAD Model:
Ensure that the Silero VAD model is optimized for inference. Consider using a lighter model or employing techniques like model quantization if applicable.
Leverage GPU Acceleration:
If you're not already using GPU acceleration, ensure that your server's GPU is utilized efficiently to speed up VAD processing.
Handle Network Latency:
Ensure that the network connection between the client and server is stable and has low latency, as this can also impact the overall responsiveness.
Monitor Resource Usage:
Keep an eye on CPU, GPU, and memory usage to ensure that your server has sufficient resources to handle real-time audio processing.
Conclusion
By implementing the above optimizations, you should experience a significant reduction in latency during VAD processing in your Conversational AI project. The key changes focus on efficient resampling, avoiding blocking operations, proper thread management, and leveraging asynchronous processing capabilities provided by frameworks like eventlet. Always ensure to test each change thoroughly to validate performance improvements and maintain the stability of your application.
If you encounter further issues or need more specific assistance, feel free to ask!