Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Update transcription pipeline to call automatic-speech-recognition pipeline, closes #362

davidmezzettie8cce346c562
diff --git a/src/python/txtai/pipeline/audio/transcription.py b/src/python/txtai/pipeline/audio/transcription.py
index 174f97ea..ee368254 100644
--- a/src/python/txtai/pipeline/audio/transcription.py
+++ b/src/python/txtai/pipeline/audio/transcription.py
@@ -9,40 +9,20 @@ try:
except (ImportError, OSError):
SOUNDFILE = False
-from transformers import AutoModelForCTC, Wav2Vec2Processor
+from ..hfpipeline import HFPipeline
-from ..hfmodel import HFModel
-
-class Transcription(HFModel):
+class Transcription(HFPipeline):
"""
Transcribes audio files to text.
"""
- def __init__(self, path="facebook/wav2vec2-base-960h", quantize=False, gpu=True, batch=64):
- """
- Constructs a new transcription pipeline.
-
- Args:
- path: optional path to model, accepts Hugging Face model hub id or local path,
- uses default model for task if not provided
- quantize: if model should be quantized, defaults to False
- gpu: True/False if GPU should be enabled, also supports a GPU device id
- batch: batch size used to incrementally process content
- """
-
- # Call parent constructor
- super().__init__(path, quantize, gpu, batch)
-
+ def __init__(self, path=None, quantize=False, gpu=True, model=None):
if not SOUNDFILE:
raise ImportError("SoundFile library not installed or libsndfile not found")
- # load model and processor
- self.model = AutoModelForCTC.from_pretrained(self.path)
- self.processor = Wav2Vec2Processor.from_pretrained(self.path)
-
- # Move model to device
- self.model.to(self.device)
+ # Call parent constructor
+ super().__init__("automatic-speech-recognition", path, quantize, gpu, model)
def __call__(self, files):
"""
@@ -63,50 +43,20 @@ class Transcription(HFModel):
# Parse audio files
speech = [sf.read(f) for f in values]
- # Get unique list of sampling rates
- unique = set(s[1] for s in speech)
+ # Format inputs
+ speech = [{"raw": s[0], "sampling_rate": s[1]} for s in speech]
- results = {}
- for sampling in unique:
- # Get inputs for current sampling rate
- inputs = [(x, s[0]) for x, s in enumerate(speech) if s[1] == sampling]
+ # Apply transformation rules and store results
+ results = []
+ for result in self.pipeline(speech):
+ # Trim whitespace
+ text = result["text"].strip()
- # Transcribe in batches
- outputs = []
- for chunk in self.batch([s for _, s in inputs], self.batchsize):
- outputs.extend(self.transcribe(chunk, sampling))
+ # Convert all upper case strings to capitalized case
+ text = text.capitalize() if text.isupper() else text
- # Store output value
- for y, (x, _) in enumerate(inputs):
- results[x] = outputs[y].capitalize()
+ # Store result
+ results.append(text)
- # Return results in same order as input
- results = [results[x] for x in sorted(results)]
+ # Return single element if single element passed in
return results[0] if isinstance(files, str) else results
-
- def transcribe(self, speech, sampling):
- """
- Transcribes audio to text.
-
- Args:
- speech: list of audio
- sampling: sampling rate
-
- Returns:
- list of transcribed text
- """
-
- with self.context():
- # Convert samples to features
- inputs = self.processor(speech, sampling_rate=sampling, padding=True, return_tensors=self.tensortype()).input_values
-
- # Place inputs on tensor device
- inputs = inputs.to(self.device)
-
- # Retrieve logits
- logits = self.model(inputs).logits
-
- # Decode argmax
- ids = self.argmax(logits, dimension=-1)
-
- return self.processor.batch_decode(ids)
diff --git a/src/python/txtai/pipeline/tensors.py b/src/python/txtai/pipeline/tensors.py
index 86564cac..c86cf72e 100644
--- a/src/python/txtai/pipeline/tensors.py
+++ b/src/python/txtai/pipeline/tensors.py
@@ -40,31 +40,6 @@ class Tensors(Pipeline):
# pylint: disable=E1102
return torch.tensor(data)
- def tensortype(self):
- """
- Returns the tensor processing framework code.
-
- Returns:
- tensor processing framework code
- """
-
- return "pt"
-
- def argmax(self, data, dimension):
- """
- Calls argmax on data using the tensor processing framework.
-
- Args:
- data: input data
- dimension: dimension to derive argmax
-
- Returns:
- argmax
- """
-
- # pylint: disable=E1101
- return torch.argmax(data, dim=dimension)
-
def context(self):
"""
Defines a context used to wrap processing with the tensor processing framework.