fixed sending noice

This commit is contained in:
rahulpscraftech360 2025-08-18 12:29:25 +05:30
parent 79474fb875
commit 0fe4c2d0b3
6 changed files with 187 additions and 10 deletions

View file

@ -19,9 +19,9 @@ import opuslib
# --- Configuration ---
SERVER_IP = "192.168.1.106" # !!! UPDATE with your server's local IP address !!!
SERVER_IP = "192.168.1.102" # !!! UPDATE with your server's local IP address !!!
OTA_PORT = 8003
MQTT_BROKER_HOST = "192.168.1.106" # MQTT gateway IP
MQTT_BROKER_HOST = "192.168.1.102" # MQTT gateway IP
MQTT_BROKER_PORT = 1883

View file

@ -1078,6 +1078,21 @@ class ConnectionHandler:
# Clear pre-buffer when resetting VAD states
if hasattr(self, 'audio_pre_buffer'):
self.audio_pre_buffer.clear()
# Clear ASR audio buffer to prevent processing leftover audio
if hasattr(self, 'asr_audio'):
self.asr_audio.clear()
# Clear ASR audio queue for this specific connection only
if hasattr(self, 'asr_audio_queue'):
# Empty the queue by getting all items without blocking
cleared_count = 0
while not self.asr_audio_queue.empty():
try:
self.asr_audio_queue.get_nowait()
cleared_count += 1
except queue.Empty:
break
if cleared_count > 0:
self.logger.bind(tag=TAG).debug(f"Cleared {cleared_count} audio chunks from ASR queue")
self.logger.bind(tag=TAG).debug("VAD states reset.")
def chat_and_close(self, text):

View file

@ -38,6 +38,10 @@ async def handleTextMessage(conn, message):
f"Client audio capture mode: {conn.client_listen_mode}"
)
if msg_json["state"] == "start":
# Reset VAD states to clear any leftover audio from previous session
conn.reset_vad_states()
# Mark that we just started listening to prevent processing stale audio
conn.just_started_listening = True
# Add initial connection flag to prevent false positive on first audio
if not hasattr(conn, "initial_connection_handled"):
conn.initial_connection_handled = False

View file

@ -10,6 +10,8 @@ import json
import io
import time
import concurrent.futures
import csv
from datetime import datetime
from abc import ABC, abstractmethod
from config.logger import setup_logging
from typing import Optional, Tuple, List, Dict, Any
@ -63,6 +65,9 @@ class ASRProviderBase(ABC):
# If voice is detected and we're not already collecting
if have_voice and not conn.client_have_voice:
# Clear the just_started_listening flag when actual voice is detected
if hasattr(conn, 'just_started_listening'):
conn.just_started_listening = False
# Add pre-buffered audio to the beginning of ASR audio
conn.asr_audio = list(conn.audio_pre_buffer) + conn.asr_audio
conn.audio_pre_buffer.clear()
@ -73,11 +78,20 @@ class ASRProviderBase(ABC):
return
if conn.client_voice_stop:
# Check if we just started listening - if so, skip this audio
if hasattr(conn, 'just_started_listening') and conn.just_started_listening:
logger.bind(tag=TAG).debug("Skipping stale audio chunks after listen start")
conn.just_started_listening = False
conn.asr_audio.clear()
conn.reset_vad_states()
return
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
conn.reset_vad_states()
if len(asr_audio_task) > 20: # Increased from 15 to 20 chunks (1.2 seconds)
logger.bind(tag=TAG).debug(f"Processing {len(asr_audio_task)} audio chunks")
await self.handle_voice_stop(conn, asr_audio_task)
# Handle voice stop
@ -253,6 +267,76 @@ class ASRProviderBase(ABC):
return file_path
def log_audio_transcript(self, file_path: str, audio_length_seconds: float, transcript: str):
"""Log audio file information to CSV file"""
try:
# Create logs directory at the same level as output_dir
log_dir = os.path.join(os.path.dirname(self.output_dir), "asr_logs")
os.makedirs(log_dir, exist_ok=True)
# Create both CSV and JSON log files for easy inspection
csv_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.csv")
json_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.json")
# Write to CSV file
csv_exists = os.path.exists(csv_log_file)
with open(csv_log_file, 'a', newline='', encoding='utf-8') as csvfile:
fieldnames = ['timestamp', 'filename', 'file_path', 'audio_length_seconds', 'transcript']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not csv_exists:
writer.writeheader()
writer.writerow({
'timestamp': datetime.now().isoformat(),
'filename': os.path.basename(file_path),
'file_path': file_path,
'audio_length_seconds': round(audio_length_seconds, 2),
'transcript': transcript
})
# Also write to JSON file for easier parsing
log_entry = {
'timestamp': datetime.now().isoformat(),
'filename': os.path.basename(file_path),
'file_path': file_path,
'audio_length_seconds': round(audio_length_seconds, 2),
'transcript': transcript
}
# Read existing JSON logs or create new list
json_logs = []
if os.path.exists(json_log_file):
try:
with open(json_log_file, 'r', encoding='utf-8') as f:
json_logs = json.load(f)
except:
json_logs = []
json_logs.append(log_entry)
# Write updated JSON logs
with open(json_log_file, 'w', encoding='utf-8') as f:
json.dump(json_logs, f, ensure_ascii=False, indent=2)
# Also create a simple text log for quick inspection
txt_log_file = os.path.join(log_dir, f"asr_log_{datetime.now().strftime('%Y%m%d')}.txt")
with open(txt_log_file, 'a', encoding='utf-8') as f:
f.write(f"\n{'='*80}\n")
f.write(f"Timestamp: {datetime.now().isoformat()}\n")
f.write(f"Filename: {os.path.basename(file_path)}\n")
f.write(f"Full Path: {file_path}\n")
f.write(f"Audio Length: {audio_length_seconds:.2f} seconds\n")
f.write(f"Transcript: {transcript}\n")
f.write(f"{'='*80}\n")
logger.bind(tag=TAG).info(
f"Logged ASR transcript to {log_dir} - File: {os.path.basename(file_path)}, "
f"Length: {audio_length_seconds:.2f}s, Transcript: {transcript[:50]}..."
)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to log audio transcript: {e}")
@abstractmethod
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"

