Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add a microphone pipeline, closes #785

davidmezzetti374197b45342
diff --git a/docs/pipeline/audio/microphone.md b/docs/pipeline/audio/microphone.md
new file mode 100644
index 00000000..9de5b90f
--- /dev/null
+++ b/docs/pipeline/audio/microphone.md
@@ -0,0 +1,62 @@
+# Microphone
+
+![pipeline](../../images/pipeline.png#only-light)
+![pipeline](../../images/pipeline-dark.png#only-dark)
+
+The Microphone pipeline reads input audio from a microphone device. This pipeline is designed to run on local machines given that it requires access to read from an input device.
+
+## Example
+
+The following shows a simple example using this pipeline.
+
+```python
+from txtai.pipeline import Microphone
+
+# Create and run pipeline
+microphone = Microphone()
+microphone()
+```
+
+## Configuration-driven example
+
+Pipelines are run with Python or configuration. Pipelines can be instantiated in [configuration](../../../api/configuration/#pipeline) using the lower case name of the pipeline. Configuration-driven pipelines are run with [workflows](../../../workflow/#configuration-driven-example) or the [API](../../../api#local-instance).
+
+### config.yml
+```yaml
+# Create pipeline using lower case class name
+audiostream:
+
+# Run pipeline with workflow
+workflow:
+ audiostream:
+ tasks:
+ - action: audiostream
+```
+
+### Run with Workflows
+
+```python
+from txtai import Application
+
+# Create and run pipeline with workflow
+app = Application("config.yml")
+list(app.workflow("audiostream", ["numpy data"]))
+```
+
+### Run with API
+
+```bash
+CONFIG=config.yml uvicorn "txtai.api:app" &
+
+curl \
+ -X POST "http://localhost:8000/workflow" \
+ -H "Content-Type: application/json" \
+ -d '{"name":"audiostream", "elements":["numpy data"]}'
+```
+
+## Methods
+
+Python documentation for the pipeline.
+
+### ::: txtai.pipeline.Microphone.__init__
+### ::: txtai.pipeline.Microphone.__call__
diff --git a/src/python/txtai/pipeline/audio/__init__.py b/src/python/txtai/pipeline/audio/__init__.py
index 40979416..5e7ce561 100644
--- a/src/python/txtai/pipeline/audio/__init__.py
+++ b/src/python/txtai/pipeline/audio/__init__.py
@@ -2,5 +2,7 @@
Audio imports
"""
+from .audiostream import AudioStream
+from .microphone import Microphone
from .texttospeech import TextToSpeech
from .transcription import Transcription
diff --git a/src/python/txtai/pipeline/audio/microphone.py b/src/python/txtai/pipeline/audio/microphone.py
new file mode 100644
index 00000000..bae016b2
--- /dev/null
+++ b/src/python/txtai/pipeline/audio/microphone.py
@@ -0,0 +1,107 @@
+"""
+Microphone module
+"""
+
+import numpy as np
+
+# Conditional import
+try:
+ import speech_recognition as sr
+ import webrtcvad
+
+ PYAUDIO = True
+except ImportError:
+ PYAUDIO = False
+
+from ..base import Pipeline
+
+
+class Microphone(Pipeline):
+ """
+ Reads input audio from a microphone device. This pipeline is designed to run on local machines given
+ that it requires access to read from an input device.
+ """
+
+ def __init__(self, rate=16000, vadmode=1, vadframe=30, vadthreshold=0.6):
+ """
+ Creates a new Microphone pipeline.
+
+ Args:
+ rate: sample rate to record audio in, defaults to 16 kHz
+ vadmode: aggressiveness of the voice activity detector, defaults to 1
+ vadframe: voice activity detector frame size in ms, defaults to 30
+ vadthreshold: percentage of frames (0.0 - 1.0) that must be voice to be considered speech, defaults to 0.6
+ """
+
+ if not PYAUDIO:
+ raise ImportError('Microphone pipeline is not available - install "pipeline" extra to enable')
+
+ # Voice activity detector
+ self.vad = webrtcvad.Vad(vadmode)
+ self.vadframe = vadframe
+ self.vadthreshold = vadthreshold
+
+ # Sample rate
+ self.rate = rate
+
+ # Speech recognition config
+ self.recognizer = sr.Recognizer()
+
+ def __call__(self, device=None):
+ # Read from microphone
+ with sr.Microphone(sample_rate=self.rate) as source:
+ # Calibrate microphone
+ self.recognizer.adjust_for_ambient_noise(source)
+
+ # Wait for speech
+ audio = None
+ while audio is None:
+ audio = self.listen(source)
+
+ # Return single element if single element passed in
+ return (audio, self.rate) if device is None or not isinstance(device, list) else [(audio, self.rate)]
+
+ def listen(self, source):
+ """
+ Listens for audio from source. Returns audio if it passes the voice
+ activity detector.
+
+ Args:
+ source: microphone source
+
+ Returns:
+ audio if present, else None
+ """
+
+ audio = self.recognizer.listen(source)
+ if self.detect(audio.frame_data, audio.sample_rate):
+ # Convert to WAV
+ data = audio.get_wav_data()
+
+ # Convert to float32
+ s16 = np.frombuffer(data, dtype=np.int16, count=len(data) // 2, offset=0)
+ return s16.astype(np.float32, order="C") / 32768
+
+ return None
+
+ def detect(self, audio, rate):
+ """
+ Voice activity detector.
+
+ Args:
+ audio: input waveform data
+ rate: sample rate
+
+ Returns:
+ True if the number of audio frames with audio pass vadthreshold, False otherwise
+ """
+
+ n = int(rate * (self.vadframe / 1000.0) * 2)
+ offset = 0
+
+ detects = []
+ while offset + n < len(audio):
+ detects.append(1 if self.vad.is_speech(audio[offset : offset + n], rate) else 0)
+ offset += n
+
+ return sum(detects) / len(detects) >= self.vadthreshold if detects else 0
diff --git a/test/python/testpipeline/testmicrophone.py b/test/python/testpipeline/testmicrophone.py
new file mode 100644
index 00000000..9997a1d0
--- /dev/null
+++ b/test/python/testpipeline/testmicrophone.py
@@ -0,0 +1,61 @@
+"""
+Microphone module tests
+"""
+
+import unittest
+
+from unittest.mock import patch
+
+import soundfile as sf
+
+from txtai.pipeline import Microphone
+
+# pylint: disable = C0411
+from utils import Utils
+
+
+class TestMicrophone(unittest.TestCase):
+ """
+ Microphone tests.
+ """
+
+ @patch("speech_recognition.Recognizer.listen")
+ @patch("speech_recognition.Recognizer.adjust_for_ambient_noise")
+ @patch("speech_recognition.Microphone")
+ # pylint: disable=C0115,C0116,W0613
+ def testMicrophone(self, microphone, ambient, listen):
+ """
+ Test listening to microphone
+ """
+
+ class Audio:
+ def __init__(self):
+ self.frame_data, self.sample_rate = None, None
+
+ def get_wav_data(self):
+ return self.frame_data
+
+ def speech(device):
+ # Read audio data
+ raw, samplerate = sf.read(Utils.PATH + "/Make_huge_profits.wav")
+
+ audio = Audio()
+ audio.frame_data, audio.sample_rate = raw, samplerate
+ return audio
+
+ def nospeech(device):
+ audio = Audio()
+ audio.sample_rate = 16000
+ audio.frame_data = b"\x00\x00" * int(audio.sample_rate * 30 / 1000)
+ return audio
+
+ microphone.return_value.__enter__.return_value = (0, 1)
+ ambient.return_value = True
+
+ pipeline = Microphone()
+
+ listen.side_effect = speech
+ self.assertIsNotNone(pipeline([1]))
+
+ listen.side_effect = nospeech
+ self.assertIsNone(pipeline.listen(microphone))