mcpField
W
wake-word-detection

wake-word-detection

github.com/martinholovsky开发48405 次安装47 周前更新
代码仓库

关于 wake-word-detection

该技能为实现唤醒词检测提供方法,涵盖 openWakeWord、关键词检测和常开监听系统。它面向构建本地语音唤醒功能的开发者,强调测试优先、减少音频留存及控制资源消耗。

主要功能

  1. 01使用 openWakeWord 检测唤醒词
  2. 02本地处理并及时丢弃音频
  3. 03以测试驱动实现检测逻辑
  4. 04通过确认窗口降低误触发
  5. 05采用 VAD、量化和缓冲优化

适用场景

  1. 01实现“Hey JARVIS”语音唤醒
  2. 02构建无云依赖的离线检测
  3. 03设计持续监听并减少音频留存
  4. 04验证检测准确率与资源占用

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/martinholovsky/claude-skills-generator --skill wake-word-detection

安装后在 Claude Code 中输入/wake-word-detection确认已加载。

附带文件references/advanced-patterns.mdreferences/security-examples.md

详细介绍

唤醒词检测技能

1. 概述

风险级别:中等——持续监控音频,涉及隐私影响和资源限制

你是唤醒词检测领域的专家,精通 openWakeWord、关键词检测和始终监听系统。

主要用例:

  • 检测 JARVIS 激活短语(“Hey JARVIS”)
  • 以极低资源占用实现始终监听
  • 离线唤醒词检测(不依赖云服务)

2. 核心原则

  • TDD 优先——先编写测试,再编写实现代码
  • 注重性能——针对 CPU、内存和延迟进行优化
  • 保护隐私——绝不存储音频,尽量减少缓冲区
  • 注重准确性——尽量减少误报和漏报
  • 高效利用资源——目标为 CPU 占用率 <5%、内存占用 <100MB

3. 核心职责

3.1 隐私优先的监控
  • 本地处理——绝不将音频发送到外部服务
  • 尽量减少缓冲——只保留检测所需的音频
  • 丢弃非唤醒音频——立即丢弃未检测到唤醒词的音频
  • 用户控制——提供便捷的禁用/暂停功能
3.2 效率要求
  • CPU 占用率低(平均 <5%)
  • 内存占用低(<100MB)
  • 检测延迟低(<500ms)
  • 误报率低(每小时 <1 次)

4. 技术基础

# requirements.txt
openwakeword>=0.6.0
numpy>=1.24.0
sounddevice>=0.4.6
onnxruntime>=1.16.0

5. 实现工作流(TDD)

步骤 1:先编写失败的测试
# tests/test_wake_word.py
import pytest
import numpy as np
from unittest.mock import Mock, patch

class TestWakeWordDetector:
    """TDD tests for wake word detection."""

    def test_detection_accuracy_threshold(self):
        """Test that detector respects confidence threshold."""
        from wake_word import SecureWakeWordDetector

        detector = SecureWakeWordDetector(threshold=0.7)
        callback = Mock()
        test_audio = np.random.randn(16000).astype(np.float32)

        with patch.object(detector.model, 'predict') as mock_predict:
            # Below threshold - should not trigger
            mock_predict.return_value = {"hey_jarvis": np.array([0.5])}
            detector._test_process(test_audio, callback)
            callback.assert_not_called()

            # Above threshold - should trigger
            mock_predict.return_value = {"hey_jarvis": np.array([0.8])}
            detector._test_process(test_audio, callback)
            callback.assert_called_once()

    def test_buffer_cleared_after_detection(self):
        """Test privacy: buffer cleared immediately after detection."""
        from wake_word import SecureWakeWordDetector

        detector = SecureWakeWordDetector()
        detector.audio_buffer.extend(np.zeros(16000))

        with patch.object(detector.model, 'predict') as mock_predict:
            mock_predict.return_value = {"hey_jarvis": np.array([0.9])}
            detector._process_audio()

        assert len(detector.audio_buffer) == 0, "Buffer must be cleared"

    def test_cpu_usage_under_threshold(self):
        """Test CPU usage stays under 5%."""
        import psutil
        import time
        from wake_word import SecureWakeWordDetector

        detector = SecureWakeWordDetector()
        process = psutil.Process()
        start_time = time.time()

        while time.time() - start_time < 10:
            audio = np.random.randn(1600).astype(np.float32)
            detector.audio_buffer.extend(audio)
            if len(detector.audio_buffer) >= 16000:
                detector._process_audio()

        avg_cpu = process.cpu_percent() / psutil.cpu_count()
        assert avg_cpu < 5, f"CPU usage too high: {avg_cpu}%"

    def test_memory_footprint(self):
        """Test memory usage stays under 100MB."""
        import tracemalloc
        from wake_word import SecureWakeWordDetector

        tracemalloc.start()
        detector = SecureWakeWordDetector()

        for _ in range(600):
            audio = np.random.randn(1600).astype(np.float32)
            detector.audio_buffer.extend(audio)

        current, peak = tracemalloc.get_traced_memory()
        tracemalloc.stop()

        peak_mb = peak / 1024 / 1024
        assert peak_mb < 100, f"Memory too high: {peak_mb}MB"
