Nag189 commited on
Commit
19bdfd0
1 Parent(s): 46e4cd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -117
app.py CHANGED
@@ -1,125 +1,138 @@
1
- import gradio as gr
2
- import librosa
 
 
3
  import numpy as np
4
  import torch
 
 
5
 
6
- from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
7
 
 
 
 
 
 
 
8
 
9
- checkpoint = "microsoft/speecht5_tts"
10
- processor = SpeechT5Processor.from_pretrained(checkpoint)
11
- model = SpeechT5ForTextToSpeech.from_pretrained(checkpoint)
 
 
 
 
12
  vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
13
 
14
-
15
- speaker_embeddings = {
16
- "BDL": "cmu_us_bdl_arctic-wav-arctic_a0009.npy",
17
- "CLB": "cmu_us_clb_arctic-wav-arctic_a0144.npy",
18
- "KSP": "cmu_us_ksp_arctic-wav-arctic_b0087.npy",
19
- "RMS": "cmu_us_rms_arctic-wav-arctic_b0353.npy",
20
- "SLT": "cmu_us_slt_arctic-wav-arctic_a0508.npy",
21
- }
22
-
23
-
24
- def predict(text, speaker):
25
- if len(text.strip()) == 0:
26
- return (16000, np.zeros(0).astype(np.int16))
27
-
 
 
 
 
 
 
 
 
 
 
28
  inputs = processor(text=text, return_tensors="pt")
29
-
30
- # limit input length
31
- input_ids = inputs["input_ids"]
32
- input_ids = input_ids[..., :model.config.max_text_positions]
33
-
34
- if speaker == "Surprise User!":
35
- # load one of the provided speaker embeddings at random
36
- idx = np.random.randint(len(speaker_embeddings))
37
- key = list(speaker_embeddings.keys())[idx]
38
- speaker_embedding = np.load(speaker_embeddings[key])
39
-
40
- # randomly shuffle the elements
41
- np.random.shuffle(speaker_embedding)
42
-
43
- # randomly flip half the values
44
- x = (np.random.rand(512) >= 0.5) * 1.0
45
- x[x == 0] = -1.0
46
- speaker_embedding *= x
47
-
48
- #speaker_embedding = np.random.rand(512).astype(np.float32) * 0.3 - 0.15
49
- else:
50
- speaker_embedding = np.load(speaker_embeddings[speaker[:3]])
51
-
52
- speaker_embedding = torch.tensor(speaker_embedding).unsqueeze(0)
53
-
54
- speech = model.generate_speech(input_ids, speaker_embedding, vocoder=vocoder)
55
-
56
- speech = (speech.numpy() * 32767).astype(np.int16)
57
- return (16000, speech)
58
-
59
-
60
- title = "Text-to-Speech based on SpeechT5"
61
-
62
- description = """
63
- 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.
64
- By pre-training on text and speech at the same time, it learns unified representations for both, resulting in improved modeling capabilities.
65
-
66
- This space demonstrates the <b>text-to-speech</b> (TTS) checkpoint for the English language.
67
-
68
- <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 HiFi-GAN vocoder. Because the model always applies random dropout, each attempt will give slightly different results.
69
- The <em>Surprise Me!</em> option creates a completely randomized speaker.
70
- """
71
-
72
- article = """
73
- <div style='margin:20px auto;'>
74
-
75
- <p>References: <a href="https://arxiv.org/abs/2110.07205">SpeechT5 paper</a> |
76
- <a href="https://github.com/microsoft/SpeechT5/">original GitHub</a> |
77
- <a href="https://huggingface.co/mechanicalsea/speecht5-tts">original weights</a></p>
78
-
79
- <pre>
80
- @article{Ao2021SpeechT5,
81
- title = {SpeechT5: Unified-Modal Encoder-Decoder Pre-training for Spoken Language Processing},
82
- 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},
83
- eprint={2110.07205},
84
- archivePrefix={arXiv},
85
- primaryClass={eess.AS},
86
- year={2021}
87
- }
88
- </pre>
89
-
90
- <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>
91
-
92
- </div>
93
- """
94
-
95
- examples = [
96
- ["As a Data Scientist, I'll be demonstrating my speaking voice in this example. If you don't like my voice, you can choose a different one by setting the speaker parameter.", "BDL (male)"],
97
- ["The octopus and Oliver went to the opera in October.", "CLB (female)"],
98
- ["She sells seashells by the seashore. I saw a kitten eating chicken in the kitchen.", "RMS (male)"],
99
- ["Brisk brave brigadiers brandished broad bright blades, blunderbusses, and bludgeons—balancing them badly.", "SLT (female)"],
100
- ["A synonym for cinnamon is a cinnamon synonym.", "BDL (male)"],
101
- ["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)"],
102
- ]
103
-
104
- gr.Interface(
105
- fn=predict,
106
- inputs=[
107
- gr.Text(label="Input Text"),
108
- gr.Radio(label="Speaker", choices=[
109
- "BDL (male)",
110
- "CLB (female)",
111
- "KSP (male)",
112
- "RMS (male)",
113
- "SLT (female)",
114
- "Surprise User!"
115
- ],
116
- value="BDL (male)"),
117
- ],
118
- outputs=[
119
- gr.Audio(label="Generated Speech", type="numpy"),
120
- ],
121
- title=title,
122
- description=description,
123
- article=article,
124
- examples=examples,
125
- ).launch()
 