View file

@ -354,6 +354,15 @@ class ASRProvider(ASRProviderBase):
f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
# Calculate audio length from WAV file
with wave.open(file_path, 'rb') as wav_file:
frames = wav_file.getnframes()
rate = wav_file.getframerate()
audio_length_seconds = frames / float(rate)
# Log the transcript information
self.log_audio_transcript(file_path, audio_length_seconds, text)
return text, file_path
except Exception as e:
@ -361,12 +370,15 @@ class ASRProvider(ASRProviderBase):
f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
# File cleanup logic
# File cleanup logic - DISABLED to preserve audio files
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
logger.bind(tag=TAG).debug(
f"Deleted temporary audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(
f"File deletion failed: {file_path} | Error: {e}")
logger.bind(tag=TAG).info(
f"Audio file preserved (deletion disabled): {file_path}")
# Commented out deletion code to preserve audio files
# try:
# os.remove(file_path)
# logger.bind(tag=TAG).debug(
# f"Deleted temporary audio file: {file_path}")
# except Exception as e:
# logger.bind(tag=TAG).error(
# f"File deletion failed: {file_path} | Error: {e}")

View file

@ -0,0 +1,62 @@
# VAD Noise Detection Debug Guide
## Current Issue
The VAD (Voice Activity Detection) is picking up background noise and sending it to ASR, resulting in improper transcripts like "HE" when nothing was said.
## Current Settings (SileroVAD)
- threshold: 0.5
- threshold_low: 0.2
- min_silence_duration_ms: 1000
- frame_window_threshold: 3
## Recommendations to Reduce Noise Sensitivity
### 1. Increase VAD Thresholds
Edit `config.yaml` and try these settings:
```yaml
VAD:
SileroVAD:
type: silero
threshold: 0.5 # Increased from 0.5
threshold_low: 0.2 # Increased from 0.2
model_dir: models/snakers4_silero-vad
min_silence_duration_ms: 1000
frame_window_threshold: 3 # Increased from 3
```
### 2. Alternative: Try TenVAD_ONNX with Higher Thresholds
```yaml
selected_module:
VAD: TenVAD_ONNX # Change from SileroVAD
VAD:
TenVAD_ONNX:
type: ten_vad_onnx
model_path: models/ten-vad-onnx
sample_rate: 16000
hop_size: 256
frame_size: 512
threshold: 0.7 # Higher threshold for noisy environments
threshold_low: 0.4 # Higher low threshold
min_silence_duration_ms: 1000
frame_window_threshold: 5 # More frames needed to confirm voice
```
### 3. Monitor Audio Files
The ASR logs are now saved in:
- CSV: `asr_logs/asr_log_YYYYMMDD.csv`
- JSON: `asr_logs/asr_log_YYYYMMDD.json`
- Text: `asr_logs/asr_log_YYYYMMDD.txt`
Check these logs to see:
- Audio length (now correctly calculated from WAV file)
- Transcript content
- File paths for manual inspection
### 4. Audio Length Fix
The audio length is now correctly calculated from the WAV file metadata instead of PCM data estimation.
### 5. Debug Information Added
- Number of audio chunks is now logged before processing
- Audio files are preserved (not deleted) for inspection