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 TextToSpeech pipeline, closes #389

davidmezzetti65a110e9fb35
diff --git a/src/python/txtai/pipeline/audio/__init__.py b/src/python/txtai/pipeline/audio/__init__.py
index eb4a41d7..40979416 100644
--- a/src/python/txtai/pipeline/audio/__init__.py
+++ b/src/python/txtai/pipeline/audio/__init__.py
@@ -2,4 +2,5 @@
Audio imports
"""
+from .texttospeech import TextToSpeech
from .transcription import Transcription
diff --git a/src/python/txtai/pipeline/audio/texttospeech.py b/src/python/txtai/pipeline/audio/texttospeech.py
new file mode 100644
index 00000000..7ba36ab5
--- /dev/null
+++ b/src/python/txtai/pipeline/audio/texttospeech.py
@@ -0,0 +1,143 @@
+"""
+TextToSpeech module
+"""
+
+# Conditional import
+try:
+ import onnxruntime as ort
+
+ from ttstokenizer import TTSTokenizer
+
+ TTS = True
+except ImportError:
+ TTS = False
+
+import torch
+import yaml
+
+import numpy as np
+
+from huggingface_hub import hf_hub_download
+
+from ..base import Pipeline
+
+
+class TextToSpeech(Pipeline):
+ """
+ Generates speech from text
+ """
+
+ def __init__(self, path="NeuML/ljspeech-jets-onnx", maxtokens=512):
+ """
+ Creates a new TextToSpeech pipeline.
+
+ Args:
+ path: optional Hugging Face model hub id
+ maxtokens: maximum number of tokens model can process, defaults to 512
+ """
+
+ if not TTS:
+ raise ImportError('TextToSpeech pipeline is not available - install "pipeline" extra to enable')
+
+ # Get path to model and config
+ config = hf_hub_download(path, filename="config.yaml")
+ model = hf_hub_download(path, filename="model.onnx")
+
+ # Read yaml config
+ with open(config, "r", encoding="utf-8") as f:
+ config = yaml.safe_load(f)
+
+ # Create tokenizer
+ tokens = config.get("token", {}).get("list")
+ self.tokenizer = TTSTokenizer(tokens)
+
+ # Create ONNX Session
+ self.model = ort.InferenceSession(model, ort.SessionOptions(), self.providers())
+
+ # Max number of input tokens model can handle
+ self.maxtokens = maxtokens
+
+ # Get model input name, typically "text"
+ self.input = self.model.get_inputs()[0].name
+
+ def __call__(self, text):
+ """
+ Generates speech from text. Text longer than maxtokens will be batched and returned
+ as a single waveform per text input.
+
+ This method supports files as a string or a list. If the input is a string,
+ the return type is string. If text is a list, the return type is a list.
+
+ Args:
+ text: text|list
+
+ Returns:
+ list of speech as NumPy array waveforms
+ """
+
+ # Convert results to a list if necessary
+ texts = [text] if isinstance(text, str) else text
+
+ outputs = []
+ for x in texts:
+ # Truncate to max size model can handle
+ x = self.tokenizer(x)
+
+ # Run input through model and store result
+ result = self.execute(x)
+ outputs.append(result)
+
+ # Return results
+ return outputs[0] if isinstance(text, str) else outputs
+
+ def providers(self):
+ """
+ Returns a list of available and usable providers.
+
+ Returns:
+ list of available and usable providers
+ """
+
+ # Create list of providers, prefer CUDA provider if available
+ # CUDA provider only available if GPU is available and onnxruntime-gpu installed
+ if torch.cuda.is_available() and "CUDAExecutionProvider" in ort.get_available_providers():
+ return [("CUDAExecutionProvider", {"cudnn_conv_algo_search": "DEFAULT"}), "CPUExecutionProvider"]
+
+ # Default when CUDA provider isn't available
+ return ["CPUExecutionProvider"]
+
+ def execute(self, tokens):
+ """
+ Executes model run for input array of tokens. This method will build batches
+ of tokens when len(tokens) > maxtokens.
+
+ Args:
+ tokens: array of tokens to pass to model
+
+ Returns:
+ waveform as NumPy array
+ """
+
+ # Split into batches and process
+ results = []
+ for x in self.batch(tokens, self.maxtokens):
+ # Run text through TTS model and save waveform
+ output = self.model.run(None, {self.input: x})
+ results.append(output[0])
+
+ # 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/test/python/testoptional.py b/test/python/testoptional.py
index ee7a4493..432f4b68 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -40,6 +40,7 @@ class TestOptional(unittest.TestCase):
"sentence_transformers",
"soundfile",
"tika",
+ "ttstokenizer",
"xmltodict",
]
@@ -139,7 +140,19 @@ class TestOptional(unittest.TestCase):
Test missing pipeline dependencies
"""
- from txtai.pipeline import Caption, HFOnnx, ImageHash, MLOnnx, Objects, Segmentation, Tabular, Textractor, Transcription, Translation
+ from txtai.pipeline import (
+ Caption,
+ HFOnnx,
+ ImageHash,
+ MLOnnx,
+ Objects,
+ Segmentation,
+ Tabular,
+ Textractor,
+ TextToSpeech,
+ Transcription,
+ Translation,
+ )
with self.assertRaises(ImportError):
Caption()
@@ -165,6 +178,9 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
Textractor()
+ with self.assertRaises(ImportError):
+ TextToSpeech()
+
with self.assertRaises(ImportError):
Transcription()
diff --git a/test/python/testpipeline/testtexttospeech.py b/test/python/testpipeline/testtexttospeech.py
new file mode 100644
index 00000000..2c8ef6e2
--- /dev/null
+++ b/test/python/testpipeline/testtexttospeech.py
@@ -0,0 +1,39 @@
+"""
+TextToSpeech module tests
+"""
+
+import unittest
+
+from unittest.mock import patch
+
+from txtai.pipeline import TextToSpeech
+
+
+class TestTextToSpeech(unittest.TestCase):
+ """
+ TextToSpeech tests.
+ """
+
+ def testTextToSpeech(self):
+ """
+ Tests generating speech for text
+ """
+
+ tts = TextToSpeech()
+
+ # Check that data is generated
+ self.assertGreater(len(tts("This is a test")), 0)
+
+ @patch("onnxruntime.get_available_providers")
+ @patch("torch.cuda.is_available")
+ def testProviders(self, cuda, providers):
+ """
+ Test that GPU provider is detected
+ """
+
+ # Test CUDA and onnxruntime-gpu installed
+ cuda.return_value = True
+ providers.return_value = ["CUDAExecutionProvider", "CPUExecutionProvider"]
+
+ tts = TextToSpeech()
+ self.assertEqual(tts.providers()[0][0], "CUDAExecutionProvider")