added filter for asr

This commit is contained in:
rahulpscraftech360 2025-08-18 18:34:51 +05:30
parent 74d27bc84c
commit 46d8834a8a
8 changed files with 544 additions and 7 deletions

View file

@ -19,9 +19,9 @@ import opuslib
# --- Configuration ---
SERVER_IP = "64.227.170.31" # !!! 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 = "64.227.170.31" # MQTT gateway IP
MQTT_BROKER_HOST = "192.168.1.102" # MQTT gateway IP
MQTT_BROKER_PORT = 1883

View file

@ -19,14 +19,16 @@ from core.handle.receiveAudioHandle import startToChat
from core.handle.reportHandle import enqueue_asr_report
from core.utils.util import remove_punctuation_and_length
from core.handle.receiveAudioHandle import handleAudioMessage
from core.utils.asr_filter import ASRFilter
TAG = __name__
logger = setup_logging()
class ASRProviderBase(ABC):
def __init__(self):
pass
def __init__(self, config=None):
self.config = config
self.asr_filter = ASRFilter(config) if config else None
# Open audio channels
async def open_audio_channels(self, conn):
@ -189,6 +191,28 @@ class ASRProviderBase(ABC):
raw_text, file_path = results.get("asr", ("", None))
speaker_name = results.get("voiceprint", None)
# Apply ASR filtering if enabled
if self.asr_filter and raw_text:
# Prepare context for filtering
filter_context = {
'time_since_bot_utterance': time.time() - getattr(conn, 'last_bot_utterance_time', 0),
'expecting_response': getattr(conn, 'expecting_user_response', False),
'recent_filtered': getattr(conn, 'recent_filtered_texts', [])[-5:]
}
should_filter, reason = self.asr_filter.should_filter(raw_text, filter_context)
if should_filter:
logger.bind(tag=TAG).info(f"Filtered transcript: '{raw_text}' - Reason: {reason}")
# Track filtered texts
if not hasattr(conn, 'recent_filtered_texts'):
conn.recent_filtered_texts = []
conn.recent_filtered_texts.append(raw_text)
# Keep only last 10 filtered texts
conn.recent_filtered_texts = conn.recent_filtered_texts[-10:]
self.stop_ws_connection()
return
# Log recognition results
if raw_text:
logger.bind(tag=TAG).info(f"Recognized text: {raw_text}")

View file

@ -45,7 +45,7 @@ class CaptureOutput:
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
super().__init__(config)
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir")

View file

