File size: 2,047 Bytes
84fda9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5104349
 
 
 
 
 
 
fc172c7
5104349
 
fc172c7
 
 
 
 
5104349
 
 
84fda9a
fc172c7
84fda9a
fc172c7
84fda9a
 
 
 
 
 
 
 
 
 
5104349
84fda9a
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import gradio as gr
from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
from transformers import AutoProcessor, AutoModelForTextToSpectrogram
from datasets import load_dataset
import torch
import soundfile as sf
import os

# Load models and processors
processor = AutoProcessor.from_pretrained("ayush2607/speecht5_tts_technical_data")
model = AutoModelForTextToSpectrogram.from_pretrained("ayush2607/speecht5_tts_technical_data")
vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")

# Load xvector containing speaker's voice characteristics from a dataset
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)

# Quantize the models
def quantize_model(model):
    quantized_model = torch.quantization.quantize_dynamic(
        model, {torch.nn.Linear}, dtype=torch.qint8
    )
    return quantized_model

# Only quantize the vocoder, as the main model might not be compatible
vocoder = quantize_model(vocoder)

# Move models to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
vocoder = vocoder.to(device)
speaker_embeddings = speaker_embeddings.to(device)

# Use inference mode for faster computation
@torch.inference_mode()
def text_to_speech(text):
    inputs = processor(text=text, return_tensors="pt").to(device)
    speech = model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder)
    speech = speech.cpu()  # Move back to CPU for saving
    output_path = "output.wav"
    sf.write(output_path, speech.numpy(), samplerate=16000)
    return output_path

# Create Gradio interface
iface = gr.Interface(
    fn=text_to_speech,
    inputs=gr.Textbox(label="Enter text to convert to speech"),
    outputs=gr.Audio(label="Generated Speech"),
    title="Text-to-Speech Converter",
    description="Convert text to speech using the optimized SpeechT5 model."
)

# Launch the app
iface.launch()