docs / huggingface_speech-to-speech.txt
danidarko's picture
Upload 59 files
b1d4de0 verified
# File: speech-to-speech-main/LLM/chat.py
class Chat:
def __init__(self, size):
self.size = size
self.init_chat_message = None
self.buffer = []
def append(self, item):
self.buffer.append(item)
if len(self.buffer) == 2 * (self.size + 1):
self.buffer.pop(0)
self.buffer.pop(0)
def init_chat(self, init_chat_message):
self.init_chat_message = init_chat_message
def to_list(self):
if self.init_chat_message:
return [self.init_chat_message] + self.buffer
else:
return self.buffer
# File: speech-to-speech-main/LLM/language_model.py
from threading import Thread
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TextIteratorStreamer
import torch
from LLM.chat import Chat
from baseHandler import BaseHandler
from rich.console import Console
import logging
from nltk import sent_tokenize
logger = logging.getLogger(__name__)
console = Console()
WHISPER_LANGUAGE_TO_LLM_LANGUAGE = {'en': 'english', 'fr': 'french', 'es': 'spanish', 'zh': 'chinese', 'ja': 'japanese', 'ko': 'korean'}
class LanguageModelHandler(BaseHandler):
def setup(self, model_name='microsoft/Phi-3-mini-4k-instruct', device='cuda', torch_dtype='float16', gen_kwargs={}, user_role='user', chat_size=1, init_chat_role=None, init_chat_prompt='You are a helpful AI assistant.'):
self.device = device
self.torch_dtype = getattr(torch, torch_dtype)
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch_dtype, trust_remote_code=True).to(device)
self.pipe = pipeline('text-generation', model=self.model, tokenizer=self.tokenizer, device=device)
self.streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, skip_special_tokens=True)
self.gen_kwargs = {'streamer': self.streamer, 'return_full_text': False, **gen_kwargs}
self.chat = Chat(chat_size)
if init_chat_role:
if not init_chat_prompt:
raise ValueError('An initial promt needs to be specified when setting init_chat_role.')
self.chat.init_chat({'role': init_chat_role, 'content': init_chat_prompt})
self.user_role = user_role
self.warmup()
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
dummy_input_text = "Repeat the word 'home'."
dummy_chat = [{'role': self.user_role, 'content': dummy_input_text}]
warmup_gen_kwargs = {'min_new_tokens': self.gen_kwargs['min_new_tokens'], 'max_new_tokens': self.gen_kwargs['max_new_tokens'], **self.gen_kwargs}
n_steps = 2
if self.device == 'cuda':
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
torch.cuda.synchronize()
start_event.record()
for _ in range(n_steps):
thread = Thread(target=self.pipe, args=(dummy_chat,), kwargs=warmup_gen_kwargs)
thread.start()
for _ in self.streamer:
pass
if self.device == 'cuda':
end_event.record()
torch.cuda.synchronize()
logger.info(f'{self.__class__.__name__}: warmed up! time: {start_event.elapsed_time(end_event) * 0.001:.3f} s')
def process(self, prompt):
logger.debug('infering language model...')
language_code = None
if isinstance(prompt, tuple):
(prompt, language_code) = prompt
prompt = f'Please reply to my message in {WHISPER_LANGUAGE_TO_LLM_LANGUAGE[language_code]}. ' + prompt
self.chat.append({'role': self.user_role, 'content': prompt})
thread = Thread(target=self.pipe, args=(self.chat.to_list(),), kwargs=self.gen_kwargs)
thread.start()
if self.device == 'mps':
generated_text = ''
for new_text in self.streamer:
generated_text += new_text
printable_text = generated_text
torch.mps.empty_cache()
else:
(generated_text, printable_text) = ('', '')
for new_text in self.streamer:
generated_text += new_text
printable_text += new_text
sentences = sent_tokenize(printable_text)
if len(sentences) > 1:
yield (sentences[0], language_code)
printable_text = new_text
self.chat.append({'role': 'assistant', 'content': generated_text})
yield (printable_text, language_code)
# File: speech-to-speech-main/LLM/mlx_language_model.py
import logging
from LLM.chat import Chat
from baseHandler import BaseHandler
from mlx_lm import load, stream_generate, generate
from rich.console import Console
import torch
logger = logging.getLogger(__name__)
console = Console()
WHISPER_LANGUAGE_TO_LLM_LANGUAGE = {'en': 'english', 'fr': 'french', 'es': 'spanish', 'zh': 'chinese', 'ja': 'japanese', 'ko': 'korean'}
class MLXLanguageModelHandler(BaseHandler):
def setup(self, model_name='microsoft/Phi-3-mini-4k-instruct', device='mps', torch_dtype='float16', gen_kwargs={}, user_role='user', chat_size=1, init_chat_role=None, init_chat_prompt='You are a helpful AI assistant.'):
self.model_name = model_name
(self.model, self.tokenizer) = load(self.model_name)
self.gen_kwargs = gen_kwargs
self.chat = Chat(chat_size)
if init_chat_role:
if not init_chat_prompt:
raise ValueError('An initial promt needs to be specified when setting init_chat_role.')
self.chat.init_chat({'role': init_chat_role, 'content': init_chat_prompt})
self.user_role = user_role
self.warmup()
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
dummy_input_text = 'Write me a poem about Machine Learning.'
dummy_chat = [{'role': self.user_role, 'content': dummy_input_text}]
n_steps = 2
for _ in range(n_steps):
prompt = self.tokenizer.apply_chat_template(dummy_chat, tokenize=False)
generate(self.model, self.tokenizer, prompt=prompt, max_tokens=self.gen_kwargs['max_new_tokens'], verbose=False)
def process(self, prompt):
logger.debug('infering language model...')
language_code = None
if isinstance(prompt, tuple):
(prompt, language_code) = prompt
prompt = f'Please reply to my message in {WHISPER_LANGUAGE_TO_LLM_LANGUAGE[language_code]}. ' + prompt
self.chat.append({'role': self.user_role, 'content': prompt})
if 'gemma' in self.model_name.lower():
chat_messages = [msg for msg in self.chat.to_list() if msg['role'] != 'system']
else:
chat_messages = self.chat.to_list()
prompt = self.tokenizer.apply_chat_template(chat_messages, tokenize=False, add_generation_prompt=True)
output = ''
curr_output = ''
for t in stream_generate(self.model, self.tokenizer, prompt, max_tokens=self.gen_kwargs['max_new_tokens']):
output += t
curr_output += t
if curr_output.endswith(('.', '?', '!', '<|end|>')):
yield (curr_output.replace('<|end|>', ''), language_code)
curr_output = ''
generated_text = output.replace('<|end|>', '')
torch.mps.empty_cache()
self.chat.append({'role': 'assistant', 'content': generated_text})
# File: speech-to-speech-main/STT/lightning_whisper_mlx_handler.py
import logging
from time import perf_counter
from baseHandler import BaseHandler
from lightning_whisper_mlx import LightningWhisperMLX
import numpy as np
from rich.console import Console
from copy import copy
import torch
logger = logging.getLogger(__name__)
console = Console()
SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'zh', 'ja', 'ko']
class LightningWhisperSTTHandler(BaseHandler):
def setup(self, model_name='distil-large-v3', device='mps', torch_dtype='float16', compile_mode=None, language=None, gen_kwargs={}):
if len(model_name.split('/')) > 1:
model_name = model_name.split('/')[-1]
self.device = device
self.model = LightningWhisperMLX(model=model_name, batch_size=6, quant=None)
self.start_language = language
self.last_language = language
self.warmup()
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
n_steps = 1
dummy_input = np.array([0] * 512)
for _ in range(n_steps):
_ = self.model.transcribe(dummy_input)['text'].strip()
def process(self, spoken_prompt):
logger.debug('infering whisper...')
global pipeline_start
pipeline_start = perf_counter()
if self.start_language != 'auto':
transcription_dict = self.model.transcribe(spoken_prompt, language=self.start_language)
else:
transcription_dict = self.model.transcribe(spoken_prompt)
language_code = transcription_dict['language']
if language_code not in SUPPORTED_LANGUAGES:
logger.warning(f'Whisper detected unsupported language: {language_code}')
if self.last_language in SUPPORTED_LANGUAGES:
transcription_dict = self.model.transcribe(spoken_prompt, language=self.last_language)
else:
transcription_dict = {'text': '', 'language': 'en'}
else:
self.last_language = language_code
pred_text = transcription_dict['text'].strip()
language_code = transcription_dict['language']
torch.mps.empty_cache()
logger.debug('finished whisper inference')
console.print(f'[yellow]USER: {pred_text}')
logger.debug(f'Language Code Whisper: {language_code}')
yield (pred_text, language_code)
# File: speech-to-speech-main/STT/paraformer_handler.py
import logging
from time import perf_counter
from baseHandler import BaseHandler
from funasr import AutoModel
import numpy as np
from rich.console import Console
import torch
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
console = Console()
class ParaformerSTTHandler(BaseHandler):
def setup(self, model_name='paraformer-zh', device='cuda', gen_kwargs={}):
print(model_name)
if len(model_name.split('/')) > 1:
model_name = model_name.split('/')[-1]
self.device = device
self.model = AutoModel(model=model_name, device=device)
self.warmup()
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
n_steps = 1
dummy_input = np.array([0] * 512, dtype=np.float32)
for _ in range(n_steps):
_ = self.model.generate(dummy_input)[0]['text'].strip().replace(' ', '')
def process(self, spoken_prompt):
logger.debug('infering paraformer...')
global pipeline_start
pipeline_start = perf_counter()
pred_text = self.model.generate(spoken_prompt)[0]['text'].strip().replace(' ', '')
torch.mps.empty_cache()
logger.debug('finished paraformer inference')
console.print(f'[yellow]USER: {pred_text}')
yield pred_text
# File: speech-to-speech-main/STT/whisper_stt_handler.py
from time import perf_counter
from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq
import torch
from copy import copy
from baseHandler import BaseHandler
from rich.console import Console
import logging
logger = logging.getLogger(__name__)
console = Console()
SUPPORTED_LANGUAGES = ['en', 'fr', 'es', 'zh', 'ja', 'ko']
class WhisperSTTHandler(BaseHandler):
def setup(self, model_name='distil-whisper/distil-large-v3', device='cuda', torch_dtype='float16', compile_mode=None, language=None, gen_kwargs={}):
self.device = device
self.torch_dtype = getattr(torch, torch_dtype)
self.compile_mode = compile_mode
self.gen_kwargs = gen_kwargs
if language == 'auto':
language = None
self.last_language = language
if self.last_language is not None:
self.gen_kwargs['language'] = self.last_language
self.processor = AutoProcessor.from_pretrained(model_name)
self.model = AutoModelForSpeechSeq2Seq.from_pretrained(model_name, torch_dtype=self.torch_dtype).to(device)
if self.compile_mode:
self.model.generation_config.cache_implementation = 'static'
self.model.forward = torch.compile(self.model.forward, mode=self.compile_mode, fullgraph=True)
self.warmup()
def prepare_model_inputs(self, spoken_prompt):
input_features = self.processor(spoken_prompt, sampling_rate=16000, return_tensors='pt').input_features
input_features = input_features.to(self.device, dtype=self.torch_dtype)
return input_features
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
n_steps = 1 if self.compile_mode == 'default' else 2
dummy_input = torch.randn((1, self.model.config.num_mel_bins, 3000), dtype=self.torch_dtype, device=self.device)
if self.compile_mode not in (None, 'default'):
warmup_gen_kwargs = {'min_new_tokens': self.gen_kwargs['max_new_tokens'], 'max_new_tokens': self.gen_kwargs['max_new_tokens'], **self.gen_kwargs}
else:
warmup_gen_kwargs = self.gen_kwargs
if self.device == 'cuda':
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
torch.cuda.synchronize()
start_event.record()
for _ in range(n_steps):
_ = self.model.generate(dummy_input, **warmup_gen_kwargs)
if self.device == 'cuda':
end_event.record()
torch.cuda.synchronize()
logger.info(f'{self.__class__.__name__}: warmed up! time: {start_event.elapsed_time(end_event) * 0.001:.3f} s')
def process(self, spoken_prompt):
logger.debug('infering whisper...')
global pipeline_start
pipeline_start = perf_counter()
input_features = self.prepare_model_inputs(spoken_prompt)
pred_ids = self.model.generate(input_features, **self.gen_kwargs)
language_code = self.processor.tokenizer.decode(pred_ids[0, 1])[2:-2]
if language_code not in SUPPORTED_LANGUAGES:
logger.warning('Whisper detected unsupported language:', language_code)
gen_kwargs = copy(self.gen_kwargs)
gen_kwargs['language'] = self.last_language
language_code = self.last_language
pred_ids = self.model.generate(input_features, **gen_kwargs)
else:
self.last_language = language_code
pred_text = self.processor.batch_decode(pred_ids, skip_special_tokens=True, decode_with_timestamps=False)[0]
language_code = self.processor.tokenizer.decode(pred_ids[0, 1])[2:-2]
logger.debug('finished whisper inference')
console.print(f'[yellow]USER: {pred_text}')
logger.debug(f'Language Code Whisper: {language_code}')
yield (pred_text, language_code)
# File: speech-to-speech-main/TTS/chatTTS_handler.py
import ChatTTS
import logging
from baseHandler import BaseHandler
import librosa
import numpy as np
from rich.console import Console
import torch
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
console = Console()
class ChatTTSHandler(BaseHandler):
def setup(self, should_listen, device='cuda', gen_kwargs={}, stream=True, chunk_size=512):
self.should_listen = should_listen
self.device = device
self.model = ChatTTS.Chat()
self.model.load(compile=False)
self.chunk_size = chunk_size
self.stream = stream
rnd_spk_emb = self.model.sample_random_speaker()
self.params_infer_code = ChatTTS.Chat.InferCodeParams(spk_emb=rnd_spk_emb)
self.warmup()
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
_ = self.model.infer('text')
def process(self, llm_sentence):
console.print(f'[green]ASSISTANT: {llm_sentence}')
if self.device == 'mps':
import time
start = time.time()
torch.mps.synchronize()
torch.mps.empty_cache()
_ = time.time() - start
wavs_gen = self.model.infer(llm_sentence, params_infer_code=self.params_infer_code, stream=self.stream)
if self.stream:
wavs = [np.array([])]
for gen in wavs_gen:
if gen[0] is None or len(gen[0]) == 0:
self.should_listen.set()
return
audio_chunk = librosa.resample(gen[0], orig_sr=24000, target_sr=16000)
audio_chunk = (audio_chunk * 32768).astype(np.int16)[0]
while len(audio_chunk) > self.chunk_size:
yield audio_chunk[:self.chunk_size]
audio_chunk = audio_chunk[self.chunk_size:]
yield np.pad(audio_chunk, (0, self.chunk_size - len(audio_chunk)))
else:
wavs = wavs_gen
if len(wavs[0]) == 0:
self.should_listen.set()
return
audio_chunk = librosa.resample(wavs[0], orig_sr=24000, target_sr=16000)
audio_chunk = (audio_chunk * 32768).astype(np.int16)
for i in range(0, len(audio_chunk), self.chunk_size):
yield np.pad(audio_chunk[i:i + self.chunk_size], (0, self.chunk_size - len(audio_chunk[i:i + self.chunk_size])))
self.should_listen.set()
# File: speech-to-speech-main/TTS/melo_handler.py
from melo.api import TTS
import logging
from baseHandler import BaseHandler
import librosa
import numpy as np
from rich.console import Console
import torch
logger = logging.getLogger(__name__)
console = Console()
WHISPER_LANGUAGE_TO_MELO_LANGUAGE = {'en': 'EN_NEWEST', 'fr': 'FR', 'es': 'ES', 'zh': 'ZH', 'ja': 'JP', 'ko': 'KR'}
WHISPER_LANGUAGE_TO_MELO_SPEAKER = {'en': 'EN-Newest', 'fr': 'FR', 'es': 'ES', 'zh': 'ZH', 'ja': 'JP', 'ko': 'KR'}
class MeloTTSHandler(BaseHandler):
def setup(self, should_listen, device='mps', language='en', speaker_to_id='en', gen_kwargs={}, blocksize=512):
self.should_listen = should_listen
self.device = device
self.language = language
self.model = TTS(language=WHISPER_LANGUAGE_TO_MELO_LANGUAGE[self.language], device=device)
self.speaker_id = self.model.hps.data.spk2id[WHISPER_LANGUAGE_TO_MELO_SPEAKER[speaker_to_id]]
self.blocksize = blocksize
self.warmup()
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
_ = self.model.tts_to_file('text', self.speaker_id, quiet=True)
def process(self, llm_sentence):
language_code = None
if isinstance(llm_sentence, tuple):
(llm_sentence, language_code) = llm_sentence
console.print(f'[green]ASSISTANT: {llm_sentence}')
if language_code is not None and self.language != language_code:
try:
self.model = TTS(language=WHISPER_LANGUAGE_TO_MELO_LANGUAGE[language_code], device=self.device)
self.speaker_id = self.model.hps.data.spk2id[WHISPER_LANGUAGE_TO_MELO_SPEAKER[language_code]]
self.language = language_code
except KeyError:
console.print(f'[red]Language {language_code} not supported by Melo. Using {self.language} instead.')
if self.device == 'mps':
import time
start = time.time()
torch.mps.synchronize()
torch.mps.empty_cache()
_ = time.time() - start
try:
audio_chunk = self.model.tts_to_file(llm_sentence, self.speaker_id, quiet=True)
except (AssertionError, RuntimeError) as e:
logger.error(f'Error in MeloTTSHandler: {e}')
audio_chunk = np.array([])
if len(audio_chunk) == 0:
self.should_listen.set()
return
audio_chunk = librosa.resample(audio_chunk, orig_sr=44100, target_sr=16000)
audio_chunk = (audio_chunk * 32768).astype(np.int16)
for i in range(0, len(audio_chunk), self.blocksize):
yield np.pad(audio_chunk[i:i + self.blocksize], (0, self.blocksize - len(audio_chunk[i:i + self.blocksize])))
self.should_listen.set()
# File: speech-to-speech-main/TTS/parler_handler.py
from threading import Thread
from time import perf_counter
from baseHandler import BaseHandler
import numpy as np
import torch
from transformers import AutoTokenizer
from parler_tts import ParlerTTSForConditionalGeneration, ParlerTTSStreamer
import librosa
import logging
from rich.console import Console
from utils.utils import next_power_of_2
from transformers.utils.import_utils import is_flash_attn_2_available
torch._inductor.config.fx_graph_cache = True
torch._dynamo.config.cache_size_limit = 15
logger = logging.getLogger(__name__)
console = Console()
if not is_flash_attn_2_available() and torch.cuda.is_available():
logger.warn('Parler TTS works best with flash attention 2, but is not installed\n Given that CUDA is available in this system, you can install flash attention 2 with `uv pip install flash-attn --no-build-isolation`')
class ParlerTTSHandler(BaseHandler):
def setup(self, should_listen, model_name='ylacombe/parler-tts-mini-jenny-30H', device='cuda', torch_dtype='float16', compile_mode=None, gen_kwargs={}, max_prompt_pad_length=8, description='A female speaker with a slightly low-pitched voice delivers her words quite expressively, in a very confined sounding environment with clear audio quality. She speaks very fast.', play_steps_s=1, blocksize=512):
self.should_listen = should_listen
self.device = device
self.torch_dtype = getattr(torch, torch_dtype)
self.gen_kwargs = gen_kwargs
self.compile_mode = compile_mode
self.max_prompt_pad_length = max_prompt_pad_length
self.description = description
self.description_tokenizer = AutoTokenizer.from_pretrained(model_name)
self.prompt_tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = ParlerTTSForConditionalGeneration.from_pretrained(model_name, torch_dtype=self.torch_dtype).to(device)
framerate = self.model.audio_encoder.config.frame_rate
self.play_steps = int(framerate * play_steps_s)
self.blocksize = blocksize
if self.compile_mode not in (None, 'default'):
logger.warning("Torch compilation modes that captures CUDA graphs are not yet compatible with the STT part. Reverting to 'default'")
self.compile_mode = 'default'
if self.compile_mode:
self.model.generation_config.cache_implementation = 'static'
self.model.forward = torch.compile(self.model.forward, mode=self.compile_mode, fullgraph=True)
self.warmup()
def prepare_model_inputs(self, prompt, max_length_prompt=50, pad=False):
pad_args_prompt = {'padding': 'max_length', 'max_length': max_length_prompt} if pad else {}
tokenized_description = self.description_tokenizer(self.description, return_tensors='pt')
input_ids = tokenized_description.input_ids.to(self.device)
attention_mask = tokenized_description.attention_mask.to(self.device)
tokenized_prompt = self.prompt_tokenizer(prompt, return_tensors='pt', **pad_args_prompt)
prompt_input_ids = tokenized_prompt.input_ids.to(self.device)
prompt_attention_mask = tokenized_prompt.attention_mask.to(self.device)
gen_kwargs = {'input_ids': input_ids, 'attention_mask': attention_mask, 'prompt_input_ids': prompt_input_ids, 'prompt_attention_mask': prompt_attention_mask, **self.gen_kwargs}
return gen_kwargs
def warmup(self):
logger.info(f'Warming up {self.__class__.__name__}')
if self.device == 'cuda':
start_event = torch.cuda.Event(enable_timing=True)
end_event = torch.cuda.Event(enable_timing=True)
n_steps = 1 if self.compile_mode == 'default' else 2
if self.device == 'cuda':
torch.cuda.synchronize()
start_event.record()
if self.compile_mode:
pad_lengths = [2 ** i for i in range(2, self.max_prompt_pad_length)]
for pad_length in pad_lengths[::-1]:
model_kwargs = self.prepare_model_inputs('dummy prompt', max_length_prompt=pad_length, pad=True)
for _ in range(n_steps):
_ = self.model.generate(**model_kwargs)
logger.info(f'Warmed up length {pad_length} tokens!')
else:
model_kwargs = self.prepare_model_inputs('dummy prompt')
for _ in range(n_steps):
_ = self.model.generate(**model_kwargs)
if self.device == 'cuda':
end_event.record()
torch.cuda.synchronize()
logger.info(f'{self.__class__.__name__}: warmed up! time: {start_event.elapsed_time(end_event) * 0.001:.3f} s')
def process(self, llm_sentence):
if isinstance(llm_sentence, tuple):
(llm_sentence, _) = llm_sentence
console.print(f'[green]ASSISTANT: {llm_sentence}')
nb_tokens = len(self.prompt_tokenizer(llm_sentence).input_ids)
pad_args = {}
if self.compile_mode:
pad_length = next_power_of_2(nb_tokens)
logger.debug(f'padding to {pad_length}')
pad_args['pad'] = True
pad_args['max_length_prompt'] = pad_length
tts_gen_kwargs = self.prepare_model_inputs(llm_sentence, **pad_args)
streamer = ParlerTTSStreamer(self.model, device=self.device, play_steps=self.play_steps)
tts_gen_kwargs = {'streamer': streamer, **tts_gen_kwargs}
torch.manual_seed(0)
thread = Thread(target=self.model.generate, kwargs=tts_gen_kwargs)
thread.start()
for (i, audio_chunk) in enumerate(streamer):
global pipeline_start
if i == 0 and 'pipeline_start' in globals():
logger.info(f'Time to first audio: {perf_counter() - pipeline_start:.3f}')
audio_chunk = librosa.resample(audio_chunk, orig_sr=44100, target_sr=16000)
audio_chunk = (audio_chunk * 32768).astype(np.int16)
for i in range(0, len(audio_chunk), self.blocksize):
yield np.pad(audio_chunk[i:i + self.blocksize], (0, self.blocksize - len(audio_chunk[i:i + self.blocksize])))
self.should_listen.set()
# File: speech-to-speech-main/VAD/vad_handler.py
import torchaudio
from VAD.vad_iterator import VADIterator
from baseHandler import BaseHandler
import numpy as np
import torch
from rich.console import Console
from utils.utils import int2float
from df.enhance import enhance, init_df
import logging
logger = logging.getLogger(__name__)
console = Console()
class VADHandler(BaseHandler):
def setup(self, should_listen, thresh=0.3, sample_rate=16000, min_silence_ms=1000, min_speech_ms=500, max_speech_ms=float('inf'), speech_pad_ms=30, audio_enhancement=False):
self.should_listen = should_listen
self.sample_rate = sample_rate
self.min_silence_ms = min_silence_ms
self.min_speech_ms = min_speech_ms
self.max_speech_ms = max_speech_ms
(self.model, _) = torch.hub.load('snakers4/silero-vad', 'silero_vad')
self.iterator = VADIterator(self.model, threshold=thresh, sampling_rate=sample_rate, min_silence_duration_ms=min_silence_ms, speech_pad_ms=speech_pad_ms)
self.audio_enhancement = audio_enhancement
if audio_enhancement:
(self.enhanced_model, self.df_state, _) = init_df()
def process(self, audio_chunk):
audio_int16 = np.frombuffer(audio_chunk, dtype=np.int16)
audio_float32 = int2float(audio_int16)
vad_output = self.iterator(torch.from_numpy(audio_float32))
if vad_output is not None and len(vad_output) != 0:
logger.debug('VAD: end of speech detected')
array = torch.cat(vad_output).cpu().numpy()
duration_ms = len(array) / self.sample_rate * 1000
if duration_ms < self.min_speech_ms or duration_ms > self.max_speech_ms:
logger.debug(f'audio input of duration: {len(array) / self.sample_rate}s, skipping')
else:
self.should_listen.clear()
logger.debug('Stop listening')
if self.audio_enhancement:
if self.sample_rate != self.df_state.sr():
audio_float32 = torchaudio.functional.resample(torch.from_numpy(array), orig_freq=self.sample_rate, new_freq=self.df_state.sr())
enhanced = enhance(self.enhanced_model, self.df_state, audio_float32.unsqueeze(0))
enhanced = torchaudio.functional.resample(enhanced, orig_freq=self.df_state.sr(), new_freq=self.sample_rate)
else:
enhanced = enhance(self.enhanced_model, self.df_state, audio_float32)
array = enhanced.numpy().squeeze()
yield array
@property
def min_time_to_debug(self):
return 1e-05
# File: speech-to-speech-main/VAD/vad_iterator.py
import torch
class VADIterator:
def __init__(self, model, threshold: float=0.5, sampling_rate: int=16000, min_silence_duration_ms: int=100, speech_pad_ms: int=30):
self.model = model
self.threshold = threshold
self.sampling_rate = sampling_rate
self.is_speaking = False
self.buffer = []
if sampling_rate not in [8000, 16000]:
raise ValueError('VADIterator does not support sampling rates other than [8000, 16000]')
self.min_silence_samples = sampling_rate * min_silence_duration_ms / 1000
self.speech_pad_samples = sampling_rate * speech_pad_ms / 1000
self.reset_states()
def reset_states(self):
self.model.reset_states()
self.triggered = False
self.temp_end = 0
self.current_sample = 0
@torch.no_grad()
def __call__(self, x):
if not torch.is_tensor(x):
try:
x = torch.Tensor(x)
except Exception:
raise TypeError('Audio cannot be casted to tensor. Cast it manually')
window_size_samples = len(x[0]) if x.dim() == 2 else len(x)
self.current_sample += window_size_samples
speech_prob = self.model(x, self.sampling_rate).item()
if speech_prob >= self.threshold and self.temp_end:
self.temp_end = 0
if speech_prob >= self.threshold and (not self.triggered):
self.triggered = True
return None
if speech_prob < self.threshold - 0.15 and self.triggered:
if not self.temp_end:
self.temp_end = self.current_sample
if self.current_sample - self.temp_end < self.min_silence_samples:
return None
else:
self.temp_end = 0
self.triggered = False
spoken_utterance = self.buffer
self.buffer = []
return spoken_utterance
if self.triggered:
self.buffer.append(x)
return None
# File: speech-to-speech-main/arguments_classes/chat_tts_arguments.py
from dataclasses import dataclass, field
@dataclass
class ChatTTSHandlerArguments:
chat_tts_stream: bool = field(default=True, metadata={'help': "The tts mode is stream Default is 'stream'."})
chat_tts_device: str = field(default='cuda', metadata={'help': "The device to be used for speech synthesis. Default is 'cuda'."})
chat_tts_chunk_size: int = field(default=512, metadata={'help': 'Sets the size of the audio data chunk processed per cycle, balancing playback latency and CPU load.. Default is 512。.'})
# File: speech-to-speech-main/arguments_classes/language_model_arguments.py
from dataclasses import dataclass, field
@dataclass
class LanguageModelHandlerArguments:
lm_model_name: str = field(default='HuggingFaceTB/SmolLM-360M-Instruct', metadata={'help': "The pretrained language model to use. Default is 'microsoft/Phi-3-mini-4k-instruct'."})
lm_device: str = field(default='cuda', metadata={'help': "The device type on which the model will run. Default is 'cuda' for GPU acceleration."})
lm_torch_dtype: str = field(default='float16', metadata={'help': 'The PyTorch data type for the model and input tensors. One of `float32` (full-precision), `float16` or `bfloat16` (both half-precision).'})
user_role: str = field(default='user', metadata={'help': "Role assigned to the user in the chat context. Default is 'user'."})
init_chat_role: str = field(default='system', metadata={'help': "Initial role for setting up the chat context. Default is 'system'."})
init_chat_prompt: str = field(default='You are a helpful and friendly AI assistant. You are polite, respectful, and aim to provide concise responses of less than 20 words.', metadata={'help': "The initial chat prompt to establish context for the language model. Default is 'You are a helpful AI assistant.'"})
lm_gen_max_new_tokens: int = field(default=128, metadata={'help': 'Maximum number of new tokens to generate in a single completion. Default is 128.'})
lm_gen_min_new_tokens: int = field(default=0, metadata={'help': 'Minimum number of new tokens to generate in a single completion. Default is 0.'})
lm_gen_temperature: float = field(default=0.0, metadata={'help': 'Controls the randomness of the output. Set to 0.0 for deterministic (repeatable) outputs. Default is 0.0.'})
lm_gen_do_sample: bool = field(default=False, metadata={'help': 'Whether to use sampling; set this to False for deterministic outputs. Default is False.'})
chat_size: int = field(default=2, metadata={'help': 'Number of interactions assitant-user to keep for the chat. None for no limitations.'})
# File: speech-to-speech-main/arguments_classes/melo_tts_arguments.py
from dataclasses import dataclass, field
@dataclass
class MeloTTSHandlerArguments:
melo_language: str = field(default='en', metadata={'help': "The language of the text to be synthesized. Default is 'EN_NEWEST'."})
melo_device: str = field(default='auto', metadata={'help': "The device to be used for speech synthesis. Default is 'auto'."})
melo_speaker_to_id: str = field(default='en', metadata={'help': "Mapping of speaker names to speaker IDs. Default is ['EN-Newest']."})
# File: speech-to-speech-main/arguments_classes/mlx_language_model_arguments.py
from dataclasses import dataclass, field
@dataclass
class MLXLanguageModelHandlerArguments:
mlx_lm_model_name: str = field(default='mlx-community/SmolLM-360M-Instruct', metadata={'help': "The pretrained language model to use. Default is 'microsoft/Phi-3-mini-4k-instruct'."})
mlx_lm_device: str = field(default='mps', metadata={'help': "The device type on which the model will run. Default is 'cuda' for GPU acceleration."})
mlx_lm_torch_dtype: str = field(default='float16', metadata={'help': 'The PyTorch data type for the model and input tensors. One of `float32` (full-precision), `float16` or `bfloat16` (both half-precision).'})
mlx_lm_user_role: str = field(default='user', metadata={'help': "Role assigned to the user in the chat context. Default is 'user'."})
mlx_lm_init_chat_role: str = field(default='system', metadata={'help': "Initial role for setting up the chat context. Default is 'system'."})
mlx_lm_init_chat_prompt: str = field(default='You are a helpful and friendly AI assistant. You are polite, respectful, and aim to provide concise responses of less than 20 words.', metadata={'help': "The initial chat prompt to establish context for the language model. Default is 'You are a helpful AI assistant.'"})
mlx_lm_gen_max_new_tokens: int = field(default=128, metadata={'help': 'Maximum number of new tokens to generate in a single completion. Default is 128.'})
mlx_lm_gen_temperature: float = field(default=0.0, metadata={'help': 'Controls the randomness of the output. Set to 0.0 for deterministic (repeatable) outputs. Default is 0.0.'})
mlx_lm_gen_do_sample: bool = field(default=False, metadata={'help': 'Whether to use sampling; set this to False for deterministic outputs. Default is False.'})
mlx_lm_chat_size: int = field(default=2, metadata={'help': 'Number of interactions assitant-user to keep for the chat. None for no limitations.'})
# File: speech-to-speech-main/arguments_classes/module_arguments.py
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class ModuleArguments:
device: Optional[str] = field(default=None, metadata={'help': 'If specified, overrides the device for all handlers.'})
mode: Optional[str] = field(default='socket', metadata={'help': "The mode to run the pipeline in. Either 'local' or 'socket'. Default is 'socket'."})
local_mac_optimal_settings: bool = field(default=False, metadata={'help': 'If specified, sets the optimal settings for Mac OS. Hence whisper-mlx, MLX LM and MeloTTS will be used.'})
stt: Optional[str] = field(default='whisper', metadata={'help': "The STT to use. Either 'whisper', 'whisper-mlx', and 'paraformer'. Default is 'whisper'."})
llm: Optional[str] = field(default='transformers', metadata={'help': "The LLM to use. Either 'transformers' or 'mlx-lm'. Default is 'transformers'"})
tts: Optional[str] = field(default='parler', metadata={'help': "The TTS to use. Either 'parler', 'melo', or 'chatTTS'. Default is 'parler'"})
log_level: str = field(default='info', metadata={'help': 'Provide logging level. Example --log_level debug, default=warning.'})
# File: speech-to-speech-main/arguments_classes/paraformer_stt_arguments.py
from dataclasses import dataclass, field
@dataclass
class ParaformerSTTHandlerArguments:
paraformer_stt_model_name: str = field(default='paraformer-zh', metadata={'help': "The pretrained model to use. Default is 'paraformer-zh'. Can be choose from https://github.com/modelscope/FunASR"})
paraformer_stt_device: str = field(default='cuda', metadata={'help': "The device type on which the model will run. Default is 'cuda' for GPU acceleration."})
# File: speech-to-speech-main/arguments_classes/parler_tts_arguments.py
from dataclasses import dataclass, field
@dataclass
class ParlerTTSHandlerArguments:
tts_model_name: str = field(default='ylacombe/parler-tts-mini-jenny-30H', metadata={'help': "The pretrained TTS model to use. Default is 'ylacombe/parler-tts-mini-jenny-30H'."})
tts_device: str = field(default='cuda', metadata={'help': "The device type on which the model will run. Default is 'cuda' for GPU acceleration."})
tts_torch_dtype: str = field(default='float16', metadata={'help': 'The PyTorch data type for the model and input tensors. One of `float32` (full-precision), `float16` or `bfloat16` (both half-precision).'})
tts_compile_mode: str = field(default=None, metadata={'help': "Compile mode for torch compile. Either 'default', 'reduce-overhead' and 'max-autotune'. Default is None (no compilation)"})
tts_gen_min_new_tokens: int = field(default=64, metadata={'help': 'Maximum number of new tokens to generate in a single completion. Default is 10, which corresponds to ~0.1 secs'})
tts_gen_max_new_tokens: int = field(default=512, metadata={'help': 'Maximum number of new tokens to generate in a single completion. Default is 256, which corresponds to ~6 secs'})
description: str = field(default='A female speaker with a slightly low-pitched voice delivers her words quite expressively, in a very confined sounding environment with clear audio quality. She speaks very fast.', metadata={'help': "Description of the speaker's voice and speaking style to guide the TTS model."})
play_steps_s: float = field(default=1.0, metadata={'help': 'The time interval in seconds for playing back the generated speech in steps. Default is 0.5 seconds.'})
max_prompt_pad_length: int = field(default=8, metadata={'help': 'When using compilation, the prompt as to be padded to closest power of 2. This parameters sets the maximun power of 2 possible.'})
# File: speech-to-speech-main/arguments_classes/socket_receiver_arguments.py
from dataclasses import dataclass, field
@dataclass
class SocketReceiverArguments:
recv_host: str = field(default='localhost', metadata={'help': "The host IP ddress for the socket connection. Default is '0.0.0.0' which binds to all available interfaces on the host machine."})
recv_port: int = field(default=12345, metadata={'help': 'The port number on which the socket server listens. Default is 12346.'})
chunk_size: int = field(default=1024, metadata={'help': 'The size of each data chunk to be sent or received over the socket. Default is 1024 bytes.'})
# File: speech-to-speech-main/arguments_classes/socket_sender_arguments.py
from dataclasses import dataclass, field
@dataclass
class SocketSenderArguments:
send_host: str = field(default='localhost', metadata={'help': "The host IP address for the socket connection. Default is '0.0.0.0' which binds to all available interfaces on the host machine."})
send_port: int = field(default=12346, metadata={'help': 'The port number on which the socket server listens. Default is 12346.'})
# File: speech-to-speech-main/arguments_classes/vad_arguments.py
from dataclasses import dataclass, field
@dataclass
class VADHandlerArguments:
thresh: float = field(default=0.3, metadata={'help': 'The threshold value for voice activity detection (VAD). Values typically range from 0 to 1, with higher values requiring higher confidence in speech detection.'})
sample_rate: int = field(default=16000, metadata={'help': 'The sample rate of the audio in Hertz. Default is 16000 Hz, which is a common setting for voice audio.'})
min_silence_ms: int = field(default=250, metadata={'help': 'Minimum length of silence intervals to be used for segmenting speech. Measured in milliseconds. Default is 250 ms.'})
min_speech_ms: int = field(default=500, metadata={'help': 'Minimum length of speech segments to be considered valid speech. Measured in milliseconds. Default is 500 ms.'})
max_speech_ms: float = field(default=float('inf'), metadata={'help': 'Maximum length of continuous speech before forcing a split. Default is infinite, allowing for uninterrupted speech segments.'})
speech_pad_ms: int = field(default=500, metadata={'help': 'Amount of padding added to the beginning and end of detected speech segments. Measured in milliseconds. Default is 250 ms.'})
audio_enhancement: bool = field(default=False, metadata={'help': 'improves sound quality by applying techniques like noise reduction, equalization, and echo cancellation. Default is False.'})
# File: speech-to-speech-main/arguments_classes/whisper_stt_arguments.py
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class WhisperSTTHandlerArguments:
stt_model_name: str = field(default='distil-whisper/distil-large-v3', metadata={'help': "The pretrained Whisper model to use. Default is 'distil-whisper/distil-large-v3'."})
stt_device: str = field(default='cuda', metadata={'help': "The device type on which the model will run. Default is 'cuda' for GPU acceleration."})
stt_torch_dtype: str = field(default='float16', metadata={'help': 'The PyTorch data type for the model and input tensors. One of `float32` (full-precision), `float16` or `bfloat16` (both half-precision).'})
stt_compile_mode: str = field(default=None, metadata={'help': "Compile mode for torch compile. Either 'default', 'reduce-overhead' and 'max-autotune'. Default is None (no compilation)"})
stt_gen_max_new_tokens: int = field(default=128, metadata={'help': 'The maximum number of new tokens to generate. Default is 128.'})
stt_gen_num_beams: int = field(default=1, metadata={'help': 'The number of beams for beam search. Default is 1, implying greedy decoding.'})
stt_gen_return_timestamps: bool = field(default=False, metadata={'help': 'Whether to return timestamps with transcriptions. Default is False.'})
stt_gen_task: str = field(default='transcribe', metadata={'help': "The task to perform, typically 'transcribe' for transcription. Default is 'transcribe'."})
language: Optional[str] = field(default='en', metadata={'help': "The language for the conversation. \n Choose between 'en' (english), 'fr' (french), 'es' (spanish), \n 'zh' (chinese), 'ko' (korean), 'ja' (japanese), or 'None'.\n If using 'auto', the language is automatically detected and can\n change during the conversation. Default is 'en'."})
# File: speech-to-speech-main/baseHandler.py
from time import perf_counter
import logging
logger = logging.getLogger(__name__)
class BaseHandler:
def __init__(self, stop_event, queue_in, queue_out, setup_args=(), setup_kwargs={}):
self.stop_event = stop_event
self.queue_in = queue_in
self.queue_out = queue_out
self.setup(*setup_args, **setup_kwargs)
self._times = []
def setup(self):
pass
def process(self):
raise NotImplementedError
def run(self):
while not self.stop_event.is_set():
input = self.queue_in.get()
if isinstance(input, bytes) and input == b'END':
logger.debug('Stopping thread')
break
start_time = perf_counter()
for output in self.process(input):
self._times.append(perf_counter() - start_time)
if self.last_time > self.min_time_to_debug:
logger.debug(f'{self.__class__.__name__}: {self.last_time: .3f} s')
self.queue_out.put(output)
start_time = perf_counter()
self.cleanup()
self.queue_out.put(b'END')
@property
def last_time(self):
return self._times[-1]
@property
def min_time_to_debug(self):
return 0.001
def cleanup(self):
pass
# File: speech-to-speech-main/connections/local_audio_streamer.py
import threading
import sounddevice as sd
import numpy as np
import time
import logging
logger = logging.getLogger(__name__)
class LocalAudioStreamer:
def __init__(self, input_queue, output_queue, list_play_chunk_size=512):
self.list_play_chunk_size = list_play_chunk_size
self.stop_event = threading.Event()
self.input_queue = input_queue
self.output_queue = output_queue
def run(self):
def callback(indata, outdata, frames, time, status):
if self.output_queue.empty():
self.input_queue.put(indata.copy())
outdata[:] = 0 * outdata
else:
outdata[:] = self.output_queue.get()[:, np.newaxis]
logger.debug('Available devices:')
logger.debug(sd.query_devices())
with sd.Stream(samplerate=16000, dtype='int16', channels=1, callback=callback, blocksize=self.list_play_chunk_size):
logger.info('Starting local audio stream')
while not self.stop_event.is_set():
time.sleep(0.001)
print('Stopping recording')
# File: speech-to-speech-main/connections/socket_receiver.py
import socket
from rich.console import Console
import logging
logger = logging.getLogger(__name__)
console = Console()
class SocketReceiver:
def __init__(self, stop_event, queue_out, should_listen, host='0.0.0.0', port=12345, chunk_size=1024):
self.stop_event = stop_event
self.queue_out = queue_out
self.should_listen = should_listen
self.chunk_size = chunk_size
self.host = host
self.port = port
def receive_full_chunk(self, conn, chunk_size):
data = b''
while len(data) < chunk_size:
packet = conn.recv(chunk_size - len(data))
if not packet:
return None
data += packet
return data
def run(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.host, self.port))
self.socket.listen(1)
logger.info('Receiver waiting to be connected...')
(self.conn, _) = self.socket.accept()
logger.info('receiver connected')
self.should_listen.set()
while not self.stop_event.is_set():
audio_chunk = self.receive_full_chunk(self.conn, self.chunk_size)
if audio_chunk is None:
self.queue_out.put(b'END')
break
if self.should_listen.is_set():
self.queue_out.put(audio_chunk)
self.conn.close()
logger.info('Receiver closed')
# File: speech-to-speech-main/connections/socket_sender.py
import socket
from rich.console import Console
import logging
logger = logging.getLogger(__name__)
console = Console()
class SocketSender:
def __init__(self, stop_event, queue_in, host='0.0.0.0', port=12346):
self.stop_event = stop_event
self.queue_in = queue_in
self.host = host
self.port = port
def run(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.host, self.port))
self.socket.listen(1)
logger.info('Sender waiting to be connected...')
(self.conn, _) = self.socket.accept()
logger.info('sender connected')
while not self.stop_event.is_set():
audio_chunk = self.queue_in.get()
self.conn.sendall(audio_chunk)
if isinstance(audio_chunk, bytes) and audio_chunk == b'END':
break
self.conn.close()
logger.info('Sender closed')
# File: speech-to-speech-main/listen_and_play.py
import socket
import threading
from queue import Queue
from dataclasses import dataclass, field
import sounddevice as sd
from transformers import HfArgumentParser
@dataclass
class ListenAndPlayArguments:
send_rate: int = field(default=16000, metadata={'help': 'In Hz. Default is 16000.'})
recv_rate: int = field(default=16000, metadata={'help': 'In Hz. Default is 16000.'})
list_play_chunk_size: int = field(default=1024, metadata={'help': 'The size of data chunks (in bytes). Default is 1024.'})
host: str = field(default='localhost', metadata={'help': "The hostname or IP address for listening and playing. Default is 'localhost'."})
send_port: int = field(default=12345, metadata={'help': 'The network port for sending data. Default is 12345.'})
recv_port: int = field(default=12346, metadata={'help': 'The network port for receiving data. Default is 12346.'})
def listen_and_play(send_rate=16000, recv_rate=44100, list_play_chunk_size=1024, host='localhost', send_port=12345, recv_port=12346):
send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
send_socket.connect((host, send_port))
recv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
recv_socket.connect((host, recv_port))
print('Recording and streaming...')
stop_event = threading.Event()
recv_queue = Queue()
send_queue = Queue()
def callback_recv(outdata, frames, time, status):
if not recv_queue.empty():
data = recv_queue.get()
outdata[:len(data)] = data
outdata[len(data):] = b'\x00' * (len(outdata) - len(data))
else:
outdata[:] = b'\x00' * len(outdata)
def callback_send(indata, frames, time, status):
if recv_queue.empty():
data = bytes(indata)
send_queue.put(data)
def send(stop_event, send_queue):
while not stop_event.is_set():
data = send_queue.get()
send_socket.sendall(data)
def recv(stop_event, recv_queue):
def receive_full_chunk(conn, chunk_size):
data = b''
while len(data) < chunk_size:
packet = conn.recv(chunk_size - len(data))
if not packet:
return None
data += packet
return data
while not stop_event.is_set():
data = receive_full_chunk(recv_socket, list_play_chunk_size * 2)
if data:
recv_queue.put(data)
try:
send_stream = sd.RawInputStream(samplerate=send_rate, channels=1, dtype='int16', blocksize=list_play_chunk_size, callback=callback_send)
recv_stream = sd.RawOutputStream(samplerate=recv_rate, channels=1, dtype='int16', blocksize=list_play_chunk_size, callback=callback_recv)
threading.Thread(target=send_stream.start).start()
threading.Thread(target=recv_stream.start).start()
send_thread = threading.Thread(target=send, args=(stop_event, send_queue))
send_thread.start()
recv_thread = threading.Thread(target=recv, args=(stop_event, recv_queue))
recv_thread.start()
input('Press Enter to stop...')
except KeyboardInterrupt:
print('Finished streaming.')
finally:
stop_event.set()
recv_thread.join()
send_thread.join()
send_socket.close()
recv_socket.close()
print('Connection closed.')
if __name__ == '__main__':
parser = HfArgumentParser((ListenAndPlayArguments,))
(listen_and_play_kwargs,) = parser.parse_args_into_dataclasses()
listen_and_play(**vars(listen_and_play_kwargs))
# File: speech-to-speech-main/s2s_pipeline.py
import logging
import os
import sys
from copy import copy
from pathlib import Path
from queue import Queue
from threading import Event
from typing import Optional
from sys import platform
from VAD.vad_handler import VADHandler
from arguments_classes.chat_tts_arguments import ChatTTSHandlerArguments
from arguments_classes.language_model_arguments import LanguageModelHandlerArguments
from arguments_classes.mlx_language_model_arguments import MLXLanguageModelHandlerArguments
from arguments_classes.module_arguments import ModuleArguments
from arguments_classes.paraformer_stt_arguments import ParaformerSTTHandlerArguments
from arguments_classes.parler_tts_arguments import ParlerTTSHandlerArguments
from arguments_classes.socket_receiver_arguments import SocketReceiverArguments
from arguments_classes.socket_sender_arguments import SocketSenderArguments
from arguments_classes.vad_arguments import VADHandlerArguments
from arguments_classes.whisper_stt_arguments import WhisperSTTHandlerArguments
from arguments_classes.melo_tts_arguments import MeloTTSHandlerArguments
import torch
import nltk
from rich.console import Console
from transformers import HfArgumentParser
from utils.thread_manager import ThreadManager
try:
nltk.data.find('tokenizers/punkt_tab')
except (LookupError, OSError):
nltk.download('punkt_tab')
try:
nltk.data.find('tokenizers/averaged_perceptron_tagger_eng')
except (LookupError, OSError):
nltk.download('averaged_perceptron_tagger_eng')
CURRENT_DIR = Path(__file__).resolve().parent
os.environ['TORCHINDUCTOR_CACHE_DIR'] = os.path.join(CURRENT_DIR, 'tmp')
console = Console()
logging.getLogger('numba').setLevel(logging.WARNING)
def prepare_args(args, prefix):
gen_kwargs = {}
for key in copy(args.__dict__):
if key.startswith(prefix):
value = args.__dict__.pop(key)
new_key = key[len(prefix) + 1:]
if new_key.startswith('gen_'):
gen_kwargs[new_key[4:]] = value
else:
args.__dict__[new_key] = value
args.__dict__['gen_kwargs'] = gen_kwargs
def main():
parser = HfArgumentParser((ModuleArguments, SocketReceiverArguments, SocketSenderArguments, VADHandlerArguments, WhisperSTTHandlerArguments, ParaformerSTTHandlerArguments, LanguageModelHandlerArguments, MLXLanguageModelHandlerArguments, ParlerTTSHandlerArguments, MeloTTSHandlerArguments, ChatTTSHandlerArguments))
if len(sys.argv) == 2 and sys.argv[1].endswith('.json'):
(module_kwargs, socket_receiver_kwargs, socket_sender_kwargs, vad_handler_kwargs, whisper_stt_handler_kwargs, paraformer_stt_handler_kwargs, language_model_handler_kwargs, mlx_language_model_handler_kwargs, parler_tts_handler_kwargs, melo_tts_handler_kwargs, chat_tts_handler_kwargs) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(module_kwargs, socket_receiver_kwargs, socket_sender_kwargs, vad_handler_kwargs, whisper_stt_handler_kwargs, paraformer_stt_handler_kwargs, language_model_handler_kwargs, mlx_language_model_handler_kwargs, parler_tts_handler_kwargs, melo_tts_handler_kwargs, chat_tts_handler_kwargs) = parser.parse_args_into_dataclasses()
global logger
logging.basicConfig(level=module_kwargs.log_level.upper(), format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
if module_kwargs.log_level == 'debug':
torch._logging.set_logs(graph_breaks=True, recompiles=True, cudagraphs=True)
def optimal_mac_settings(mac_optimal_settings: Optional[str], *handler_kwargs):
if mac_optimal_settings:
for kwargs in handler_kwargs:
if hasattr(kwargs, 'device'):
kwargs.device = 'mps'
if hasattr(kwargs, 'mode'):
kwargs.mode = 'local'
if hasattr(kwargs, 'stt'):
kwargs.stt = 'whisper-mlx'
if hasattr(kwargs, 'llm'):
kwargs.llm = 'mlx-lm'
if hasattr(kwargs, 'tts'):
kwargs.tts = 'melo'
optimal_mac_settings(module_kwargs.local_mac_optimal_settings, module_kwargs)
if platform == 'darwin':
if module_kwargs.device == 'cuda':
raise ValueError("Cannot use CUDA on macOS. Please set the device to 'cpu' or 'mps'.")
if module_kwargs.llm != 'mlx-lm':
logger.warning('For macOS users, it is recommended to use mlx-lm. You can activate it by passing --llm mlx-lm.')
if module_kwargs.tts != 'melo':
logger.warning('If you experiences issues generating the voice, considering setting the tts to melo.')
def overwrite_device_argument(common_device: Optional[str], *handler_kwargs):
if common_device:
for kwargs in handler_kwargs:
if hasattr(kwargs, 'lm_device'):
kwargs.lm_device = common_device
if hasattr(kwargs, 'tts_device'):
kwargs.tts_device = common_device
if hasattr(kwargs, 'stt_device'):
kwargs.stt_device = common_device
if hasattr(kwargs, 'paraformer_stt_device'):
kwargs.paraformer_stt_device = common_device
overwrite_device_argument(module_kwargs.device, language_model_handler_kwargs, mlx_language_model_handler_kwargs, parler_tts_handler_kwargs, whisper_stt_handler_kwargs, paraformer_stt_handler_kwargs)
prepare_args(whisper_stt_handler_kwargs, 'stt')
prepare_args(paraformer_stt_handler_kwargs, 'paraformer_stt')
prepare_args(language_model_handler_kwargs, 'lm')
prepare_args(mlx_language_model_handler_kwargs, 'mlx_lm')
prepare_args(parler_tts_handler_kwargs, 'tts')
prepare_args(melo_tts_handler_kwargs, 'melo')
prepare_args(chat_tts_handler_kwargs, 'chat_tts')
stop_event = Event()
should_listen = Event()
recv_audio_chunks_queue = Queue()
send_audio_chunks_queue = Queue()
spoken_prompt_queue = Queue()
text_prompt_queue = Queue()
lm_response_queue = Queue()
if module_kwargs.mode == 'local':
from connections.local_audio_streamer import LocalAudioStreamer
local_audio_streamer = LocalAudioStreamer(input_queue=recv_audio_chunks_queue, output_queue=send_audio_chunks_queue)
comms_handlers = [local_audio_streamer]
should_listen.set()
else:
from connections.socket_receiver import SocketReceiver
from connections.socket_sender import SocketSender
comms_handlers = [SocketReceiver(stop_event, recv_audio_chunks_queue, should_listen, host=socket_receiver_kwargs.recv_host, port=socket_receiver_kwargs.recv_port, chunk_size=socket_receiver_kwargs.chunk_size), SocketSender(stop_event, send_audio_chunks_queue, host=socket_sender_kwargs.send_host, port=socket_sender_kwargs.send_port)]
vad = VADHandler(stop_event, queue_in=recv_audio_chunks_queue, queue_out=spoken_prompt_queue, setup_args=(should_listen,), setup_kwargs=vars(vad_handler_kwargs))
if module_kwargs.stt == 'whisper':
from STT.whisper_stt_handler import WhisperSTTHandler
stt = WhisperSTTHandler(stop_event, queue_in=spoken_prompt_queue, queue_out=text_prompt_queue, setup_kwargs=vars(whisper_stt_handler_kwargs))
elif module_kwargs.stt == 'whisper-mlx':
from STT.lightning_whisper_mlx_handler import LightningWhisperSTTHandler
stt = LightningWhisperSTTHandler(stop_event, queue_in=spoken_prompt_queue, queue_out=text_prompt_queue, setup_kwargs=vars(whisper_stt_handler_kwargs))
elif module_kwargs.stt == 'paraformer':
from STT.paraformer_handler import ParaformerSTTHandler
stt = ParaformerSTTHandler(stop_event, queue_in=spoken_prompt_queue, queue_out=text_prompt_queue, setup_kwargs=vars(paraformer_stt_handler_kwargs))
else:
raise ValueError('The STT should be either whisper, whisper-mlx, or paraformer.')
if module_kwargs.llm == 'transformers':
from LLM.language_model import LanguageModelHandler
lm = LanguageModelHandler(stop_event, queue_in=text_prompt_queue, queue_out=lm_response_queue, setup_kwargs=vars(language_model_handler_kwargs))
elif module_kwargs.llm == 'mlx-lm':
from LLM.mlx_language_model import MLXLanguageModelHandler
lm = MLXLanguageModelHandler(stop_event, queue_in=text_prompt_queue, queue_out=lm_response_queue, setup_kwargs=vars(mlx_language_model_handler_kwargs))
else:
raise ValueError('The LLM should be either transformers or mlx-lm')
if module_kwargs.tts == 'parler':
from TTS.parler_handler import ParlerTTSHandler
tts = ParlerTTSHandler(stop_event, queue_in=lm_response_queue, queue_out=send_audio_chunks_queue, setup_args=(should_listen,), setup_kwargs=vars(parler_tts_handler_kwargs))
elif module_kwargs.tts == 'melo':
try:
from TTS.melo_handler import MeloTTSHandler
except RuntimeError as e:
logger.error('Error importing MeloTTSHandler. You might need to run: python -m unidic download')
raise e
tts = MeloTTSHandler(stop_event, queue_in=lm_response_queue, queue_out=send_audio_chunks_queue, setup_args=(should_listen,), setup_kwargs=vars(melo_tts_handler_kwargs))
elif module_kwargs.tts == 'chatTTS':
try:
from TTS.chatTTS_handler import ChatTTSHandler
except RuntimeError as e:
logger.error('Error importing ChatTTSHandler')
raise e
tts = ChatTTSHandler(stop_event, queue_in=lm_response_queue, queue_out=send_audio_chunks_queue, setup_args=(should_listen,), setup_kwargs=vars(chat_tts_handler_kwargs))
else:
raise ValueError('The TTS should be either parler, melo or chatTTS')
try:
pipeline_manager = ThreadManager([*comms_handlers, vad, stt, lm, tts])
pipeline_manager.start()
except KeyboardInterrupt:
pipeline_manager.stop()
if __name__ == '__main__':
main()