* Create emo_gen.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * update server.py, fix bugs in func get_text() and infer(). (#52) * Extract get_text() and infer() from webui.py. (#53) * Extract get_text() and infer() from webui.py. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * add emo emb * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * init emo gen * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * init emo * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * init emo * Delete bert/bert-base-japanese-v3 directory * Create .gitkeep * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Create add_punc.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix bug in bert_gen.py (#54) * Update README.md * fix bug in models.py (#56) * 更新 models.py * Fix japanese cleaner (#61) * 初步,睡觉明天继续写( * 好好好放错分支了,熬夜是大忌 * [pre-commit.ci] pre-commit autoupdate (#55) * [pre-commit.ci] pre-commit autoupdate updates: - [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.5.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.5.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Create tokenizer_config.json * update preprocess_text.py:过滤一个音频匹配多个文本的情况 (#57) * update preprocess_text.py:过滤音频不存在的情况 (#58) * 修复日语cleaner和bert * better * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Stardust·减 <star_dust_chen@foxmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Sora <atri@suzakuintsubaki.com> * Apply Code Formatter Change * Add config.yml for global configuration. (#62) * Add config.yml for global configuration. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix bug in webui.py. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Rename config.yml to default_config.yml. Add ./config.yml to gitignore. * Add config.py to parse config.yml * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Update webui.py (#65) * Update webui.py: 1. Add auto translation from Chinese to Japanese. 2. Start to use config.py in webui.py to set config instead of using the command line. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix (#68) * 加上ー * fix * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Update infer.py and webui.py. Supports loading and inference models of 1.1.1 version. (#66) * Update infer.py and webui.py. Supports loading and inference models of 1.1.1 version. * Update config.json * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix bug in translate.py (#69) * Supports loading and inference models of 1.1、1.0.1、1.0 version. (#70) * Supports loading and inference models of 1.1、1.0.1、1.0 version. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Delete useless file in OldVersion --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Update japanese.py (#71) Handling JA long pronunciations * 使用配置文件配置bert_gen.py, preprocess_text.py, resample.py (#72) * Update bert_gen.py, preprocess_text.py, resample.py. Support using config.yml in these files. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update bert_gen.py * Update bert_gen.py, fix bug. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Delete bert/bert-base-japanese-v3 directory * Create config.json * Create tokenizer_config.json * Create vocab.txt * Update server.py. 支持多版本多模型 (#76) * Update server.py. 支持多版本多模型 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Dev webui (#77) * 申请pr (#75) * 2023/10/11 update 界面优化 * Update webui.py 翻译英文页面为中文 * Update train_ms.py 单卡训练 * 加入图片 * Update extern_subprocess.py * Update asr_transcript.py * Update asr_transcript.py * Update asr_transcript.py * Update extern_subprocess.py * Update asr_transcript.py * Update asr_transcript.py * Update asr_transcript.py * Update all_process.py * Update extern_subprocess.py * Update all_process.py * Update all_process.py * Update asr_transcript.py * Update extern_subprocess.py * Update webui.py * Create re_matching.py * Update webui.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update all_process.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update all_process.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update all_process.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update asr_transcript.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Pack 'update' functions into a module * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update all_process.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update asr_transcript.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update extern_subprocess.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update README.md * Update README.md * Update README.md * Update README.md * Update README.md * Update all_process.py * Update asr_transcript.py * Update webui.py * Add files via upload * Update extern_subprocess.py * Update all_process.py * Update asr_transcript.py * Update bert_gen.py * Update extern_subprocess.py * Update preprocess_text.py * Update re_matching.py * Update resample.py * Update update_status.py * Update update_status.py * Update webui.py * Update all_process.py * Update preprocess_text.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update train_ms.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Stardust·减 <star_dust_chen@foxmail.com> Co-authored-by: innnky <67028263+innnky@users.noreply.github.com> * Delete all_process.py * Delete asr_transcript.py * Delete extern_subprocess.py --------- Co-authored-by: spicysama <122108331+AnyaCoder@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: innnky <67028263+innnky@users.noreply.github.com> * Create config.json * Create preprocessor_config.json * Create vocab.json * Delete emotional/wav2vec2-large-robust-12-ft-emotion-msp-dim/.gitkeep * Update emo_gen.py * Delete add_punc.py * add emotion_clustering.i * Apply Code Formatter Change * Update models.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update preprocess_text.py (#78) * Update preprocess_text.py. 检测重复以及不存在的音频 (#79) * Handle Janpanese long pronunciations (#80) * Handle Janpanese long pronunciations * Update japanese.py * Update japanese.py * Use unified phonemes for Japanese long vowel (#82) * Use an unified phoneme for Japanese long vowel `symbol.py` has not been updated to ensure compatibility with older version models. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * 增加一个按钮,点击后可以按句子切分,添加“|” (#81) * Update re_matching.py * Update webui.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix phonemer bug (#83) * Fix phonemer bug * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix long vowel handler bug (#84) * Fix long vowel handler bug * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * 加入整合包管理器的特性:长文本合成可以自定义句间段间停顿 (#85) * Update webui.py * Update re_matching.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Update train_ms.py * fix' * Update cleaner.py * add en * add en * Update english.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * add en * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * add en * add en * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * add en * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * 更新 README.md * 更新 README.md * 更新 README.md * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Change phonemer to pyopenjtalk (#86) * Change phonemer to pyopenjtalk * 修改为openjtalk便于安装 --------- Co-authored-by: Stardust·减 <star_dust_chen@foxmail.com> * 更新 english.py * Fix english_bert_mock.py. (#87) * Add punctuation execptions (#88) * Add punctuation execptions * Ellipses exceptions * remove get bert * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix bug in oldVersion. (#89) * Update requirements.txt * change to large * rollback requirements.txt * Feat: Enable 1.1.1 models using fix-ver infer. (#91) * Feat: Enable 1.1.1 models using fix-ver infer. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Add Japanese accent (high-low) (#90) * Add punctuation execptions * Ellipses exceptions * Add Japanese accent * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Do not replace iteration mark (#92) * Add punctuation execptions * Ellipses exceptions * Add Japanese accent * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Do not replace iteration mark --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix: fix import error in oldVersion (#93) * Refactor: reusing model loading in webui.py and server.py. (#94) * Feat: Enable using config.yml in train_ms.py (#96) * 更新 emo_gen.py * Change emo_gen.py (#97) * Fix emo_gen bugs * Add multiprocess * Fix queue (#98) * Fix emo_gen bugs * Add multiprocess * Del var * Fix queue * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix training bugs (#99) * Updatge cluster notebook * Fix train * Fix filename * Update infer.py (#100) * Update infer.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Add reference audio (#101) * Add reference audio * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update * Update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Stardust·减 <star_dust_chen@foxmail.com> * Fix: fix 1.1.1-fix (#102) * Fix infer bug (#103) * Feat: Add server_fastapi.py. (#104) * Feat: Add server_fastapi.py. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix: Update requirements.txt. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix: requirements.txt. (#105) * Swith to deberta-v3-large (#106) * Swith to deberta-v3-large * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Feat: Update config.py. (#107) * Feat: Update config.py. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Dev fix (#108) * fix bugs when deploying * fix bugs when deploying * fix bugs when deploying * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Revert "Dev fix (#108)" (#109) This reverts commit 685e18a10498d602b1a9a26079340d11925646f0. * Dev fix (#110) * fix bugs when deploying * fix bugs when deploying * fix bugs when deploying * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix fixed bugs * fix fixed bugs * fix fixed bug 3 * fix fixed bug 4 * fix fixed bug 5 * fix * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Add emo vec quantizer (#111) Co-authored-by: Stardust·减 <star_dust_chen@foxmail.com> * Clean req and gitignore (#112) * Clean req and gitignore * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Switch to deberta-v2-large-japanese (#113) * Switch to deberta-v2-large-japanese * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix emo bugs (#114) * Fix english (#115) * Remove emo (#117) * Don't train codebook * Remove emo * Update * Update * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Merge dev into no-emo (#122) * [pre-commit.ci] pre-commit autoupdate (#95) * [pre-commit.ci] pre-commit autoupdate updates: - [github.com/astral-sh/ruff-pre-commit: v0.0.292 → v0.1.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.292...v0.1.1) - [github.com/psf/black: 23.9.1 → 23.10.0](https://github.com/psf/black/compare/23.9.1...23.10.0) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Don't train codebook (#116) * Update requirements.txt * Update english_bert_mock.py * Fix: server_fastapi.py (#118) * Fix: server_fastapi.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Fix: don't print debug logging. (#119) * Fix: don't print debug logging. * Feat: support emo_gen config * Fix config * Apply Code Formatter Change * 更新,修正bug (#121) * Feat: Update infer.py preprocess_text.py server_fastapi.py. * Fix resample.py. Maintain same directory structure in out_dir as in_dir. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update resample.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> * Update server_fastapi.py to no-emo ver * Update config.py, no emo config --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: OedoSoldier <31711261+OedoSoldier@users.noreply.github.com> Co-authored-by: Stardust·减 <star_dust_chen@foxmail.com> Co-authored-by: Stardust-minus <Stardust-minus@users.noreply.github.com> * Update train_ms.py * Update latest version info (#124) --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: jiangyuxiaoxiao <atri@suzakuintsubaki.com> Co-authored-by: AkitoLiu <39857739+Akito-UzukiP@users.noreply.github.com> Co-authored-by: Stardust-minus <Stardust-minus@users.noreply.github.com> Co-authored-by: OedoSoldier <31711261+OedoSoldier@users.noreply.github.com> Co-authored-by: spicysama <122108331+AnyaCoder@users.noreply.github.com> Co-authored-by: innnky <67028263+innnky@users.noreply.github.com> Co-authored-by: YYuX-1145 <138500330+YYuX-1145@users.noreply.github.com>
358 lines
10 KiB
Python
358 lines
10 KiB
Python
import os
|
|
import glob
|
|
import argparse
|
|
import logging
|
|
import json
|
|
import subprocess
|
|
import numpy as np
|
|
from scipy.io.wavfile import read
|
|
import torch
|
|
|
|
MATPLOTLIB_FLAG = False
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
|
|
assert os.path.isfile(checkpoint_path)
|
|
checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
|
|
iteration = checkpoint_dict["iteration"]
|
|
learning_rate = checkpoint_dict["learning_rate"]
|
|
if (
|
|
optimizer is not None
|
|
and not skip_optimizer
|
|
and checkpoint_dict["optimizer"] is not None
|
|
):
|
|
optimizer.load_state_dict(checkpoint_dict["optimizer"])
|
|
elif optimizer is None and not skip_optimizer:
|
|
# else: Disable this line if Infer and resume checkpoint,then enable the line upper
|
|
new_opt_dict = optimizer.state_dict()
|
|
new_opt_dict_params = new_opt_dict["param_groups"][0]["params"]
|
|
new_opt_dict["param_groups"] = checkpoint_dict["optimizer"]["param_groups"]
|
|
new_opt_dict["param_groups"][0]["params"] = new_opt_dict_params
|
|
optimizer.load_state_dict(new_opt_dict)
|
|
|
|
saved_state_dict = checkpoint_dict["model"]
|
|
if hasattr(model, "module"):
|
|
state_dict = model.module.state_dict()
|
|
else:
|
|
state_dict = model.state_dict()
|
|
|
|
new_state_dict = {}
|
|
for k, v in state_dict.items():
|
|
try:
|
|
# assert "emb_g" not in k
|
|
new_state_dict[k] = saved_state_dict[k]
|
|
assert saved_state_dict[k].shape == v.shape, (
|
|
saved_state_dict[k].shape,
|
|
v.shape,
|
|
)
|
|
except:
|
|
# For upgrading from the old version
|
|
if "ja_bert_proj" in k:
|
|
v = torch.zeros_like(v)
|
|
logger.warn(
|
|
f"Seems you are using the old version of the model, the {k} is automatically set to zero for backward compatibility"
|
|
)
|
|
else:
|
|
logger.error(f"{k} is not in the checkpoint")
|
|
|
|
new_state_dict[k] = v
|
|
|
|
if hasattr(model, "module"):
|
|
model.module.load_state_dict(new_state_dict, strict=False)
|
|
else:
|
|
model.load_state_dict(new_state_dict, strict=False)
|
|
|
|
logger.info(
|
|
"Loaded checkpoint '{}' (iteration {})".format(checkpoint_path, iteration)
|
|
)
|
|
|
|
return model, optimizer, learning_rate, iteration
|
|
|
|
|
|
def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
|
|
logger.info(
|
|
"Saving model and optimizer state at iteration {} to {}".format(
|
|
iteration, checkpoint_path
|
|
)
|
|
)
|
|
if hasattr(model, "module"):
|
|
state_dict = model.module.state_dict()
|
|
else:
|
|
state_dict = model.state_dict()
|
|
torch.save(
|
|
{
|
|
"model": state_dict,
|
|
"iteration": iteration,
|
|
"optimizer": optimizer.state_dict(),
|
|
"learning_rate": learning_rate,
|
|
},
|
|
checkpoint_path,
|
|
)
|
|
|
|
|
|
def summarize(
|
|
writer,
|
|
global_step,
|
|
scalars={},
|
|
histograms={},
|
|
images={},
|
|
audios={},
|
|
audio_sampling_rate=22050,
|
|
):
|
|
for k, v in scalars.items():
|
|
writer.add_scalar(k, v, global_step)
|
|
for k, v in histograms.items():
|
|
writer.add_histogram(k, v, global_step)
|
|
for k, v in images.items():
|
|
writer.add_image(k, v, global_step, dataformats="HWC")
|
|
for k, v in audios.items():
|
|
writer.add_audio(k, v, global_step, audio_sampling_rate)
|
|
|
|
|
|
def latest_checkpoint_path(dir_path, regex="G_*.pth"):
|
|
f_list = glob.glob(os.path.join(dir_path, regex))
|
|
f_list.sort(key=lambda f: int("".join(filter(str.isdigit, f))))
|
|
x = f_list[-1]
|
|
return x
|
|
|
|
|
|
def plot_spectrogram_to_numpy(spectrogram):
|
|
global MATPLOTLIB_FLAG
|
|
if not MATPLOTLIB_FLAG:
|
|
import matplotlib
|
|
|
|
matplotlib.use("Agg")
|
|
MATPLOTLIB_FLAG = True
|
|
mpl_logger = logging.getLogger("matplotlib")
|
|
mpl_logger.setLevel(logging.WARNING)
|
|
import matplotlib.pylab as plt
|
|
import numpy as np
|
|
|
|
fig, ax = plt.subplots(figsize=(10, 2))
|
|
im = ax.imshow(spectrogram, aspect="auto", origin="lower", interpolation="none")
|
|
plt.colorbar(im, ax=ax)
|
|
plt.xlabel("Frames")
|
|
plt.ylabel("Channels")
|
|
plt.tight_layout()
|
|
|
|
fig.canvas.draw()
|
|
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
|
|
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
|
plt.close()
|
|
return data
|
|
|
|
|
|
def plot_alignment_to_numpy(alignment, info=None):
|
|
global MATPLOTLIB_FLAG
|
|
if not MATPLOTLIB_FLAG:
|
|
import matplotlib
|
|
|
|
matplotlib.use("Agg")
|
|
MATPLOTLIB_FLAG = True
|
|
mpl_logger = logging.getLogger("matplotlib")
|
|
mpl_logger.setLevel(logging.WARNING)
|
|
import matplotlib.pylab as plt
|
|
import numpy as np
|
|
|
|
fig, ax = plt.subplots(figsize=(6, 4))
|
|
im = ax.imshow(
|
|
alignment.transpose(), aspect="auto", origin="lower", interpolation="none"
|
|
)
|
|
fig.colorbar(im, ax=ax)
|
|
xlabel = "Decoder timestep"
|
|
if info is not None:
|
|
xlabel += "\n\n" + info
|
|
plt.xlabel(xlabel)
|
|
plt.ylabel("Encoder timestep")
|
|
plt.tight_layout()
|
|
|
|
fig.canvas.draw()
|
|
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
|
|
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
|
plt.close()
|
|
return data
|
|
|
|
|
|
def load_wav_to_torch(full_path):
|
|
sampling_rate, data = read(full_path)
|
|
return torch.FloatTensor(data.astype(np.float32)), sampling_rate
|
|
|
|
|
|
def load_filepaths_and_text(filename, split="|"):
|
|
with open(filename, encoding="utf-8") as f:
|
|
filepaths_and_text = [line.strip().split(split) for line in f]
|
|
return filepaths_and_text
|
|
|
|
|
|
def get_hparams(init=True):
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument(
|
|
"-c",
|
|
"--config",
|
|
type=str,
|
|
default="./configs/base.json",
|
|
help="JSON file for configuration",
|
|
)
|
|
parser.add_argument("-m", "--model", type=str, required=True, help="Model name")
|
|
|
|
args = parser.parse_args()
|
|
model_dir = os.path.join("./logs", args.model)
|
|
|
|
if not os.path.exists(model_dir):
|
|
os.makedirs(model_dir)
|
|
|
|
config_path = args.config
|
|
config_save_path = os.path.join(model_dir, "config.json")
|
|
if init:
|
|
with open(config_path, "r", encoding="utf-8") as f:
|
|
data = f.read()
|
|
with open(config_save_path, "w", encoding="utf-8") as f:
|
|
f.write(data)
|
|
else:
|
|
with open(config_save_path, "r", vencoding="utf-8") as f:
|
|
data = f.read()
|
|
config = json.loads(data)
|
|
hparams = HParams(**config)
|
|
hparams.model_dir = model_dir
|
|
return hparams
|
|
|
|
|
|
def clean_checkpoints(path_to_models="logs/44k/", n_ckpts_to_keep=2, sort_by_time=True):
|
|
"""Freeing up space by deleting saved ckpts
|
|
|
|
Arguments:
|
|
path_to_models -- Path to the model directory
|
|
n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth
|
|
sort_by_time -- True -> chronologically delete ckpts
|
|
False -> lexicographically delete ckpts
|
|
"""
|
|
import re
|
|
|
|
ckpts_files = [
|
|
f
|
|
for f in os.listdir(path_to_models)
|
|
if os.path.isfile(os.path.join(path_to_models, f))
|
|
]
|
|
|
|
def name_key(_f):
|
|
return int(re.compile("._(\\d+)\\.pth").match(_f).group(1))
|
|
|
|
def time_key(_f):
|
|
return os.path.getmtime(os.path.join(path_to_models, _f))
|
|
|
|
sort_key = time_key if sort_by_time else name_key
|
|
|
|
def x_sorted(_x):
|
|
return sorted(
|
|
[f for f in ckpts_files if f.startswith(_x) and not f.endswith("_0.pth")],
|
|
key=sort_key,
|
|
)
|
|
|
|
to_del = [
|
|
os.path.join(path_to_models, fn)
|
|
for fn in (x_sorted("G")[:-n_ckpts_to_keep] + x_sorted("D")[:-n_ckpts_to_keep])
|
|
]
|
|
|
|
def del_info(fn):
|
|
return logger.info(f".. Free up space by deleting ckpt {fn}")
|
|
|
|
def del_routine(x):
|
|
return [os.remove(x), del_info(x)]
|
|
|
|
[del_routine(fn) for fn in to_del]
|
|
|
|
|
|
def get_hparams_from_dir(model_dir):
|
|
config_save_path = os.path.join(model_dir, "config.json")
|
|
with open(config_save_path, "r", encoding="utf-8") as f:
|
|
data = f.read()
|
|
config = json.loads(data)
|
|
|
|
hparams = HParams(**config)
|
|
hparams.model_dir = model_dir
|
|
return hparams
|
|
|
|
|
|
def get_hparams_from_file(config_path):
|
|
# print("config_path: ", config_path)
|
|
with open(config_path, "r", encoding="utf-8") as f:
|
|
data = f.read()
|
|
config = json.loads(data)
|
|
|
|
hparams = HParams(**config)
|
|
return hparams
|
|
|
|
|
|
def check_git_hash(model_dir):
|
|
source_dir = os.path.dirname(os.path.realpath(__file__))
|
|
if not os.path.exists(os.path.join(source_dir, ".git")):
|
|
logger.warn(
|
|
"{} is not a git repository, therefore hash value comparison will be ignored.".format(
|
|
source_dir
|
|
)
|
|
)
|
|
return
|
|
|
|
cur_hash = subprocess.getoutput("git rev-parse HEAD")
|
|
|
|
path = os.path.join(model_dir, "githash")
|
|
if os.path.exists(path):
|
|
saved_hash = open(path).read()
|
|
if saved_hash != cur_hash:
|
|
logger.warn(
|
|
"git hash values are different. {}(saved) != {}(current)".format(
|
|
saved_hash[:8], cur_hash[:8]
|
|
)
|
|
)
|
|
else:
|
|
open(path, "w").write(cur_hash)
|
|
|
|
|
|
def get_logger(model_dir, filename="train.log"):
|
|
global logger
|
|
logger = logging.getLogger(os.path.basename(model_dir))
|
|
logger.setLevel(logging.DEBUG)
|
|
|
|
formatter = logging.Formatter("%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s")
|
|
if not os.path.exists(model_dir):
|
|
os.makedirs(model_dir)
|
|
h = logging.FileHandler(os.path.join(model_dir, filename))
|
|
h.setLevel(logging.DEBUG)
|
|
h.setFormatter(formatter)
|
|
logger.addHandler(h)
|
|
return logger
|
|
|
|
|
|
class HParams:
|
|
def __init__(self, **kwargs):
|
|
for k, v in kwargs.items():
|
|
if type(v) == dict:
|
|
v = HParams(**v)
|
|
self[k] = v
|
|
|
|
def keys(self):
|
|
return self.__dict__.keys()
|
|
|
|
def items(self):
|
|
return self.__dict__.items()
|
|
|
|
def values(self):
|
|
return self.__dict__.values()
|
|
|
|
def __len__(self):
|
|
return len(self.__dict__)
|
|
|
|
def __getitem__(self, key):
|
|
return getattr(self, key)
|
|
|
|
def __setitem__(self, key, value):
|
|
return setattr(self, key, value)
|
|
|
|
def __contains__(self, key):
|
|
return key in self.__dict__
|
|
|
|
def __repr__(self):
|
|
return self.__dict__.__repr__()
|