Vinay15 commited on
Commit
08a2633
·
verified ·
1 Parent(s): 358bffc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -0
app.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Step 1: Import necessary libraries
2
+ import gradio as gr
3
+ import json
4
+ import torch
5
+ from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
6
+ from datasets import load_dataset
7
+ import soundfile as sf
8
+
9
+ # Step 2: Load the models and the pronunciation dictionary
10
+ processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
11
+ model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
12
+ vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
13
+
14
+ # Load pronunciation dictionary from JSON file
15
+ with open("pronunciation_dict.json", "r") as f:
16
+ pronunciation_dict = json.load(f)
17
+
18
+ # Function to preprocess the input text
19
+ def preprocess_text(text):
20
+ for term, phonetic in pronunciation_dict.items():
21
+ text = text.replace(term, phonetic)
22
+ return text
23
+
24
+ # Step 3: Define the TTS function
25
+ def text_to_speech(input_text):
26
+ # Preprocess the text
27
+ processed_text = preprocess_text(input_text)
28
+
29
+ # Convert the processed text to model inputs
30
+ inputs = processor(text=processed_text, return_tensors="pt")
31
+
32
+ # Load xvector embeddings from dataset for speaker voice characteristics
33
+ embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
34
+ speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0)
35
+
36
+ # Generate speech using the model and vocoder
37
+ speech = model.generate_speech(inputs["input_ids"], speaker_embeddings, vocoder=vocoder)
38
+
39
+ # Save the generated speech as a .wav file
40
+ output_file = "speech_output.wav"
41
+ sf.write(output_file, speech.numpy(), samplerate=16000)
42
+
43
+ return output_file
44
+
45
+ # Step 4: Create Gradio interface
46
+ iface = gr.Interface(fn=text_to_speech,
47
+ inputs="text",
48
+ outputs="audio",
49
+ title="Text-to-Speech (TTS) Application",
50
+ description="Enter text with technical jargon for TTS conversion.")
51
+
52
+ # Step 5: Launch the app
53
+ iface.launch(share=True)