@ -0,0 +1,158 @@
from typing import Dict, List, Tuple, Optional
import re
from config.logger import setup_logging
from core.utils.asr_metrics import get_metrics
logger = setup_logging()
class ASRFilter:
"""
Context-aware ASR filtering system to reduce false positives
while preserving legitimate user input
"""
def __init__(self, config: Dict):
# Check if config has filtering directly (when passed from modules_initialize)
if 'filtering' in config:
self.config = config.get('filtering', {})
else:
# Fallback to ASR.filtering if available
self.config = config.get('ASR', {}).get('filtering', {})
self.enabled = self.config.get('enabled', True)
self.mode = self.config.get('mode', 'smart') # strict, smart, disabled
self.min_word_count = self.config.get('min_word_count', 2)
self.min_char_length = self.config.get('min_char_length', 3)
# Load filter lists
self.standalone_false_positives = self.config.get(
'standalone_false_positives',
["yeah", "so", "thanks", "okay", "um", "uh", "ah", "hmm", "oh"]
)
self.always_filter = self.config.get(
'always_filter',
["test test test", "one two three"]
)
# Context tracking
self.last_bot_utterance = ""
self.expecting_response = False
self.conversation_context = []
def should_filter(self, text: str, context: Optional[Dict] = None) -> Tuple[bool, str]:
"""
Determine if transcript should be filtered
Returns: (should_filter, reason)
"""
if not self.enabled or self.mode == 'disabled':
return False, "Filtering disabled"
# Clean and prepare text
original_text = text.strip()
cleaned_text = self._clean_text(text)
word_count = len(original_text.split())
# Determine if should filter
should_filter = False
reason = ""
# Always filter list
if any(pattern in cleaned_text for pattern in self.always_filter):
should_filter = True
reason = "Matches always-filter pattern"
# Mode-specific filtering
elif self.mode == 'strict':
should_filter, reason = self._strict_filter(cleaned_text, word_count)
else: # smart mode
should_filter, reason = self._smart_filter(cleaned_text, word_count, original_text, context)
# Track metrics
metrics = get_metrics()
metrics.record_transcript(original_text, should_filter, reason)
return should_filter, reason
def _clean_text(self, text: str) -> str:
"""Remove punctuation and normalize text"""
# Remove punctuation but keep spaces
cleaned = re.sub(r'[^\w\s]', '', text)
return cleaned.strip().lower()
def _strict_filter(self, text: str, word_count: int) -> Tuple[bool, str]:
"""Strict filtering mode"""
if len(text) < self.min_char_length:
return True, f"Too short ({len(text)} chars)"
if word_count < self.min_word_count:
return True, f"Too few words ({word_count})"
if text in self.standalone_false_positives:
return True, "Matches false positive list"
return False, "Passed strict filter"
def _smart_filter(self, text: str, word_count: int,
original: str, context: Optional[Dict]) -> Tuple[bool, str]:
"""Smart context-aware filtering"""
# Very short text
if len(text) < 2:
return True, "Single character or empty"
# Check if it's a response to a yes/no question
if context and context.get('expecting_response'):
if text in ['yes', 'no', 'yeah', 'nope', 'okay', 'sure']:
return False, "Valid response to question"
# Single word that's commonly a false positive
if word_count == 1 and text in self.standalone_false_positives:
# Check conversation context
if self._is_likely_noise(text, context):
return True, "Likely noise (single word, no context)"
# Multiple identical words (often noise)
words = text.split()
if len(set(words)) == 1 and len(words) > 2:
return True, "Repeated word pattern"
# Part of a longer phrase - usually legitimate
if word_count >= 3:
return False, "Part of longer phrase"
return False, "Passed smart filter"
def _is_likely_noise(self, text: str, context: Optional[Dict]) -> bool:
"""Determine if single word is likely noise based on context"""
if not context:
return True
# Check timing - if it comes immediately after bot stops speaking
time_since_bot = context.get('time_since_bot_utterance', float('inf'))
if time_since_bot < 0.5: # Within 500ms
return True
# Check if it matches recent pattern of noise
recent_filtered = context.get('recent_filtered', [])
if text in recent_filtered:
return True
return False
def update_context(self, key: str, value: any):
"""Update filtering context"""
if key == 'bot_utterance':
self.last_bot_utterance = value
self.expecting_response = self._is_question(value)
elif key == 'conversation':
self.conversation_context.append(value)
# Keep last 10 exchanges
self.conversation_context = self.conversation_context[-10:]
def _is_question(self, text: str) -> bool:
"""Check if bot utterance is a question"""
question_patterns = [
r'\?$', # Ends with ?
r'^(do|does|did|will|would|can|could|should|is|are|what|where|when|why|how)',
r'(right|correct|okay|yes or no)[\?\.]?$'
]
return any(re.search(pattern, text.lower()) for pattern in question_patterns)

View file

@ -0,0 +1,109 @@
import json
import os
from datetime import datetime
from collections import defaultdict
from typing import Dict, List, Any
from config.logger import setup_logging
logger = setup_logging()
class ASRMetrics:
"""Track ASR filtering effectiveness"""
def __init__(self):
self.metrics = {
'total_transcripts': 0,
'filtered_count': 0,
'filter_reasons': defaultdict(int),
'filtered_words': defaultdict(int),
'false_positive_rate': 0.0,
'session_start': datetime.now().isoformat()
}
def record_transcript(self, text: str, filtered: bool, reason: str = None):
"""Record a transcript and whether it was filtered"""
self.metrics['total_transcripts'] += 1
if filtered:
self.metrics['filtered_count'] += 1
if reason:
self.metrics['filter_reasons'][reason] += 1
# Track filtered words/phrases
self.metrics['filtered_words'][text.lower()] += 1
def calculate_stats(self):
"""Calculate filtering statistics"""
total = self.metrics['total_transcripts']
if total > 0:
self.metrics['false_positive_rate'] = (
self.metrics['filtered_count'] / total * 100
)
def get_summary(self) -> Dict[str, Any]:
"""Get current metrics summary"""
self.calculate_stats()
return {
'total_transcripts': self.metrics['total_transcripts'],
'filtered_count': self.metrics['filtered_count'],
'false_positive_rate': round(self.metrics['false_positive_rate'], 2),
'top_filter_reasons': dict(
sorted(self.metrics['filter_reasons'].items(),
key=lambda x: x[1], reverse=True)[:5]
),
'top_filtered_words': dict(
sorted(self.metrics['filtered_words'].items(),
key=lambda x: x[1], reverse=True)[:10]
)
}
def export_report(self, filepath: str = None):
"""Export metrics report to file"""
self.calculate_stats()
# Default filepath if not provided
if not filepath:
log_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs", "asr_metrics")
os.makedirs(log_dir, exist_ok=True)
filepath = os.path.join(log_dir, f"asr_metrics_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json")
report = {
'timestamp': datetime.now().isoformat(),
'session_start': self.metrics['session_start'],
'metrics': {
'total_transcripts': self.metrics['total_transcripts'],
'filtered_count': self.metrics['filtered_count'],
'false_positive_rate': round(self.metrics['false_positive_rate'], 2)
},
'filter_reasons': dict(self.metrics['filter_reasons']),
'top_filtered_words': dict(
sorted(self.metrics['filtered_words'].items(),
key=lambda x: x[1], reverse=True)[:20]
)
}
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
logger.info(f"ASR metrics report exported to {filepath}")
return filepath
def reset(self):
"""Reset all metrics"""
self.__init__()
# Global metrics instance
_global_metrics = None
def get_metrics() -> ASRMetrics:
"""Get global ASR metrics instance"""
global _global_metrics
if _global_metrics is None:
_global_metrics = ASRMetrics()
return _global_metrics
def reset_metrics():
"""Reset global metrics"""
global _global_metrics
if _global_metrics:
_global_metrics.reset()

