Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Transcription pipeline improvements, closes #392

davidmezzettic90d78126caf
diff --git a/setup.py b/setup.py
index 35c32747..c22c7318 100644
--- a/setup.py
+++ b/setup.py
@@ -30,7 +30,7 @@ extras["graph"] = ["networkx>=2.6.3", "python-louvain>=0.16"]
extras["model"] = ["onnx>=1.11.0", "onnxruntime>=1.11.0"]
-extras["pipeline-audio"] = ["onnx>=1.11.0", "onnxruntime>=1.11.0", "soundfile>=0.10.3.post1", "ttstokenizer>=1.0.0"]
+extras["pipeline-audio"] = ["onnx>=1.11.0", "onnxruntime>=1.11.0", "soundfile>=0.10.3.post1", "scipy>=1.4.1", "ttstokenizer>=1.0.0"]
extras["pipeline-data"] = ["beautifulsoup4>=4.9.3", "nltk>=3.5", "pandas>=1.1.0", "tika>=1.24"]
diff --git a/src/python/txtai/pipeline/audio/texttospeech.py b/src/python/txtai/pipeline/audio/texttospeech.py
index 7ba36ab5..20f96adc 100644
--- a/src/python/txtai/pipeline/audio/texttospeech.py
+++ b/src/python/txtai/pipeline/audio/texttospeech.py
@@ -127,17 +127,3 @@ class TextToSpeech(Pipeline):
# Concatenate results and return
return np.concatenate(results)
-
- def batch(self, texts, size):
- """
- Splits texts into separate batch sizes specified by size.
-
- Args:
- texts: text elements
- size: batch size
-
- Returns:
- list of evenly sized batches with the last batch having the remaining elements
- """
-
- return [texts[x : x + size] for x in range(0, len(texts), size)]
diff --git a/src/python/txtai/pipeline/audio/transcription.py b/src/python/txtai/pipeline/audio/transcription.py
index 591d86cc..e110eaf1 100644
--- a/src/python/txtai/pipeline/audio/transcription.py
+++ b/src/python/txtai/pipeline/audio/transcription.py
@@ -5,6 +5,8 @@ Transcription module
try:
import soundfile as sf
+ from scipy import signal
+
SOUNDFILE = True
except (ImportError, OSError):
SOUNDFILE = False
@@ -24,7 +26,7 @@ class Transcription(HFPipeline):
# Call parent constructor
super().__init__("automatic-speech-recognition", path, quantize, gpu, model)
- def __call__(self, audio, rate=None):
+ def __call__(self, audio, rate=None, chunk=10, join=True):
"""
Transcribes audio files or data to text.
@@ -34,6 +36,10 @@ class Transcription(HFPipeline):
Args:
audio: audio|list
rate: sampling rate, only required with raw audio data
+ chunk: process audio in chunk second sized segments
+ join: if True (default), combine each chunk back together into a single text output.
+ When False, chunks are returned as a list of dicts, each having raw associated audio and
+ sample rate in addition to text
Returns:
list of transcribed text
@@ -42,34 +48,25 @@ class Transcription(HFPipeline):
# Convert single element to list
values = [audio] if not isinstance(audio, list) else audio
- # Parse audio
- speech = self.parse(values, rate)
+ # Read input audio
+ speech = self.read(values, rate)
# Apply transformation rules and store results
- results = []
- for result in self.pipeline(speech):
- # Trim whitespace
- text = result["text"].strip()
-
- # Convert all upper case strings to capitalized case
- text = text.capitalize() if text.isupper() else text
-
- # Store result
- results.append(text)
+ results = self.batchprocess(speech, chunk) if chunk and not join else self.process(speech, chunk)
# Return single element if single element passed in
return results[0] if not isinstance(audio, list) else results
- def parse(self, audio, rate):
+ def read(self, audio, rate):
"""
- Parses audio to raw waveforms and sampling rates.
+ Read audio to raw waveforms and sampling rates.
Args:
audio: audio|list
rate: optional sampling rate
Returns:
- List of dictionaries
+ List of (audio data, sample rate)
"""
speech = []
@@ -81,6 +78,143 @@ class Transcription(HFPipeline):
# Input is NumPy array
raw, samplerate = x, rate
- speech.append({"raw": raw, "sampling_rate": samplerate})
+ speech.append((raw, samplerate))
return speech
+
+ def process(self, speech, chunk):
+ """
+ Standard processing loop. Runs a single pipeline call for all speech inputs along
+ with the chunk size. Returns text for each input.
+
+ Args:
+ speech: list of dicts with raw data and sample rates
+ chunk: split audio into chunk seconds sized segments for processing
+
+ Returns:
+ list of transcribed text
+ """
+
+ results = []
+ for result in self.pipeline([self.convert(*x) for x in speech], chunk_length_s=chunk, ignore_warning=True):
+ # Store result
+ results.append(self.clean(result["text"]))
+
+ return results
+
+ def batchprocess(self, speech, chunk):
+ """
+ Batch processing loop. Runs a pipeline call per speech input. Each speech input is split
+ into chunk duration segments. Each segment is individually transcribed and returned along with
+ the raw wav snippets.
+
+ Args:
+ speech: list of dicts with raw data and sample rates
+ chunk: split audio into chunk seconds sized segments for processing
+
+ Returns:
+ list of lists of dicts. each dict has text, raw wav data and sample rate
+ """
+
+ results = []
+
+ # Process each element individually to get time-sliced chunks
+ for raw, rate in speech:
+ # Get segments for current speech entry
+ segments = self.segments(raw, rate, chunk)
+
+ # Process segments, store raw data before processing given pipeline modifies it
+ sresults = []
+ for x, result in enumerate(self.pipeline([self.convert(*x) for x in segments])):
+ sresults.append({"text": self.clean(result["text"]), "raw": segments[x][0], "rate": segments[x][1]})
+
+ results.append(sresults)
+
+ return results
+
+ def segments(self, raw, rate, chunk):
+ """
+ Builds chunk duration batches.
+
+ Args:
+ raw: raw audio data
+ rate: sample rate
+ chunk: chunk duration size
+ """
+
+ segments = []
+
+ # Split into batches, use sample rate * chunk seconds
+ for segment in self.batch(raw, rate * chunk):
+ segments.append((segment, rate))
+
+ return segments
+
+ def convert(self, raw, rate):
+ """
+ Converts input audio to mono with a sample rate equal to the pipeline model's
+ sample rate.
+
+ Args:
+ raw: raw audio data
+
+ Returns:
+ audio data ready for pipeline model
+ """
+
+ # Convert stereo to mono, if necessary
+ raw = self.mono(raw)
+
+ # Resample to model sample rate
+ raw, rate = self.resample(raw, rate)
+
+ return {"raw": raw, "sampling_rate": rate}
+
+ def mono(self, raw):
+ """
+ Convert stereo to mono audio.
+
+ Args:
+ raw: raw audio data
+
+ Returns:
+ audio data with a single channel
+ """
+
+ return raw.mean(axis=1) if len(raw.shape) > 1 else raw
+
+ def resample(self, raw, rate):
+ """
+ Resample raw audio if the sample rate doesn't match the sample rate required for this model.
+
+ Args:
+ raw: raw audio data
+ rate: sample rate
+
+ Returns:
+ raw audio resampled if necessary or original raw audio
+ """
+
+ targetrate = self.pipeline.feature_extractor.sampling_rate
+ if rate != targetrate:
+ samples = round(len(raw) * float(targetrate) / rate)
+ raw = signal.resample(raw, samples)
+
+ return raw, targetrate
+
+ def clean(self, text):
+ """
+ Applies text normalization rules.
+
+ Args:
+ text: input text
+
+ Returns:
+ clean text
+ """
+
+ # Trim whitespace
+ text = text.strip()
+
+ # Convert all upper case strings to capitalized case
+ return text.capitalize() if text.isupper() else text
diff --git a/src/python/txtai/pipeline/base.py b/src/python/txtai/pipeline/base.py
index 6fad9358..f42add89 100644
--- a/src/python/txtai/pipeline/base.py
+++ b/src/python/txtai/pipeline/base.py
@@ -7,3 +7,17 @@ class Pipeline:
"""
Base class for all Pipelines. The only interface requirement is to define a __call___ method.
"""
+
+ def batch(self, data, size):
+ """
+ Splits data into separate batch sizes specified by size.
+
+ Args:
+ data: data elements
+ size: batch size
+
+ Returns:
+ list of evenly sized batches with the last batch having the remaining elements
+ """
+
+ return [data[x : x + size] for x in range(0, len(data), size)]
diff --git a/src/python/txtai/pipeline/hfmodel.py b/src/python/txtai/pipeline/hfmodel.py
index 319570ed..cebd485c 100644
--- a/src/python/txtai/pipeline/hfmodel.py
+++ b/src/python/txtai/pipeline/hfmodel.py
@@ -109,17 +109,3 @@ class HFModel(Tensors):
# pylint: disable=E1102
return ({name: self.tensor(tensor).to(self.device) for name, tensor in tokens.items()}, indices)
-
- def batch(self, texts, size):
- """
- Splits texts into separate batch sizes specified by size.
-
- Args:
- texts: text elements
- size: batch size
-
- Returns:
- list of evenly sized batches with the last batch having the remaining elements
- """
-
- return [texts[x : x + size] for x in range(0, len(texts), size)]
diff --git a/test/python/testpipeline/testtranscription.py b/test/python/testpipeline/testtranscription.py
index f03eb479..e3c2d5c9 100644
--- a/test/python/testpipeline/testtranscription.py
+++ b/test/python/testpipeline/testtranscription.py
@@ -4,8 +4,11 @@ Transcription module tests
import unittest
+import numpy as np
import soundfile as sf
+from scipy import signal
+
from txtai.pipeline import Transcription
# pylint: disable = C0411
@@ -29,6 +32,19 @@ class TestTranscription(unittest.TestCase):
self.assertEqual(transcribe(raw, samplerate), "Make huge profits without working make up to one hundred thousand dollars a day")
+ def testChunks(self):
+ """
+ Test splitting transcription into chunks
+ """
+
+ transcribe = Transcription()
+
+ result = transcribe(Utils.PATH + "/Make_huge_profits.wav", join=False)[0]
+
+ self.assertIsInstance(result["raw"], np.ndarray)
+ self.assertIsNotNone(result["rate"])
+ self.assertEqual(result["text"], "Make huge profits without working make up to one hundred thousand dollars a day")
+
def testFile(self):
"""
Test audio file to text transcription
@@ -39,3 +55,34 @@ class TestTranscription(unittest.TestCase):
self.assertEqual(
transcribe(Utils.PATH + "/Make_huge_profits.wav"), "Make huge profits without working make up to one hundred thousand dollars a day"
)
+
+ def testResample(self):
+ """
+ Test resampled audio file to text transcription
+ """
+
+ transcribe = Transcription()
+
+ # Read audio data
+ raw, samplerate = sf.read(Utils.PATH + "/Make_huge_profits.wav")
+
+ # Resample for testing
+ samples = round(len(raw) * float(22050) / samplerate)
+ raw, samplerate = signal.resample(raw, samples), 22050
+
+ self.assertEqual(transcribe(raw, samplerate), "Make huge profits without working make up to one hundred thousand dollars a day")
+
+ def testStereo(self):
+ """
+ Test audio file in stereo to text transcription
+ """
+
+ transcribe = Transcription()
+
+ # Read audio data
+ raw, samplerate = sf.read(Utils.PATH + "/Make_huge_profits.wav")
+
+ # Convert mono to stereo
+ raw = np.column_stack((raw, raw))
+
+ self.assertEqual(transcribe(raw, samplerate), "Make huge profits without working make up to one hundred thousand dollars a day")