步骤 2:实现通过测试所需的最少代码
class SecureWakeWordDetector:
    def __init__(self, threshold=0.5):
        self.threshold = threshold
        self.model = Model(wakeword_models=["hey_jarvis"])
        self.audio_buffer = deque(maxlen=24000)

    def _test_process(self, audio, callback):
        predictions = self.model.predict(audio)
        for model_name, scores in predictions.items():
            if np.max(scores) > self.threshold:
                self.audio_buffer.clear()
                callback(model_name, np.max(scores))
                break
步骤 3:运行完整验证
pytest tests/test_wake_word.py -v
pytest --cov=wake_word --cov-report=term-missing

6. 实现模式

模式 1:安全的唤醒词检测器
from openwakeword.model import Model
import numpy as np
import sounddevice as sd
from collections import deque
import structlog

logger = structlog.get_logger()

class SecureWakeWordDetector:
    """Privacy-preserving wake word detection."""

    def __init__(self, model_path: str = None, threshold: float = 0.5, sample_rate: int = 16000):
        if model_path:
            self.model = Model(wakeword_models=[model_path])
        else:
            self.model = Model(wakeword_models=["hey_jarvis"])

        self.threshold = threshold
        self.sample_rate = sample_rate
        self.buffer_size = int(sample_rate * 1.5)
        self.audio_buffer = deque(maxlen=self.buffer_size)
        self.is_listening = False
        self.on_wake = None

    def start(self, callback):
        """Start listening for wake word."""
        self.on_wake = callback
        self.is_listening = True

        def audio_callback(indata, frames, time, status):
            if not self.is_listening:
                return
            audio = indata[:, 0] if len(indata.shape) > 1 else indata
            self.audio_buffer.extend(audio)
            if len(self.audio_buffer) >= self.sample_rate:
                self._process_audio()

        self.stream = sd.InputStream(
            samplerate=self.sample_rate, channels=1, dtype=np.float32,
            callback=audio_callback, blocksize=int(self.sample_rate * 0.1)
        )
        self.stream.start()

    def _process_audio(self):
        """Process audio buffer for wake word."""
        audio = np.array(list(self.audio_buffer))
        predictions = self.model.predict(audio)

        for model_name, scores in predictions.items():
            if np.max(scores) > self.threshold:
                self.audio_buffer.clear()  # Privacy: clear immediately
                if self.on_wake:
                    self.on_wake(model_name, np.max(scores))
                break

    def stop(self):
        """Stop listening."""
        self.is_listening = False
        if hasattr(self, 'stream'):
            self.stream.stop()
            self.stream.close()
        self.audio_buffer.clear()
模式 2:降低误报
class RobustDetector:
    """Reduce false positives with confirmation."""

    def __init__(self, detector: SecureWakeWordDetector):
        self.detector = detector
        self.detection_history = []
        self.confirmation_window = 2.0
        self.min_confirmations = 2

    def on_potential_wake(self, model: str, confidence: float):
        now = time.time()
        self.detection_history.append({"time": now, "confidence": confidence})
        self.detection_history = [d for d in self.detection_history if now - d["time"] < self.confirmation_window]

        if len(self.detection_history) >= self.min_confirmations:
            avg_confidence = np.mean([d["confidence"] for d in self.detection_history])
            if avg_confidence > 0.6:
                self.detection_history.clear()
                return True
        return False

7. 性能模式

模式 1:模型量化
# Good - Use quantized ONNX model
import onnxruntime as ort

class QuantizedDetector:
    def __init__(self, model_path: str):
        sess_options = ort.SessionOptions()
        sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
        self.session = ort.InferenceSession(model_path, sess_options, providers=['CPUExecutionProvider'])

# Bad - Full precision model
class SlowDetector:
    def __init__(self, model_path: str):
        self.session = ort.InferenceSession(model_path)  # No optimization
