abderrahimbrighal's picture
Create app.py
df9eeef verified
# Import necessary libraries and modules
from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
from datasets import load_dataset
import torch
from IPython.display import Audio
# Load the processor and model for text-to-speech
processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
# Prepare the input text
text = "Don't count the days, make the days count."
inputs = processor(text=text, return_tensors="pt")
# Load the speaker embeddings dataset and select a specific speaker
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
# Generate the spectrogram for the speech
spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
# Load the vocoder model to convert the spectrogram to speech waveform
vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
speech = model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder)
# Play the generated speech
Audio(speech, rate=16000)