ElesisSiegherts commited on
Commit
592ab9f
1 Parent(s): 7b4f85e

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +278 -0
app.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import os
3
+
4
+ import gradio as gr
5
+ import numpy as np
6
+ import torch
7
+
8
+ from infer import infer
9
+ from server_fastapi import Models
10
+
11
+ is_hf_spaces = os.getenv("SYSTEM") == "spaces"
12
+ limit = 100
13
+
14
+
15
+ root_dir = "weights"
16
+
17
+ model_holder = Models()
18
+
19
+
20
+ def refresh_model():
21
+ global model_holder
22
+ model_holder = Models()
23
+
24
+ model_dirs = [
25
+ d for d in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, d))
26
+ ]
27
+ model_names = []
28
+ for model_name in model_dirs:
29
+ model_dir = os.path.join(root_dir, model_name)
30
+ pth_files = [f for f in os.listdir(model_dir) if f.endswith(".pth")]
31
+ if len(pth_files) != 1:
32
+ print(f"{root_dir}/{model_name}のpthファイルの数が1つではないので無視します")
33
+ continue
34
+ model_path = os.path.join(model_dir, pth_files[0])
35
+ config_path = os.path.join(model_dir, "config.json")
36
+ try:
37
+ model_holder.init_model(
38
+ config_path=config_path,
39
+ model_path=model_path,
40
+ device=device,
41
+ language="JP",
42
+ )
43
+ model_names.append(model_name)
44
+ except Exception as e:
45
+ print(f"{root_dir}/{model_name}の初期化に失敗しました\n{e}")
46
+ continue
47
+ return model_names
48
+
49
+
50
+ def update_model_dropdown():
51
+ model_names = refresh_model()
52
+ return gr.Dropdown(choices=model_names, value=model_names[0])
53
+
54
+
55
+ # `server_fastapi.py`から取ってきて微修正
56
+ def _voice(
57
+ model_id: int,
58
+ text: str,
59
+ language: str = "JP",
60
+ emotion: int = 0,
61
+ sdp_ratio: float = 0.2,
62
+ noise: float = 0.6,
63
+ noisew: float = 0.8,
64
+ length: float = 1.0,
65
+ line_split: bool = True,
66
+ split_interval: float = 0.2,
67
+ speaker_id: int = 0,
68
+ ):
69
+ if model_id not in model_holder.models.keys():
70
+ return f"エラー、model_id={model_id}は存在しません", None
71
+ speaker_name = model_holder.models[model_id].id2spk[speaker_id]
72
+
73
+ start_time = datetime.datetime.now()
74
+
75
+ print("-----")
76
+ print(datetime.datetime.now())
77
+ print(
78
+ f"model_id={model_id}, speaker_id={speaker_id}, speaker_name={speaker_name}, language={language}"
79
+ )
80
+ print(f"text:\n{text}")
81
+
82
+ if is_hf_spaces and len(text) > limit:
83
+ print(f"Error: 文字数が{limit}文字を超えています")
84
+ return f"エラー、文字数が{limit}文字を超えています", None
85
+
86
+ try:
87
+ if not line_split:
88
+ with torch.no_grad():
89
+ audio = infer(
90
+ text=text,
91
+ sdp_ratio=sdp_ratio,
92
+ noise_scale=noise,
93
+ noise_scale_w=noisew,
94
+ length_scale=length,
95
+ sid=speaker_name,
96
+ language=language,
97
+ hps=model_holder.models[model_id].hps,
98
+ net_g=model_holder.models[model_id].net_g,
99
+ device=model_holder.models[model_id].device,
100
+ emotion=emotion,
101
+ )
102
+ else:
103
+ texts = text.split("\n")
104
+ texts = [t for t in texts if t != ""] # 空行を削除
105
+ audios = []
106
+ with torch.no_grad():
107
+ for i, t in enumerate(texts):
108
+ audios.append(
109
+ infer(
110
+ text=t,
111
+ sdp_ratio=sdp_ratio,
112
+ noise_scale=noise,
113
+ noise_scale_w=noisew,
114
+ length_scale=length,
115
+ sid=speaker_name,
116
+ language=language,
117
+ hps=model_holder.models[model_id].hps,
118
+ net_g=model_holder.models[model_id].net_g,
119
+ device=model_holder.models[model_id].device,
120
+ emotion=emotion,
121
+ )
122
+ )
123
+ if i != len(texts) - 1:
124
+ audios.append(np.zeros(int(44100 * split_interval)))
125
+ audio = np.concatenate(audios)
126
+ end_time = datetime.datetime.now()
127
+ duration = (end_time - start_time).total_seconds()
128
+ print(f"{end_time}: Done, {duration} seconds.")
129
+ return f"Success, time: {duration} seconds.", (
130
+ model_holder.models[model_id].hps.data.sampling_rate,
131
+ audio,
132
+ )
133
+ except Exception as e:
134
+ print(f"Error: {e}")
135
+ return f"エラー\n{e}", None
136
+
137
+
138
+ initial_text = "この電車は、急行、調布ゆきです。"
139
+
140
+ example_local = [
141
+ [initial_text, "JP"],
142
+ [ # ChatGPTに考えてもらった告白セリフ
143
+ """私、ずっと前からあなたのことを見てきました。あなたの笑顔、優しさ、強さに、心惹かれていたんです。
144
+ 友達として過ごす中で、あなたのことがだんだんと特別な存在になっていくのがわかりました。
145
+ えっと、私、あなたのことが好きです!もしよければ、私と付き合ってくれませんか?""",
146
+ "JP",
147
+ ],
148
+ [ # 夏目漱石『吾輩は猫である』
149
+ """吾輩は猫である。名前はまだ無い。
150
+ どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。
151
+ 吾輩はここで始めて人間というものを見た。しかもあとで聞くと、それは書生という、人間中で一番獰悪な種族であったそうだ。
152
+ この書生というのは時々我々を捕まえて煮て食うという話である。""",
153
+ "JP",
154
+ ],
155
+ [ # 梶井基次郎『桜の樹の下には』
156
+ """桜の樹の下には屍体が埋まっている!これは信じていいことなんだよ。
157
+ 何故って、桜の花があんなにも見事に咲くなんて信じられないことじゃないか。俺はあの美しさが信じられないので、このにさんにち不安だった。
158
+ しかしいま、やっとわかるときが来た。桜の樹の下には屍体が埋まっている。これは信じていいことだ。""",
159
+ "JP",
160
+ ],
161
+ [ # ChatGPTと考えた、感情を表すセリフ
162
+ """やったー!テストで満点取れたよ!私とっても嬉しいな!
163
+ どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。
164
+ あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。
165
+ あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。""",
166
+ "JP",
167
+ ],
168
+ [ # 上の丁寧語バージョン
169
+ """やりました!テストで満点取れましたよ!私とっても嬉しいです!
170
+ どうして私の意見を無視するんですか?許せません!ムカつきます!あんたなんか死んでください。
171
+ あはははっ!この漫画めっちゃ笑えます、見てくださいこれ、ふふふ、あはは。
172
+ あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しいです。""",
173
+ "JP",
174
+ ],
175
+ [ # ChatGPTに考えてもらった音声合成の説明文章
176
+ """音声合成は、機械学習を活用して、テキストから人の声を再現する技術です。この技術は、言語の構造を解析し、それに基づいて音声を生成します。
177
+ この分野の最新の研究成果を使うと、より自然で表現豊かな音声の生成が可能である。深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現することが出来る。""",
178
+ "JP",
179
+ ],
180
+ [
181
+ "Speech synthesis is the artificial production of human speech. A computer system used for this purpose is called a speech synthesizer, and can be implemented in software or hardware products.",
182
+ "EN",
183
+ ],
184
+ ]
185
+
186
+ example_hf_spaces = [
187
+ [initial_text, "JP"],
188
+ ["えっと、私、あなたのことが好きです!もしよければ付き合ってくれませんか?", "JP"],
189
+ ["吾輩は猫である。名前はまだ無い。", "JP"],
190
+ ["どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。", "JP"],
191
+ ["やったー!テストで満点取れたよ!私とっても嬉しいな!", "JP"],
192
+ ["どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。", "JP"],
193
+ ["あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。", "JP"],
194
+ ["あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。", "JP"],
195
+ ["深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現されている。", "JP"],
196
+ ]
197
+
198
+ initial_md = """
199
+ # 京王線自動放送メーカー
200
+
201
+
202
+
203
+
204
+
205
+ """
206
+
207
+
208
+ if __name__ == "__main__":
209
+ device = "cuda" if torch.cuda.is_available() else "cpu"
210
+ # device = "cpu"
211
+
212
+ languages = ["JP", "EN", "ZH"]
213
+ examples = example_hf_spaces if is_hf_spaces else example_local
214
+
215
+ model_names = refresh_model()
216
+
217
+ with gr.Blocks() as app:
218
+ gr.Markdown(initial_md)
219
+ with gr.Row():
220
+ with gr.Column():
221
+ with gr.Row():
222
+ model_input = gr.Dropdown(
223
+ label="モデル一覧",
224
+ choices=model_names,
225
+ type="index",
226
+ scale=3,
227
+ )
228
+ if not is_hf_spaces:
229
+ refresh_button = gr.Button("モデル一覧を更新", scale=1)
230
+ refresh_button.click(
231
+ update_model_dropdown, outputs=[model_input]
232
+ )
233
+ text_input = gr.TextArea(label="テキスト", value=initial_text)
234
+ language = gr.Dropdown(choices=languages, value="JP", label="言語")
235
+ line_split = gr.Checkbox(label="改行で分けて生成", value=not is_hf_spaces)
236
+ split_interval = gr.Slider(
237
+ minimum=0.1, maximum=2, value=0.5, step=0.1, label="分けた場合に挟む無音の長さ"
238
+ )
239
+
240
+ with gr.Accordion(label="詳細設定", open=False):
241
+ emotion = gr.Slider(
242
+ minimum=0, maximum=9, value=0, step=1, label="Emotion"
243
+ )
244
+ sdp_ratio = gr.Slider(
245
+ minimum=0, maximum=1, value=0.2, step=0.1, label="SDP Ratio"
246
+ )
247
+ noise_scale = gr.Slider(
248
+ minimum=0.1, maximum=2, value=0.6, step=0.1, label="Noise"
249
+ )
250
+ noise_scale_w = gr.Slider(
251
+ minimum=0.1, maximum=2, value=0.8, step=0.1, label="Noise_W"
252
+ )
253
+ length_scale = gr.Slider(
254
+ minimum=0.1, maximum=2, value=1.0, step=0.1, label="Length"
255
+ )
256
+ with gr.Column():
257
+ button = gr.Button("実行", variant="primary")
258
+ text_output = gr.Textbox(label="情報")
259
+ audio_output = gr.Audio(label="結果")
260
+
261
+ button.click(
262
+ _voice,
263
+ inputs=[
264
+ model_input, # model_id
265
+ text_input, # text
266
+ language, # language
267
+ emotion, # emotion
268
+ sdp_ratio, # sdp_ratio
269
+ noise_scale, # noise
270
+ noise_scale_w, # noise_w
271
+ length_scale, # length
272
+ line_split, # auto_split
273
+ split_interval, # interval
274
+ ],
275
+ outputs=[text_output, audio_output],
276
+ )
277
+
278
+ app.launch(inbrowser=True)