View file

@ -128,9 +128,15 @@ def initialize_asr(config):
else config["ASR"][select_asr_module]["type"]
)
# Create module config with filtering settings
module_config = config["ASR"][select_asr_module].copy()
# Add ASR filtering config if available
if "filtering" in config["ASR"]:
module_config["filtering"] = config["ASR"]["filtering"]
new_asr = asr.create_instance(
asr_type,
config["ASR"][select_asr_module],
module_config,
str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
)

View file

@ -139,7 +139,7 @@ def write_json_file(file_path, data):
json.dump(data, file, ensure_ascii=False, indent=4)
def remove_punctuation_and_length(text):
def remove_punctuation_and_length(text, config=None, use_filter=True):
# Unicode ranges for full-width and half-width symbols
full_width_punctuations = (
"!"#$%&'()*+,-。/:;<=>?@[\]^_`{|}~"
@ -159,6 +159,16 @@ def remove_punctuation_and_length(text):
and char not in full_width_space
)
# Apply ASR filtering if enabled
if use_filter and config:
from core.utils.asr_filter import ASRFilter
asr_filter = ASRFilter(config)
should_filter, reason = asr_filter.should_filter(result)
if should_filter:
return 0, ""
# Legacy hardcoded filter (deprecated, but kept for compatibility)
if result == "Yeah":
return 0, ""

View file