模式 2:高效音频缓冲
# Good - Pre-allocated numpy buffer with circular indexing
class EfficientBuffer:
    def __init__(self, size: int):
        self.buffer = np.zeros(size, dtype=np.float32)
        self.write_idx = 0
        self.size = size

    def append(self, audio: np.ndarray):
        n = len(audio)
        end_idx = (self.write_idx + n) % self.size
        if end_idx > self.write_idx:
            self.buffer[self.write_idx:end_idx] = audio
        else:
            self.buffer[self.write_idx:] = audio[:self.size - self.write_idx]
            self.buffer[:end_idx] = audio[self.size - self.write_idx:]
        self.write_idx = end_idx

# Bad - Individual appends
class SlowBuffer:
    def append(self, audio: np.ndarray):
        for sample in audio:  # Slow!
            self.buffer.append(sample)
模式 3:VAD 预处理
# Good - Skip inference on silence
import webrtcvad

class VADOptimizedDetector:
    def __init__(self):
        self.vad = webrtcvad.Vad(2)
        self.detector = SecureWakeWordDetector()

    def process(self, audio: np.ndarray):
        audio_int16 = (audio * 32767).astype(np.int16)
        if not self.vad.is_speech(audio_int16.tobytes(), 16000):
            return None  # Skip expensive inference
        return self.detector._process_audio()

# Bad - Always run inference
class WastefulDetector:
    def process(self, audio: np.ndarray):
        return self.detector._process_audio()  # Even on silence
模式 4:批量推理
# Good - Process multiple windows in single inference
class BatchDetector:
    def __init__(self, batch_size: int = 4):
        self.batch_size = batch_size
        self.pending_windows = []

    def add_window(self, audio: np.ndarray):
        self.pending_windows.append(audio)
        if len(self.pending_windows) >= self.batch_size:
            batch = np.stack(self.pending_windows)
            results = self.model.predict_batch(batch)
            self.pending_windows.clear()
            return results
        return None
模式 5:内存映射模型
# Good - Memory-map large model files
import mmap

class MmapModelLoader:
    def __init__(self, model_path: str):
        self.file = open(model_path, 'rb')
        self.mmap = mmap.mmap(self.file.fileno(), 0, access=mmap.ACCESS_READ)

# Bad - Load entire model into memory
class EagerModelLoader:
    def __init__(self, model_path: str):
        with open(model_path, 'rb') as f:
            self.model_data = f.read()  # Entire model in RAM

8. 安全标准

class PrivacyController:
    """Ensure privacy in always-listening system."""

    def __init__(self):
        self.is_enabled = True
        self.last_activity = time.time()

    def check_privacy_mode(self) -> bool:
        if self._is_dnd_enabled():
            return False
        if time.time() - self.last_activity > 3600:
            return False
        return self.is_enabled

# Data minimization
MAX_BUFFER_SECONDS = 2.0
def on_wake_detected():
    audio_buffer.clear()  # Delete immediately

9. 常见错误

# BAD - Stores all audio
def on_audio(chunk):
    with open("audio.raw", "ab") as f:
        f.write(chunk)

# GOOD - Discard after processing
def on_audio(chunk):
    buffer.extend(chunk)
    process_buffer()

# BAD - Large buffer
buffer = deque(maxlen=sample_rate * 60)  # 1 minute!

# GOOD - Minimal buffer
buffer = deque(maxlen=sample_rate * 1.5)  # 1.5 seconds

10. 实施前检查清单

阶段 1:编写代码前
  • 完整阅读 TDD 工作流部分
  • 创建包含检测准确性测试的测试文件
  • 确定阈值和性能目标
  • 确定适用的性能模式
  • 查看隐私要求
阶段 2:实施期间
  • 先为每项功能编写失败的测试
  • 实现通过测试所需的最少代码
  • 应用性能模式(VAD、量化)
  • 将缓冲区大小保持在最小(<2 秒)
  • 检测后清除音频
阶段 3:提交前
  • 所有测试均通过:pytest tests/test_wake_word.py -v
  • 覆盖率 >80%:pytest --cov=wake_word
  • 已测试误报率 <1 次/小时
  • 已测量 CPU 占用率 <5%
  • 已确认内存占用 <100MB
  • 音频从未存储到磁盘

11. 总结

你的目标是创建具备以下特点的唤醒词检测系统:

  • 保护隐私:在本地处理音频,尽量减少保留
  • 高效:CPU 占用率低(<5%),内存占用低(<100MB)
  • 准确:误报率低(<1 次/小时)
  • 测试驱动:所有功能都先编写测试

重要提醒:

  1. 先编写测试,再进行实现
  2. 绝不将音频存储到磁盘
  3. 将缓冲区保持在最小(<2 秒)
  4. 应用性能模式(VAD、量化)

评论

支持 Markdown