Views
No views yet
1from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
2from speechbrain.pretrained import EncoderClassifier
3from IPython.display import Audio
4from datasets import load_dataset
5import noisereduce as nr
6import soundfile as sf
7import os, torchaudio
8import numpy as np
9import torch
10
11# Load the processor and model
12processor = SpeechT5Processor.from_pretrained("checkpoint-60000") # Replace with the model folder
13processor.tokenizer.split_special_tokens = True
14model = SpeechT5ForTextToSpeech.from_pretrained("checkpoint-60000") # Replace with the model folder
15vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
16
17# Load speaker embeddings dataset
18embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
19speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
20
21# Load the speaker model
22spk_model_name = "speechbrain/spkrec-xvect-voxceleb"
23device = "cuda" if torch.cuda.is_available() else "cpu"
24speaker_model = EncoderClassifier.from_hparams(
25 source=spk_model_name,
26 run_opts={"device": device},
27 savedir=os.path.join("/tmp", spk_model_name),
28)
29
30# Load and process the Ratan Tata voice file
31signal, fs = torchaudio.load('wavs/converted_ratan_tata_tts_200.wav') # Replace with a Ratan Tata voice file
32speaker_embeddings = speaker_model.encode_batch(signal)
33speaker_embeddings = torch.nn.functional.normalize(speaker_embeddings, dim=2).squeeze().cpu().numpy()
34speaker_embeddings = torch.tensor(np.array([speaker_embeddings]))
35
36# Define input text
37input_text = '''
38This is Generated Audio.
39India, a land of ancient wisdom and boundless potential, stands at the cusp of a new era. Our youth, the vibrant heartbeat of our nation, hold the key to unlocking this potential...
40'''
41
42# Split text into chunks based on character length
43def split_text_by_length(text, max_length=60):
44 words = text.split()
45 result = []
46 current_line = []
47 for word in words:
48 if len(' '.join(current_line + [word])) > max_length:
49 result.append(' '.join(current_line))
50 current_line = [word]
51 else:
52 current_line.append(word)
53 if current_line:
54 result.append(' '.join(current_line))
55 return result
56
57splited_text = split_text_by_length(input_text, max_length=80)
58
59# Generate speech for each text chunk and apply noise reduction
60all_speech = []
61for i in splited_text:
62 inputs = processor(text=i, return_tensors="pt")
63 speech_chunk = model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder)
64
65 if isinstance(speech_chunk, torch.Tensor):
66 speech_chunk = speech_chunk.cpu().numpy()
67
68 reduced_noise_chunk = nr.reduce_noise(y=speech_chunk, sr=16000) # assuming 16kHz sample rate
69 all_speech.append(reduced_noise_chunk)
70
71# Concatenate all speech chunks
72concatenated_speech = np.concatenate(all_speech)
73
74# Play the final audio
75Audio(concatenated_speech, rate=16000)