@ -0,0 +1,230 @@
import pytest
import sys
import os
# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.utils.asr_filter import ASRFilter
from core.utils.asr_metrics import get_metrics, reset_metrics
class TestASRFilter:
@pytest.fixture(autouse=True)
def reset_global_metrics(self):
"""Reset global metrics before each test"""
reset_metrics()
@pytest.fixture
def smart_filter_config(self):
"""Config for smart mode filter"""
return {
'filtering': {
'enabled': True,
'mode': 'smart',
'min_word_count': 2,
'min_char_length': 3,
'standalone_false_positives': [
"yeah", "so", "thanks", "okay", "um", "uh", "ah", "hmm", "oh"
],
'always_filter': [
"test test test", "one two three"
]
}
}
@pytest.fixture
def strict_filter_config(self):
"""Config for strict mode filter"""
return {
'filtering': {
'enabled': True,
'mode': 'strict',
'min_word_count': 2,
'min_char_length': 3,
'standalone_false_positives': [
"yeah", "so", "thanks", "okay", "um", "uh", "ah", "hmm", "oh"
]
}
}
@pytest.fixture
def disabled_filter_config(self):
"""Config for disabled filter"""
return {
'filtering': {
'enabled': False
}
}
def test_filter_single_false_positive_smart_mode(self, smart_filter_config):
"""Test filtering single false positive words in smart mode"""
filter = ASRFilter(smart_filter_config)
# Should filter single false positives without context
should_filter, reason = filter.should_filter("yeah")
assert should_filter == True
assert "noise" in reason.lower()
should_filter, reason = filter.should_filter("um")
assert should_filter == True
def test_keep_legitimate_phrase_smart_mode(self, smart_filter_config):
"""Test keeping legitimate phrases in smart mode"""
filter = ASRFilter(smart_filter_config)
# Should keep longer phrases
should_filter, reason = filter.should_filter("Yeah, play some music")
assert should_filter == False
should_filter, reason = filter.should_filter("Thanks for helping me")
assert should_filter == False
def test_filter_always_filter_patterns(self, smart_filter_config):
"""Test filtering always-filter patterns"""
filter = ASRFilter(smart_filter_config)
should_filter, reason = filter.should_filter("test test test")
assert should_filter == True
assert "always-filter" in reason
should_filter, reason = filter.should_filter("one two three")
assert should_filter == True
def test_filter_repeated_words(self, smart_filter_config):
"""Test filtering repeated word patterns"""
filter = ASRFilter(smart_filter_config)
should_filter, reason = filter.should_filter("hello hello hello")
assert should_filter == True
assert "repeated" in reason.lower()
should_filter, reason = filter.should_filter("no no no no")
assert should_filter == True
def test_context_aware_filtering(self, smart_filter_config):
"""Test context-aware filtering for responses"""
filter = ASRFilter(smart_filter_config)
# Should keep yes/no responses when expecting response
context = {'expecting_response': True}
should_filter, reason = filter.should_filter("yes", context)
assert should_filter == False
assert "response to question" in reason.lower()
should_filter, reason = filter.should_filter("yeah", context)
assert should_filter == False
def test_strict_mode_filtering(self, strict_filter_config):
"""Test strict mode filtering"""
filter = ASRFilter(strict_filter_config)
# Should filter short text
should_filter, reason = filter.should_filter("hi")
assert should_filter == True
assert "chars" in reason
# Should filter single words
should_filter, reason = filter.should_filter("hello")
assert should_filter == True
assert "words" in reason
# Should keep longer phrases
should_filter, reason = filter.should_filter("hello world")
assert should_filter == False
def test_disabled_filter(self, disabled_filter_config):
"""Test disabled filter mode"""
filter = ASRFilter(disabled_filter_config)
# Should not filter anything
should_filter, reason = filter.should_filter("yeah")
assert should_filter == False
assert "disabled" in reason.lower()
should_filter, reason = filter.should_filter("test test test")
assert should_filter == False
def test_timing_based_filtering(self, smart_filter_config):
"""Test filtering based on timing after bot utterance"""
filter = ASRFilter(smart_filter_config)
# Should filter single words that come immediately after bot speaks
context = {
'time_since_bot_utterance': 0.3, # 300ms after bot
'expecting_response': False
}
should_filter, reason = filter.should_filter("yeah", context)
assert should_filter == True
# Should not filter if enough time has passed
context['time_since_bot_utterance'] = 2.0 # 2 seconds after bot
should_filter, reason = filter.should_filter("yeah", context)
assert should_filter == True # Still filtered as single word without context
def test_recent_filtered_pattern(self, smart_filter_config):
"""Test filtering based on recent filtered patterns"""
filter = ASRFilter(smart_filter_config)
# Should filter if word was recently filtered
context = {
'recent_filtered': ['yeah', 'um', 'ah']
}
should_filter, reason = filter.should_filter("yeah", context)
assert should_filter == True
def test_question_detection(self, smart_filter_config):
"""Test question detection for bot utterances"""
filter = ASRFilter(smart_filter_config)
filter.update_context('bot_utterance', "Do you want to play music?")
assert filter.expecting_response == True
filter.update_context('bot_utterance', "What is your name?")
assert filter.expecting_response == True
filter.update_context('bot_utterance', "I'm playing music for you.")
assert filter.expecting_response == False
def test_metrics_tracking(self, smart_filter_config):
"""Test that metrics are properly tracked"""
filter = ASRFilter(smart_filter_config)
metrics = get_metrics()
# Filter some transcripts
filter.should_filter("yeah")
filter.should_filter("Play some music please")
filter.should_filter("test test test")
# Check metrics
summary = metrics.get_summary()
assert summary['total_transcripts'] == 3
assert summary['filtered_count'] == 2
assert summary['false_positive_rate'] > 0
def test_edge_cases(self, smart_filter_config):
"""Test edge cases"""
filter = ASRFilter(smart_filter_config)
# Empty string
should_filter, reason = filter.should_filter("")
assert should_filter == True
# Very short text
should_filter, reason = filter.should_filter("a")
assert should_filter == True
# Punctuation only
should_filter, reason = filter.should_filter("...")
assert should_filter == True
# Mixed case
should_filter, reason = filter.should_filter("YeAh")
assert should_filter == True
# With punctuation
should_filter, reason = filter.should_filter("yeah!")
assert should_filter == True
if __name__ == "__main__":
pytest.main([__file__, "-v"])