1
+ import streamlit as st
2
+ import time
3
+ from datetime import datetime
4
+ from transformers import SpeechT5Processor, SpeechT5ForSpeechToSpeech, SpeechT5HifiGan,SpeechT5ForTextToSpeech
5
  import numpy as np
6
  import torch
7
+ from io import StringIO
8
+ import soundfile as sf
9
 
 
10
 
11
+ html_temp= """
12
+ <div style="background-color:tomato;padding:10px">
13
+ <h2 style="color:white;text-align:centre;"> Text-to-Speech </h2>
14
+ </div>
15
+ """
16
+ st.markdown(html_temp,unsafe_allow_html=True)
17
 
18
+ st.markdown(
19
+ """
20
+ Text to Audio Conversion.
21
+ """
22
+ )
23
+ model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
24
+ processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
25
  vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
26
 
27
+ speaker_embeddings = np.load("cmu_us_slt_arctic-wav-arctic_a0499.npy")
28
+ speaker_embeddings = torch.tensor(speaker_embeddings).unsqueeze(0)
29
+
30
+ text = st.text_area("Type your text..")
31
+ st.button("Convert")
32
+ inputs = processor(text=text, return_tensors="pt")
33
+ spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
34
+ with torch.no_grad():
35
+ speech = vocoder(spectrogram)
36
+ sf.write("speech.wav", speech.numpy(), samplerate=16000)
37
+
38
+ audio_file = open('speech.wav', 'rb')
39
+ audio_bytes = audio_file.read()
40
+ st.audio(audio_bytes, format='audio/wav')
41
+
42
+
43
+ uploaded_file=st.file_uploader("Upload your text file here",type=['txt'] )
44
+ if uploaded_file is not None:
45
+ stringio = StringIO(uploaded_file.getvalue().decode("utf-8"))
46
+ #To read file as string:
47
+ text = stringio.read()
48
+ st.write(text)
49
+
50
+ st.button("Convert",key=1)
51
  inputs = processor(text=text, return_tensors="pt")
52
+ spectrogram = model.generate_speech(inputs["input_ids"], speaker_embeddings)
53
+ with torch.no_grad():
54
+ speech = vocoder(spectrogram)
55
+ sf.write("speech.wav", speech.numpy(), samplerate=16000)
56
+ audio_file = open('speech.wav', 'rb')
57
+ audio_bytes = audio_file.read()
58
+ st.audio(audio_bytes, format='audio/wav')
59
+
60
+
61
+
62
+
63
+
64
+ st.text("Thanks for using")
65
+
66
+ if st.button("About"):
67
+ st.text("Created by Surendra Kumar")
68
+ ## footer
69
+ from htbuilder import HtmlElement, div, ul, li, br, hr, a, p, img, styles, classes, fonts
70
+ from htbuilder.units import percent, px
71
+ from htbuilder.funcs import rgba, rgb
72
+
73
+
74
+ def image(src_as_string, **style):
75
+ return img(src=src_as_string, style=styles(**style))
76
+
77
+
78
+ def link(link, text, **style):
79
+ return a(_href=link, _target="_blank", style=styles(**style))(text)
80
+
81
+
82
+ def layout(*args):
83
+ style = """
84
+ <style>
85
+ # MainMenu {visibility: hidden;}
86
+ footer {visibility: hidden;}
87
+ .stApp { bottom: 105px; }
88
+ </style>
89
+ """
90
+
91
+ style_div = styles(
92
+ position="fixed",
93
+ left=0,
94
+ bottom=0,
95
+ margin=px(0, 0, 0, 0),
96
+ width=percent(100),
97
+ color="black",
98
+ text_align="center",
99
+ height="auto",
100
+ opacity=1
101
+ )
102
+
103
+ style_hr = styles(
104
+ display="block",
105
+ margin=px(8, 8, "auto", "auto"),
106
+ border_style="solid",
107
+ border_width=px(0.5)
108
+ )
109
+
110
+ body = p()
111
+ foot = div(
112
+ style=style_div
113
+ )(
114
+ hr(
115
+ style=style_hr
116
+ ),
117
+ body
118
+ )
119
+ st.markdown(style,unsafe_allow_html=True)
120
+
121
+ for arg in args:
122
+ if isinstance(arg, str):
123
+ body(arg)
124
+
125
+ elif isinstance(arg, HtmlElement):
126
+ body(arg)
127
+
128
+ st.markdown(str(foot), unsafe_allow_html=True)
129
+
130
+
131
+ def footer():
132
+ myargs = [
133
+ "©️ Apps Consultants",
134
+ ]
135
+ layout(*myargs)
136
+
137
+ if __name__ == "__main__":
138
+ footer()