Edmon02 commited on
Commit
0ab2a52
1 Parent(s): b6ba689

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +230 -0
app.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import librosa
3
+ import numpy as np
4
+ import torch
5
+ import string
6
+ import googletrans
7
+
8
+ from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
9
+
10
+
11
+ checkpoint = "microsoft/speecht5_tts"
12
+ processor = SpeechT5Processor.from_pretrained(checkpoint)
13
+ model = SpeechT5ForTextToSpeech.from_pretrained(checkpoint)
14
+ vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
15
+
16
+
17
+ speaker_embeddings = {
18
+ "BDL": "spkemb/cmu_us_bdl_arctic-wav-arctic_a0009.npy",
19
+ }
20
+
21
+ import pandas as pd
22
+ import inflect
23
+ import re
24
+ from googletrans import Translator
25
+
26
+ translator = Translator()
27
+
28
+ def convert_number_to_words(number: float) -> str:
29
+ p = inflect.engine()
30
+ words = p.number_to_words(number)
31
+ words = translator.translate(words, dest='hy').text
32
+ return words
33
+
34
+ def process_text(text: str) -> str:
35
+ # Convert numbers to words
36
+ words = []
37
+ text = str(text) if str(text) else ''
38
+ for word in text.split():
39
+ # Check if the word is a number
40
+ if re.search(r'\d', word):
41
+ words.append(convert_number_to_words(int(''.join(filter(str.isdigit, word)))))
42
+ else:
43
+ words.append(word)
44
+
45
+ # Join the words back into a sentence
46
+ processed_text = ' '.join(words)
47
+ return processed_text
48
+
49
+ # Read CSV file into a pandas DataFrame
50
+ df = pd.read_csv('AudioSet.csv')
51
+
52
+ # Apply the processing function to the 'normalized_text' column
53
+ df['normalized_text'] = df['normalized_text'].apply(process_text)
54
+
55
+ # Save the updated DataFrame back to the CSV file
56
+ df.to_csv('AudioSet.csv', index=False)
57
+
58
+ replacements = [
59
+ ("՚", "?"),
60
+ ('՛', ""),
61
+ ('՝', ""),
62
+ ("«", "\""),
63
+ ("»", "\""),
64
+ ("՞", "?"),
65
+ ("ա", "a"),
66
+ ("բ", "b"),
67
+ ("գ", "g"),
68
+ ("դ", "d"),
69
+ ("զ", "z"),
70
+ ("է", "e"),
71
+ ("ը", "e'"),
72
+ ("թ", "t'"),
73
+ ("ժ", "jh"),
74
+ ("ի", "i"),
75
+ ("լ", "l"),
76
+ ("խ", "kh"),
77
+ ("ծ", "ts"),
78
+ ("կ", "k"),
79
+ ("հ", "h"),
80
+ ("ձ", "dz"),
81
+ ("ղ", "gh"),
82
+ ("ճ", "ch"),
83
+ ("մ", "m"),
84
+ ("յ", "y"),
85
+ ("ն", "n"),
86
+ ("շ", "sh"),
87
+ ("չ", "ch'"),
88
+ ("պ", "p"),
89
+ ("ջ", "j"),
90
+ ("ռ", "r"),
91
+ ("ս", "s"),
92
+ ("վ", "v"),
93
+ ("տ", "t"),
94
+ ("ր", "r"),
95
+ ("ց", "ts'"),
96
+ ("ւ", ""),
97
+ ("փ", "p'"),
98
+ ("ք", "k'"),
99
+ ("և", "yev"),
100
+ ("օ", "o"),
101
+ ("ֆ", "f"),
102
+ ('։', "."),
103
+ ('–', "-"),
104
+ ('†', "e'"),
105
+ ]
106
+
107
+
108
+ def cleanup_text(text):
109
+
110
+ translator = str.maketrans("", "", string.punctuation)
111
+
112
+ text = text.translate(translator).lower()
113
+ text = text.lower()
114
+
115
+ normalized_text = text
116
+
117
+ normalized_text = normalized_text.replace("ու", "u")
118
+ normalized_text = normalized_text.replace("եւ", "u")
119
+ normalized_text = normalized_text.replace("եվ", "u")
120
+
121
+ # Handle 'ո' at the beginning of a word
122
+ normalized_text = normalized_text.replace(" ո", " vo")
123
+
124
+ # Handle 'ո' in the middle of a word
125
+ normalized_text = normalized_text.replace("ո", "o")
126
+
127
+ # Handle 'ե' at the beginning of a word
128
+ normalized_text = normalized_text.replace(" ե", " ye")
129
+
130
+ # Handle 'ե' in the middle of a word
131
+ normalized_text = normalized_text.replace("ե", "e")
132
+
133
+ # Apply other replacements
134
+ for src, dst in replacements:
135
+ normalized_text = normalized_text.replace(src, dst)
136
+
137
+ inputs = normalized_text
138
+ return inputs
139
+
140
+ def predict(text, speaker):
141
+ if len(text.strip()) == 0:
142
+ return (16000, np.zeros(0).astype(np.int16))
143
+
144
+ text = process_text(text)
145
+
146
+ text = cleanup_text({'normalized_text': text})['normalized_text']
147
+
148
+ inputs = processor(text=text, return_tensors="pt")
149
+
150
+ # limit input length
151
+ input_ids = inputs["input_ids"]
152
+ input_ids = input_ids[..., :model.config.max_text_positions]
153
+
154
+ speaker_embedding = np.load(speaker_embeddings[speaker[:3]])
155
+
156
+ speaker_embedding = torch.tensor(speaker_embedding).unsqueeze(0)
157
+
158
+ speech = model.generate_speech(input_ids, speaker_embedding, vocoder=vocoder)
159
+
160
+ speech = (speech.numpy() * 32767).astype(np.int16)
161
+ return (16000, speech)
162
+
163
+
164
+ title = "SpeechT5: Speech Synthesis"
165
+
166
+ description = """
167
+ The <b>SpeechT5</b> model is pre-trained on text as well as speech inputs, with targets that are also a mix of text and speech.
168
+ By pre-training on text and speech at the same time, it learns unified representations for both, resulting in improved modeling capabilities.
169
+
170
+ SpeechT5 can be fine-tuned for different speech tasks. This space demonstrates the <b>text-to-speech</b> (TTS) checkpoint for the English language.
171
+
172
+ See also the <a href="https://huggingface.co/spaces/Matthijs/speecht5-asr-demo">speech recognition (ASR) demo</a>
173
+ and the <a href="https://huggingface.co/spaces/Matthijs/speecht5-vc-demo">voice conversion demo</a>.
174
+
175
+ Refer to <a href="https://colab.research.google.com/drive/1i7I5pzBcU3WDFarDnzweIj4-sVVoIUFJ">this Colab notebook</a> to learn how to fine-tune the SpeechT5 TTS model on your own dataset or language.
176
+
177
+ <b>How to use:</b> Enter some English text and choose a speaker. The output is a mel spectrogram, which is converted to a mono 16 kHz waveform by the
178
+ HiFi-GAN vocoder. Because the model always applies random dropout, each attempt will give slightly different results.
179
+ The <em>Surprise Me!</em> option creates a completely randomized speaker.
180
+ """
181
+
182
+ article = """
183
+ <div style='margin:20px auto;'>
184
+
185
+ <p>References: <a href="https://arxiv.org/abs/2110.07205">SpeechT5 paper</a> |
186
+ <a href="https://github.com/microsoft/SpeechT5/">original GitHub</a> |
187
+ <a href="https://huggingface.co/mechanicalsea/speecht5-tts">original weights</a></p>
188
+
189
+ <pre>
190
+ @article{Ao2021SpeechT5,
191
+ title = {SpeechT5: Unified-Modal Encoder-Decoder Pre-training for Spoken Language Processing},
192
+ author = {Junyi Ao and Rui Wang and Long Zhou and Chengyi Wang and Shuo Ren and Yu Wu and Shujie Liu and Tom Ko and Qing Li and Yu Zhang and Zhihua Wei and Yao Qian and Jinyu Li and Furu Wei},
193
+ eprint={2110.07205},
194
+ archivePrefix={arXiv},
195
+ primaryClass={eess.AS},
196
+ year={2021}
197
+ }
198
+ </pre>
199
+
200
+ <p>Speaker embeddings were generated from <a href="http://www.festvox.org/cmu_arctic/">CMU ARCTIC</a> using <a href="https://huggingface.co/mechanicalsea/speecht5-vc/blob/main/manifest/utils/prep_cmu_arctic_spkemb.py">this script</a>.</p>
201
+
202
+ </div>
203
+ """
204
+
205
+ examples = [
206
+ ["It is not in the stars to hold our destiny but in ourselves.", "BDL (male)"],
207
+ ["The octopus and Oliver went to the opera in October.", "CLB (female)"],
208
+ ["She sells seashells by the seashore. I saw a kitten eating chicken in the kitchen.", "RMS (male)"],
209
+ ["Brisk brave brigadiers brandished broad bright blades, blunderbusses, and bludgeons—balancing them badly.", "SLT (female)"],
210
+ ["A synonym for cinnamon is a cinnamon synonym.", "BDL (male)"],
211
+ ["How much wood would a woodchuck chuck if a woodchuck could chuck wood? He would chuck, he would, as much as he could, and chuck as much wood as a woodchuck would if a woodchuck could chuck wood.", "CLB (female)"],
212
+ ]
213
+
214
+ gr.Interface(
215
+ fn=predict,
216
+ inputs=[
217
+ gr.Text(label="Input Text"),
218
+ gr.Radio(label="Speaker", choices=[
219
+ "BDL (male)"
220
+ ],
221
+ value="BDL (male)"),
222
+ ],
223
+ outputs=[
224
+ gr.Audio(label="Generated Speech", type="numpy"),
225
+ ],
226
+ title=title,
227
+ description=description,
228
+ article=article,
229
+ examples=examples,
230
+ ).launch()