Spaces:
Runtime error
Runtime error
init
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .dockerignore +25 -0
- .gitignore +34 -0
- App.bat +11 -0
- Data/.gitignore +2 -0
- Dataset.bat +11 -0
- Dockerfile +23 -0
- Dockerfile.train +109 -0
- Editor.bat +11 -0
- LICENSE +661 -0
- Merge.bat +13 -0
- README.md +1 -1
- Style.bat +12 -0
- Train.bat +13 -0
- app.py +500 -0
- attentions.py +462 -0
- bert/bert_models.json +14 -0
- bert/chinese-roberta-wwm-ext-large/.gitattributes +9 -0
- bert/chinese-roberta-wwm-ext-large/README.md +57 -0
- bert/chinese-roberta-wwm-ext-large/added_tokens.json +1 -0
- bert/chinese-roberta-wwm-ext-large/config.json +28 -0
- bert/chinese-roberta-wwm-ext-large/special_tokens_map.json +1 -0
- bert/chinese-roberta-wwm-ext-large/tokenizer.json +0 -0
- bert/chinese-roberta-wwm-ext-large/tokenizer_config.json +1 -0
- bert/chinese-roberta-wwm-ext-large/vocab.txt +0 -0
- bert/deberta-v2-large-japanese-char-wwm/.gitattributes +34 -0
- bert/deberta-v2-large-japanese-char-wwm/README.md +89 -0
- bert/deberta-v2-large-japanese-char-wwm/config.json +37 -0
- bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json +7 -0
- bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json +19 -0
- bert/deberta-v2-large-japanese-char-wwm/vocab.txt +0 -0
- bert/deberta-v3-large/.gitattributes +27 -0
- bert/deberta-v3-large/README.md +93 -0
- bert/deberta-v3-large/config.json +22 -0
- bert/deberta-v3-large/generator_config.json +22 -0
- bert/deberta-v3-large/tokenizer_config.json +4 -0
- bert_gen.py +85 -0
- clustering.ipynb +0 -0
- colab.ipynb +410 -0
- common/constants.py +28 -0
- common/log.py +16 -0
- common/stdout_wrapper.py +38 -0
- common/subprocess_utils.py +32 -0
- common/tts_model.py +335 -0
- commons.py +152 -0
- config.py +291 -0
- configs/config.json +72 -0
- configs/configs_jp_extra.json +79 -0
- configs/paths.yml +8 -0
- data_utils.py +456 -0
- default_config.yml +70 -0
.dockerignore
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Dockerfile.deploy用の.dockerignore
|
2 |
+
# 日本語のJP-Extraのエディター稼働のみに必要なファイルを指定する
|
3 |
+
|
4 |
+
*
|
5 |
+
|
6 |
+
!/bert/deberta-v2-large-japanese-char-wwm/
|
7 |
+
!/common/
|
8 |
+
!/configs/
|
9 |
+
!/dict_data/default.csv
|
10 |
+
!/model_assets/
|
11 |
+
!/monotonic_align/
|
12 |
+
!/text/
|
13 |
+
|
14 |
+
!/attentions.py
|
15 |
+
!/commons.py
|
16 |
+
!/config.py
|
17 |
+
!/default_config.yml
|
18 |
+
!/infer.py
|
19 |
+
!/models.py
|
20 |
+
!/models_jp_extra.py
|
21 |
+
!/modules.py
|
22 |
+
!/requirements.txt
|
23 |
+
!/server_editor.py
|
24 |
+
!/transforms.py
|
25 |
+
!/utils.py
|
.gitignore
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.vscode/
|
2 |
+
|
3 |
+
__pycache__/
|
4 |
+
venv/
|
5 |
+
.ipynb_checkpoints/
|
6 |
+
|
7 |
+
/*.yml
|
8 |
+
!/default_config.yml
|
9 |
+
/bert/*/*.bin
|
10 |
+
/bert/*/*.h5
|
11 |
+
/bert/*/*.model
|
12 |
+
/bert/*/*.safetensors
|
13 |
+
/bert/*/*.msgpack
|
14 |
+
|
15 |
+
/pretrained/*.safetensors
|
16 |
+
/pretrained/*.pth
|
17 |
+
|
18 |
+
/pretrained_jp_extra/*.safetensors
|
19 |
+
/pretrained_jp_extra/*.pth
|
20 |
+
|
21 |
+
/slm/*/*.bin
|
22 |
+
|
23 |
+
/scripts/test/
|
24 |
+
*.zip
|
25 |
+
*.csv
|
26 |
+
*.bak
|
27 |
+
/mos_results/
|
28 |
+
|
29 |
+
safetensors.ipynb
|
30 |
+
*.wav
|
31 |
+
/static/
|
32 |
+
|
33 |
+
# pyopenjtalk's dictionary
|
34 |
+
*.dic
|
App.bat
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chcp 65001 > NUL
|
2 |
+
@echo off
|
3 |
+
|
4 |
+
pushd %~dp0
|
5 |
+
echo Running app.py...
|
6 |
+
venv\Scripts\python app.py
|
7 |
+
|
8 |
+
if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
|
9 |
+
|
10 |
+
popd
|
11 |
+
pause
|
Data/.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
*
|
2 |
+
!.gitignore
|
Dataset.bat
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chcp 65001 > NUL
|
2 |
+
@echo off
|
3 |
+
|
4 |
+
pushd %~dp0
|
5 |
+
echo Running webui_dataset.py...
|
6 |
+
venv\Scripts\python webui_dataset.py
|
7 |
+
|
8 |
+
if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
|
9 |
+
|
10 |
+
popd
|
11 |
+
pause
|
Dockerfile
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Hugging face spaces (CPU) でエディタ (server_editor.py) のデプロイ用
|
2 |
+
|
3 |
+
# See https://huggingface.co/docs/hub/spaces-sdks-docker-first-demo
|
4 |
+
|
5 |
+
FROM python:3.10
|
6 |
+
|
7 |
+
RUN useradd -m -u 1000 user
|
8 |
+
|
9 |
+
USER user
|
10 |
+
|
11 |
+
ENV HOME=/home/user \
|
12 |
+
PATH=/home/user/.local/bin:$PATH
|
13 |
+
|
14 |
+
WORKDIR $HOME/app
|
15 |
+
|
16 |
+
RUN pip install --no-cache-dir --upgrade pip
|
17 |
+
|
18 |
+
COPY --chown=user . $HOME/app
|
19 |
+
|
20 |
+
RUN pip install --no-cache-dir -r $HOME/app/requirements.txt
|
21 |
+
|
22 |
+
# 必要に応じて制限を変更してください
|
23 |
+
CMD ["python", "server_editor.py", "--line_length", "50", "--line_count", "3","--port", "7860"]
|
Dockerfile.train
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# PaperspaceのGradient環境での学習環境構築用Dockerfileです。
|
2 |
+
# 環境のみ構築するため、イメージには学習用のコードは含まれていません。
|
3 |
+
# 以下を参照しました。
|
4 |
+
# https://github.com/gradient-ai/base-container/tree/main/pt211-tf215-cudatk120-py311
|
5 |
+
|
6 |
+
# 主なバージョン等
|
7 |
+
# Ubuntu 22.04
|
8 |
+
# Python 3.10
|
9 |
+
# PyTorch 2.1.2 (CUDA 11.8)
|
10 |
+
# CUDA Toolkit 12.0, CUDNN 8.9.7
|
11 |
+
|
12 |
+
|
13 |
+
# ==================================================================
|
14 |
+
# Initial setup
|
15 |
+
# ------------------------------------------------------------------
|
16 |
+
|
17 |
+
# Ubuntu 22.04 as base image
|
18 |
+
FROM ubuntu:22.04
|
19 |
+
# RUN yes| unminimize
|
20 |
+
|
21 |
+
# Set ENV variables
|
22 |
+
ENV LANG C.UTF-8
|
23 |
+
ENV SHELL=/bin/bash
|
24 |
+
ENV DEBIAN_FRONTEND=noninteractive
|
25 |
+
|
26 |
+
ENV APT_INSTALL="apt-get install -y --no-install-recommends"
|
27 |
+
ENV PIP_INSTALL="python3 -m pip --no-cache-dir install --upgrade"
|
28 |
+
ENV GIT_CLONE="git clone --depth 10"
|
29 |
+
|
30 |
+
# ==================================================================
|
31 |
+
# Tools
|
32 |
+
# ------------------------------------------------------------------
|
33 |
+
|
34 |
+
RUN apt-get update && \
|
35 |
+
$APT_INSTALL \
|
36 |
+
sudo \
|
37 |
+
build-essential \
|
38 |
+
ca-certificates \
|
39 |
+
wget \
|
40 |
+
curl \
|
41 |
+
git \
|
42 |
+
zip \
|
43 |
+
unzip \
|
44 |
+
nano \
|
45 |
+
ffmpeg \
|
46 |
+
software-properties-common \
|
47 |
+
gnupg \
|
48 |
+
python3 \
|
49 |
+
python3-pip \
|
50 |
+
python3-dev
|
51 |
+
|
52 |
+
# ==================================================================
|
53 |
+
# Git-lfs
|
54 |
+
# ------------------------------------------------------------------
|
55 |
+
|
56 |
+
RUN curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash && \
|
57 |
+
$APT_INSTALL git-lfs
|
58 |
+
|
59 |
+
|
60 |
+
# Add symlink so python and python3 commands use same python3.9 executable
|
61 |
+
RUN ln -s /usr/bin/python3 /usr/local/bin/python
|
62 |
+
|
63 |
+
# ==================================================================
|
64 |
+
# Installing CUDA packages (CUDA Toolkit 12.0 and CUDNN 8.9.7)
|
65 |
+
# ------------------------------------------------------------------
|
66 |
+
RUN wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin && \
|
67 |
+
mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 && \
|
68 |
+
wget https://developer.download.nvidia.com/compute/cuda/12.0.0/local_installers/cuda-repo-ubuntu2204-12-0-local_12.0.0-525.60.13-1_amd64.deb && \
|
69 |
+
dpkg -i cuda-repo-ubuntu2204-12-0-local_12.0.0-525.60.13-1_amd64.deb && \
|
70 |
+
cp /var/cuda-repo-ubuntu2204-12-0-local/cuda-*-keyring.gpg /usr/share/keyrings/ && \
|
71 |
+
apt-get update && \
|
72 |
+
$APT_INSTALL cuda && \
|
73 |
+
rm cuda-repo-ubuntu2204-12-0-local_12.0.0-525.60.13-1_amd64.deb
|
74 |
+
|
75 |
+
# Installing CUDNN
|
76 |
+
RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub && \
|
77 |
+
add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /" && \
|
78 |
+
apt-get update && \
|
79 |
+
$APT_INSTALL libcudnn8=8.9.7.29-1+cuda12.2 \
|
80 |
+
libcudnn8-dev=8.9.7.29-1+cuda12.2
|
81 |
+
|
82 |
+
|
83 |
+
ENV PATH=$PATH:/usr/local/cuda/bin
|
84 |
+
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
|
85 |
+
|
86 |
+
|
87 |
+
# ==================================================================
|
88 |
+
# PyTorch
|
89 |
+
# ------------------------------------------------------------------
|
90 |
+
|
91 |
+
# Based on https://pytorch.org/get-started/locally/
|
92 |
+
|
93 |
+
RUN $PIP_INSTALL torch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 --index-url https://download.pytorch.org/whl/cu118
|
94 |
+
|
95 |
+
|
96 |
+
RUN $PIP_INSTALL jupyterlab
|
97 |
+
|
98 |
+
# Install requirements.txt from the project
|
99 |
+
COPY requirements.txt /tmp/requirements.txt
|
100 |
+
RUN $PIP_INSTALL -r /tmp/requirements.txt
|
101 |
+
RUN rm /tmp/requirements.txt
|
102 |
+
|
103 |
+
# ==================================================================
|
104 |
+
# Startup
|
105 |
+
# ------------------------------------------------------------------
|
106 |
+
|
107 |
+
EXPOSE 8888 6006
|
108 |
+
|
109 |
+
CMD jupyter lab --allow-root --ip=0.0.0.0 --no-browser --ServerApp.trust_xheaders=True --ServerApp.disable_check_xsrf=False --ServerApp.allow_remote_access=True --ServerApp.allow_origin='*' --ServerApp.allow_credentials=True
|
Editor.bat
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chcp 65001 > NUL
|
2 |
+
@echo off
|
3 |
+
|
4 |
+
pushd %~dp0
|
5 |
+
echo Running server_editor.py --inbroser
|
6 |
+
venv\Scripts\python server_editor.py --inbrowser
|
7 |
+
|
8 |
+
if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
|
9 |
+
|
10 |
+
popd
|
11 |
+
pause
|
LICENSE
ADDED
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works, specifically designed to ensure
|
12 |
+
cooperation with the community in the case of network server software.
|
13 |
+
|
14 |
+
The licenses for most software and other practical works are designed
|
15 |
+
to take away your freedom to share and change the works. By contrast,
|
16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
17 |
+
share and change all versions of a program--to make sure it remains free
|
18 |
+
software for all its users.
|
19 |
+
|
20 |
+
When we speak of free software, we are referring to freedom, not
|
21 |
+
price. Our General Public Licenses are designed to make sure that you
|
22 |
+
have the freedom to distribute copies of free software (and charge for
|
23 |
+
them if you wish), that you receive source code or can get it if you
|
24 |
+
want it, that you can change the software or use pieces of it in new
|
25 |
+
free programs, and that you know you can do these things.
|
26 |
+
|
27 |
+
Developers that use our General Public Licenses protect your rights
|
28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
29 |
+
you this License which gives you legal permission to copy, distribute
|
30 |
+
and/or modify the software.
|
31 |
+
|
32 |
+
A secondary benefit of defending all users' freedom is that
|
33 |
+
improvements made in alternate versions of the program, if they
|
34 |
+
receive widespread use, become available for other developers to
|
35 |
+
incorporate. Many developers of free software are heartened and
|
36 |
+
encouraged by the resulting cooperation. However, in the case of
|
37 |
+
software used on network servers, this result may fail to come about.
|
38 |
+
The GNU General Public License permits making a modified version and
|
39 |
+
letting the public access it on a server without ever releasing its
|
40 |
+
source code to the public.
|
41 |
+
|
42 |
+
The GNU Affero General Public License is designed specifically to
|
43 |
+
ensure that, in such cases, the modified source code becomes available
|
44 |
+
to the community. It requires the operator of a network server to
|
45 |
+
provide the source code of the modified version running there to the
|
46 |
+
users of that server. Therefore, public use of a modified version, on
|
47 |
+
a publicly accessible server, gives the public access to the source
|
48 |
+
code of the modified version.
|
49 |
+
|
50 |
+
An older license, called the Affero General Public License and
|
51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
53 |
+
released a new version of the Affero GPL which permits relicensing under
|
54 |
+
this license.
|
55 |
+
|
56 |
+
The precise terms and conditions for copying, distribution and
|
57 |
+
modification follow.
|
58 |
+
|
59 |
+
TERMS AND CONDITIONS
|
60 |
+
|
61 |
+
0. Definitions.
|
62 |
+
|
63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
64 |
+
|
65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
66 |
+
works, such as semiconductor masks.
|
67 |
+
|
68 |
+
"The Program" refers to any copyrightable work licensed under this
|
69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
70 |
+
"recipients" may be individuals or organizations.
|
71 |
+
|
72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
73 |
+
in a fashion requiring copyright permission, other than the making of an
|
74 |
+
exact copy. The resulting work is called a "modified version" of the
|
75 |
+
earlier work or a work "based on" the earlier work.
|
76 |
+
|
77 |
+
A "covered work" means either the unmodified Program or a work based
|
78 |
+
on the Program.
|
79 |
+
|
80 |
+
To "propagate" a work means to do anything with it that, without
|
81 |
+
permission, would make you directly or secondarily liable for
|
82 |
+
infringement under applicable copyright law, except executing it on a
|
83 |
+
computer or modifying a private copy. Propagation includes copying,
|
84 |
+
distribution (with or without modification), making available to the
|
85 |
+
public, and in some countries other activities as well.
|
86 |
+
|
87 |
+
To "convey" a work means any kind of propagation that enables other
|
88 |
+
parties to make or receive copies. Mere interaction with a user through
|
89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
90 |
+
|
91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
92 |
+
to the extent that it includes a convenient and prominently visible
|
93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
94 |
+
tells the user that there is no warranty for the work (except to the
|
95 |
+
extent that warranties are provided), that licensees may convey the
|
96 |
+
work under this License, and how to view a copy of this License. If
|
97 |
+
the interface presents a list of user commands or options, such as a
|
98 |
+
menu, a prominent item in the list meets this criterion.
|
99 |
+
|
100 |
+
1. Source Code.
|
101 |
+
|
102 |
+
The "source code" for a work means the preferred form of the work
|
103 |
+
for making modifications to it. "Object code" means any non-source
|
104 |
+
form of a work.
|
105 |
+
|
106 |
+
A "Standard Interface" means an interface that either is an official
|
107 |
+
standard defined by a recognized standards body, or, in the case of
|
108 |
+
interfaces specified for a particular programming language, one that
|
109 |
+
is widely used among developers working in that language.
|
110 |
+
|
111 |
+
The "System Libraries" of an executable work include anything, other
|
112 |
+
than the work as a whole, that (a) is included in the normal form of
|
113 |
+
packaging a Major Component, but which is not part of that Major
|
114 |
+
Component, and (b) serves only to enable use of the work with that
|
115 |
+
Major Component, or to implement a Standard Interface for which an
|
116 |
+
implementation is available to the public in source code form. A
|
117 |
+
"Major Component", in this context, means a major essential component
|
118 |
+
(kernel, window system, and so on) of the specific operating system
|
119 |
+
(if any) on which the executable work runs, or a compiler used to
|
120 |
+
produce the work, or an object code interpreter used to run it.
|
121 |
+
|
122 |
+
The "Corresponding Source" for a work in object code form means all
|
123 |
+
the source code needed to generate, install, and (for an executable
|
124 |
+
work) run the object code and to modify the work, including scripts to
|
125 |
+
control those activities. However, it does not include the work's
|
126 |
+
System Libraries, or general-purpose tools or generally available free
|
127 |
+
programs which are used unmodified in performing those activities but
|
128 |
+
which are not part of the work. For example, Corresponding Source
|
129 |
+
includes interface definition files associated with source files for
|
130 |
+
the work, and the source code for shared libraries and dynamically
|
131 |
+
linked subprograms that the work is specifically designed to require,
|
132 |
+
such as by intimate data communication or control flow between those
|
133 |
+
subprograms and other parts of the work.
|
134 |
+
|
135 |
+
The Corresponding Source need not include anything that users
|
136 |
+
can regenerate automatically from other parts of the Corresponding
|
137 |
+
Source.
|
138 |
+
|
139 |
+
The Corresponding Source for a work in source code form is that
|
140 |
+
same work.
|
141 |
+
|
142 |
+
2. Basic Permissions.
|
143 |
+
|
144 |
+
All rights granted under this License are granted for the term of
|
145 |
+
copyright on the Program, and are irrevocable provided the stated
|
146 |
+
conditions are met. This License explicitly affirms your unlimited
|
147 |
+
permission to run the unmodified Program. The output from running a
|
148 |
+
covered work is covered by this License only if the output, given its
|
149 |
+
content, constitutes a covered work. This License acknowledges your
|
150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
151 |
+
|
152 |
+
You may make, run and propagate covered works that you do not
|
153 |
+
convey, without conditions so long as your license otherwise remains
|
154 |
+
in force. You may convey covered works to others for the sole purpose
|
155 |
+
of having them make modifications exclusively for you, or provide you
|
156 |
+
with facilities for running those works, provided that you comply with
|
157 |
+
the terms of this License in conveying all material for which you do
|
158 |
+
not control copyright. Those thus making or running the covered works
|
159 |
+
for you must do so exclusively on your behalf, under your direction
|
160 |
+
and control, on terms that prohibit them from making any copies of
|
161 |
+
your copyrighted material outside their relationship with you.
|
162 |
+
|
163 |
+
Conveying under any other circumstances is permitted solely under
|
164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
165 |
+
makes it unnecessary.
|
166 |
+
|
167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
168 |
+
|
169 |
+
No covered work shall be deemed part of an effective technological
|
170 |
+
measure under any applicable law fulfilling obligations under article
|
171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
172 |
+
similar laws prohibiting or restricting circumvention of such
|
173 |
+
measures.
|
174 |
+
|
175 |
+
When you convey a covered work, you waive any legal power to forbid
|
176 |
+
circumvention of technological measures to the extent such circumvention
|
177 |
+
is effected by exercising rights under this License with respect to
|
178 |
+
the covered work, and you disclaim any intention to limit operation or
|
179 |
+
modification of the work as a means of enforcing, against the work's
|
180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
181 |
+
technological measures.
|
182 |
+
|
183 |
+
4. Conveying Verbatim Copies.
|
184 |
+
|
185 |
+
You may convey verbatim copies of the Program's source code as you
|
186 |
+
receive it, in any medium, provided that you conspicuously and
|
187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
188 |
+
keep intact all notices stating that this License and any
|
189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
190 |
+
keep intact all notices of the absence of any warranty; and give all
|
191 |
+
recipients a copy of this License along with the Program.
|
192 |
+
|
193 |
+
You may charge any price or no price for each copy that you convey,
|
194 |
+
and you may offer support or warranty protection for a fee.
|
195 |
+
|
196 |
+
5. Conveying Modified Source Versions.
|
197 |
+
|
198 |
+
You may convey a work based on the Program, or the modifications to
|
199 |
+
produce it from the Program, in the form of source code under the
|
200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
201 |
+
|
202 |
+
a) The work must carry prominent notices stating that you modified
|
203 |
+
it, and giving a relevant date.
|
204 |
+
|
205 |
+
b) The work must carry prominent notices stating that it is
|
206 |
+
released under this License and any conditions added under section
|
207 |
+
7. This requirement modifies the requirement in section 4 to
|
208 |
+
"keep intact all notices".
|
209 |
+
|
210 |
+
c) You must license the entire work, as a whole, under this
|
211 |
+
License to anyone who comes into possession of a copy. This
|
212 |
+
License will therefore apply, along with any applicable section 7
|
213 |
+
additional terms, to the whole of the work, and all its parts,
|
214 |
+
regardless of how they are packaged. This License gives no
|
215 |
+
permission to license the work in any other way, but it does not
|
216 |
+
invalidate such permission if you have separately received it.
|
217 |
+
|
218 |
+
d) If the work has interactive user interfaces, each must display
|
219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
221 |
+
work need not make them do so.
|
222 |
+
|
223 |
+
A compilation of a covered work with other separate and independent
|
224 |
+
works, which are not by their nature extensions of the covered work,
|
225 |
+
and which are not combined with it such as to form a larger program,
|
226 |
+
in or on a volume of a storage or distribution medium, is called an
|
227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
228 |
+
used to limit the access or legal rights of the compilation's users
|
229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
230 |
+
in an aggregate does not cause this License to apply to the other
|
231 |
+
parts of the aggregate.
|
232 |
+
|
233 |
+
6. Conveying Non-Source Forms.
|
234 |
+
|
235 |
+
You may convey a covered work in object code form under the terms
|
236 |
+
of sections 4 and 5, provided that you also convey the
|
237 |
+
machine-readable Corresponding Source under the terms of this License,
|
238 |
+
in one of these ways:
|
239 |
+
|
240 |
+
a) Convey the object code in, or embodied in, a physical product
|
241 |
+
(including a physical distribution medium), accompanied by the
|
242 |
+
Corresponding Source fixed on a durable physical medium
|
243 |
+
customarily used for software interchange.
|
244 |
+
|
245 |
+
b) Convey the object code in, or embodied in, a physical product
|
246 |
+
(including a physical distribution medium), accompanied by a
|
247 |
+
written offer, valid for at least three years and valid for as
|
248 |
+
long as you offer spare parts or customer support for that product
|
249 |
+
model, to give anyone who possesses the object code either (1) a
|
250 |
+
copy of the Corresponding Source for all the software in the
|
251 |
+
product that is covered by this License, on a durable physical
|
252 |
+
medium customarily used for software interchange, for a price no
|
253 |
+
more than your reasonable cost of physically performing this
|
254 |
+
conveying of source, or (2) access to copy the
|
255 |
+
Corresponding Source from a network server at no charge.
|
256 |
+
|
257 |
+
c) Convey individual copies of the object code with a copy of the
|
258 |
+
written offer to provide the Corresponding Source. This
|
259 |
+
alternative is allowed only occasionally and noncommercially, and
|
260 |
+
only if you received the object code with such an offer, in accord
|
261 |
+
with subsection 6b.
|
262 |
+
|
263 |
+
d) Convey the object code by offering access from a designated
|
264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
265 |
+
Corresponding Source in the same way through the same place at no
|
266 |
+
further charge. You need not require recipients to copy the
|
267 |
+
Corresponding Source along with the object code. If the place to
|
268 |
+
copy the object code is a network server, the Corresponding Source
|
269 |
+
may be on a different server (operated by you or a third party)
|
270 |
+
that supports equivalent copying facilities, provided you maintain
|
271 |
+
clear directions next to the object code saying where to find the
|
272 |
+
Corresponding Source. Regardless of what server hosts the
|
273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
274 |
+
available for as long as needed to satisfy these requirements.
|
275 |
+
|
276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
277 |
+
you inform other peers where the object code and Corresponding
|
278 |
+
Source of the work are being offered to the general public at no
|
279 |
+
charge under subsection 6d.
|
280 |
+
|
281 |
+
A separable portion of the object code, whose source code is excluded
|
282 |
+
from the Corresponding Source as a System Library, need not be
|
283 |
+
included in conveying the object code work.
|
284 |
+
|
285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
286 |
+
tangible personal property which is normally used for personal, family,
|
287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
290 |
+
product received by a particular user, "normally used" refers to a
|
291 |
+
typical or common use of that class of product, regardless of the status
|
292 |
+
of the particular user or of the way in which the particular user
|
293 |
+
actually uses, or expects or is expected to use, the product. A product
|
294 |
+
is a consumer product regardless of whether the product has substantial
|
295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
296 |
+
the only significant mode of use of the product.
|
297 |
+
|
298 |
+
"Installation Information" for a User Product means any methods,
|
299 |
+
procedures, authorization keys, or other information required to install
|
300 |
+
and execute modified versions of a covered work in that User Product from
|
301 |
+
a modified version of its Corresponding Source. The information must
|
302 |
+
suffice to ensure that the continued functioning of the modified object
|
303 |
+
code is in no case prevented or interfered with solely because
|
304 |
+
modification has been made.
|
305 |
+
|
306 |
+
If you convey an object code work under this section in, or with, or
|
307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
308 |
+
part of a transaction in which the right of possession and use of the
|
309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
310 |
+
fixed term (regardless of how the transaction is characterized), the
|
311 |
+
Corresponding Source conveyed under this section must be accompanied
|
312 |
+
by the Installation Information. But this requirement does not apply
|
313 |
+
if neither you nor any third party retains the ability to install
|
314 |
+
modified object code on the User Product (for example, the work has
|
315 |
+
been installed in ROM).
|
316 |
+
|
317 |
+
The requirement to provide Installation Information does not include a
|
318 |
+
requirement to continue to provide support service, warranty, or updates
|
319 |
+
for a work that has been modified or installed by the recipient, or for
|
320 |
+
the User Product in which it has been modified or installed. Access to a
|
321 |
+
network may be denied when the modification itself materially and
|
322 |
+
adversely affects the operation of the network or violates the rules and
|
323 |
+
protocols for communication across the network.
|
324 |
+
|
325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
326 |
+
in accord with this section must be in a format that is publicly
|
327 |
+
documented (and with an implementation available to the public in
|
328 |
+
source code form), and must require no special password or key for
|
329 |
+
unpacking, reading or copying.
|
330 |
+
|
331 |
+
7. Additional Terms.
|
332 |
+
|
333 |
+
"Additional permissions" are terms that supplement the terms of this
|
334 |
+
License by making exceptions from one or more of its conditions.
|
335 |
+
Additional permissions that are applicable to the entire Program shall
|
336 |
+
be treated as though they were included in this License, to the extent
|
337 |
+
that they are valid under applicable law. If additional permissions
|
338 |
+
apply only to part of the Program, that part may be used separately
|
339 |
+
under those permissions, but the entire Program remains governed by
|
340 |
+
this License without regard to the additional permissions.
|
341 |
+
|
342 |
+
When you convey a copy of a covered work, you may at your option
|
343 |
+
remove any additional permissions from that copy, or from any part of
|
344 |
+
it. (Additional permissions may be written to require their own
|
345 |
+
removal in certain cases when you modify the work.) You may place
|
346 |
+
additional permissions on material, added by you to a covered work,
|
347 |
+
for which you have or can give appropriate copyright permission.
|
348 |
+
|
349 |
+
Notwithstanding any other provision of this License, for material you
|
350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
351 |
+
that material) supplement the terms of this License with terms:
|
352 |
+
|
353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
354 |
+
terms of sections 15 and 16 of this License; or
|
355 |
+
|
356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
357 |
+
author attributions in that material or in the Appropriate Legal
|
358 |
+
Notices displayed by works containing it; or
|
359 |
+
|
360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
361 |
+
requiring that modified versions of such material be marked in
|
362 |
+
reasonable ways as different from the original version; or
|
363 |
+
|
364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
365 |
+
authors of the material; or
|
366 |
+
|
367 |
+
e) Declining to grant rights under trademark law for use of some
|
368 |
+
trade names, trademarks, or service marks; or
|
369 |
+
|
370 |
+
f) Requiring indemnification of licensors and authors of that
|
371 |
+
material by anyone who conveys the material (or modified versions of
|
372 |
+
it) with contractual assumptions of liability to the recipient, for
|
373 |
+
any liability that these contractual assumptions directly impose on
|
374 |
+
those licensors and authors.
|
375 |
+
|
376 |
+
All other non-permissive additional terms are considered "further
|
377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
378 |
+
received it, or any part of it, contains a notice stating that it is
|
379 |
+
governed by this License along with a term that is a further
|
380 |
+
restriction, you may remove that term. If a license document contains
|
381 |
+
a further restriction but permits relicensing or conveying under this
|
382 |
+
License, you may add to a covered work material governed by the terms
|
383 |
+
of that license document, provided that the further restriction does
|
384 |
+
not survive such relicensing or conveying.
|
385 |
+
|
386 |
+
If you add terms to a covered work in accord with this section, you
|
387 |
+
must place, in the relevant source files, a statement of the
|
388 |
+
additional terms that apply to those files, or a notice indicating
|
389 |
+
where to find the applicable terms.
|
390 |
+
|
391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
392 |
+
form of a separately written license, or stated as exceptions;
|
393 |
+
the above requirements apply either way.
|
394 |
+
|
395 |
+
8. Termination.
|
396 |
+
|
397 |
+
You may not propagate or modify a covered work except as expressly
|
398 |
+
provided under this License. Any attempt otherwise to propagate or
|
399 |
+
modify it is void, and will automatically terminate your rights under
|
400 |
+
this License (including any patent licenses granted under the third
|
401 |
+
paragraph of section 11).
|
402 |
+
|
403 |
+
However, if you cease all violation of this License, then your
|
404 |
+
license from a particular copyright holder is reinstated (a)
|
405 |
+
provisionally, unless and until the copyright holder explicitly and
|
406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
407 |
+
holder fails to notify you of the violation by some reasonable means
|
408 |
+
prior to 60 days after the cessation.
|
409 |
+
|
410 |
+
Moreover, your license from a particular copyright holder is
|
411 |
+
reinstated permanently if the copyright holder notifies you of the
|
412 |
+
violation by some reasonable means, this is the first time you have
|
413 |
+
received notice of violation of this License (for any work) from that
|
414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
415 |
+
your receipt of the notice.
|
416 |
+
|
417 |
+
Termination of your rights under this section does not terminate the
|
418 |
+
licenses of parties who have received copies or rights from you under
|
419 |
+
this License. If your rights have been terminated and not permanently
|
420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
421 |
+
material under section 10.
|
422 |
+
|
423 |
+
9. Acceptance Not Required for Having Copies.
|
424 |
+
|
425 |
+
You are not required to accept this License in order to receive or
|
426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
428 |
+
to receive a copy likewise does not require acceptance. However,
|
429 |
+
nothing other than this License grants you permission to propagate or
|
430 |
+
modify any covered work. These actions infringe copyright if you do
|
431 |
+
not accept this License. Therefore, by modifying or propagating a
|
432 |
+
covered work, you indicate your acceptance of this License to do so.
|
433 |
+
|
434 |
+
10. Automatic Licensing of Downstream Recipients.
|
435 |
+
|
436 |
+
Each time you convey a covered work, the recipient automatically
|
437 |
+
receives a license from the original licensors, to run, modify and
|
438 |
+
propagate that work, subject to this License. You are not responsible
|
439 |
+
for enforcing compliance by third parties with this License.
|
440 |
+
|
441 |
+
An "entity transaction" is a transaction transferring control of an
|
442 |
+
organization, or substantially all assets of one, or subdividing an
|
443 |
+
organization, or merging organizations. If propagation of a covered
|
444 |
+
work results from an entity transaction, each party to that
|
445 |
+
transaction who receives a copy of the work also receives whatever
|
446 |
+
licenses to the work the party's predecessor in interest had or could
|
447 |
+
give under the previous paragraph, plus a right to possession of the
|
448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
449 |
+
the predecessor has it or can get it with reasonable efforts.
|
450 |
+
|
451 |
+
You may not impose any further restrictions on the exercise of the
|
452 |
+
rights granted or affirmed under this License. For example, you may
|
453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
454 |
+
rights granted under this License, and you may not initiate litigation
|
455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
456 |
+
any patent claim is infringed by making, using, selling, offering for
|
457 |
+
sale, or importing the Program or any portion of it.
|
458 |
+
|
459 |
+
11. Patents.
|
460 |
+
|
461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
462 |
+
License of the Program or a work on which the Program is based. The
|
463 |
+
work thus licensed is called the contributor's "contributor version".
|
464 |
+
|
465 |
+
A contributor's "essential patent claims" are all patent claims
|
466 |
+
owned or controlled by the contributor, whether already acquired or
|
467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
468 |
+
by this License, of making, using, or selling its contributor version,
|
469 |
+
but do not include claims that would be infringed only as a
|
470 |
+
consequence of further modification of the contributor version. For
|
471 |
+
purposes of this definition, "control" includes the right to grant
|
472 |
+
patent sublicenses in a manner consistent with the requirements of
|
473 |
+
this License.
|
474 |
+
|
475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
476 |
+
patent license under the contributor's essential patent claims, to
|
477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
478 |
+
propagate the contents of its contributor version.
|
479 |
+
|
480 |
+
In the following three paragraphs, a "patent license" is any express
|
481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
482 |
+
(such as an express permission to practice a patent or covenant not to
|
483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
484 |
+
party means to make such an agreement or commitment not to enforce a
|
485 |
+
patent against the party.
|
486 |
+
|
487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
488 |
+
and the Corresponding Source of the work is not available for anyone
|
489 |
+
to copy, free of charge and under the terms of this License, through a
|
490 |
+
publicly available network server or other readily accessible means,
|
491 |
+
then you must either (1) cause the Corresponding Source to be so
|
492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
494 |
+
consistent with the requirements of this License, to extend the patent
|
495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
496 |
+
actual knowledge that, but for the patent license, your conveying the
|
497 |
+
covered work in a country, or your recipient's use of the covered work
|
498 |
+
in a country, would infringe one or more identifiable patents in that
|
499 |
+
country that you have reason to believe are valid.
|
500 |
+
|
501 |
+
If, pursuant to or in connection with a single transaction or
|
502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
503 |
+
covered work, and grant a patent license to some of the parties
|
504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
505 |
+
or convey a specific copy of the covered work, then the patent license
|
506 |
+
you grant is automatically extended to all recipients of the covered
|
507 |
+
work and works based on it.
|
508 |
+
|
509 |
+
A patent license is "discriminatory" if it does not include within
|
510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
512 |
+
specifically granted under this License. You may not convey a covered
|
513 |
+
work if you are a party to an arrangement with a third party that is
|
514 |
+
in the business of distributing software, under which you make payment
|
515 |
+
to the third party based on the extent of your activity of conveying
|
516 |
+
the work, and under which the third party grants, to any of the
|
517 |
+
parties who would receive the covered work from you, a discriminatory
|
518 |
+
patent license (a) in connection with copies of the covered work
|
519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
520 |
+
for and in connection with specific products or compilations that
|
521 |
+
contain the covered work, unless you entered into that arrangement,
|
522 |
+
or that patent license was granted, prior to 28 March 2007.
|
523 |
+
|
524 |
+
Nothing in this License shall be construed as excluding or limiting
|
525 |
+
any implied license or other defenses to infringement that may
|
526 |
+
otherwise be available to you under applicable patent law.
|
527 |
+
|
528 |
+
12. No Surrender of Others' Freedom.
|
529 |
+
|
530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
531 |
+
otherwise) that contradict the conditions of this License, they do not
|
532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
534 |
+
License and any other pertinent obligations, then as a consequence you may
|
535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
536 |
+
to collect a royalty for further conveying from those to whom you convey
|
537 |
+
the Program, the only way you could satisfy both those terms and this
|
538 |
+
License would be to refrain entirely from conveying the Program.
|
539 |
+
|
540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
541 |
+
|
542 |
+
Notwithstanding any other provision of this License, if you modify the
|
543 |
+
Program, your modified version must prominently offer all users
|
544 |
+
interacting with it remotely through a computer network (if your version
|
545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
546 |
+
Source of your version by providing access to the Corresponding Source
|
547 |
+
from a network server at no charge, through some standard or customary
|
548 |
+
means of facilitating copying of software. This Corresponding Source
|
549 |
+
shall include the Corresponding Source for any work covered by version 3
|
550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
551 |
+
following paragraph.
|
552 |
+
|
553 |
+
Notwithstanding any other provision of this License, you have
|
554 |
+
permission to link or combine any covered work with a work licensed
|
555 |
+
under version 3 of the GNU General Public License into a single
|
556 |
+
combined work, and to convey the resulting work. The terms of this
|
557 |
+
License will continue to apply to the part which is the covered work,
|
558 |
+
but the work with which it is combined will remain governed by version
|
559 |
+
3 of the GNU General Public License.
|
560 |
+
|
561 |
+
14. Revised Versions of this License.
|
562 |
+
|
563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
566 |
+
address new problems or concerns.
|
567 |
+
|
568 |
+
Each version is given a distinguishing version number. If the
|
569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
570 |
+
Public License "or any later version" applies to it, you have the
|
571 |
+
option of following the terms and conditions either of that numbered
|
572 |
+
version or of any later version published by the Free Software
|
573 |
+
Foundation. If the Program does not specify a version number of the
|
574 |
+
GNU Affero General Public License, you may choose any version ever published
|
575 |
+
by the Free Software Foundation.
|
576 |
+
|
577 |
+
If the Program specifies that a proxy can decide which future
|
578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
579 |
+
public statement of acceptance of a version permanently authorizes you
|
580 |
+
to choose that version for the Program.
|
581 |
+
|
582 |
+
Later license versions may give you additional or different
|
583 |
+
permissions. However, no additional obligations are imposed on any
|
584 |
+
author or copyright holder as a result of your choosing to follow a
|
585 |
+
later version.
|
586 |
+
|
587 |
+
15. Disclaimer of Warranty.
|
588 |
+
|
589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
597 |
+
|
598 |
+
16. Limitation of Liability.
|
599 |
+
|
600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
608 |
+
SUCH DAMAGES.
|
609 |
+
|
610 |
+
17. Interpretation of Sections 15 and 16.
|
611 |
+
|
612 |
+
If the disclaimer of warranty and limitation of liability provided
|
613 |
+
above cannot be given local legal effect according to their terms,
|
614 |
+
reviewing courts shall apply local law that most closely approximates
|
615 |
+
an absolute waiver of all civil liability in connection with the
|
616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
617 |
+
copy of the Program in return for a fee.
|
618 |
+
|
619 |
+
END OF TERMS AND CONDITIONS
|
620 |
+
|
621 |
+
How to Apply These Terms to Your New Programs
|
622 |
+
|
623 |
+
If you develop a new program, and you want it to be of the greatest
|
624 |
+
possible use to the public, the best way to achieve this is to make it
|
625 |
+
free software which everyone can redistribute and change under these terms.
|
626 |
+
|
627 |
+
To do so, attach the following notices to the program. It is safest
|
628 |
+
to attach them to the start of each source file to most effectively
|
629 |
+
state the exclusion of warranty; and each file should have at least
|
630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
631 |
+
|
632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
633 |
+
Copyright (C) <year> <name of author>
|
634 |
+
|
635 |
+
This program is free software: you can redistribute it and/or modify
|
636 |
+
it under the terms of the GNU Affero General Public License as published
|
637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
638 |
+
(at your option) any later version.
|
639 |
+
|
640 |
+
This program is distributed in the hope that it will be useful,
|
641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
643 |
+
GNU Affero General Public License for more details.
|
644 |
+
|
645 |
+
You should have received a copy of the GNU Affero General Public License
|
646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
647 |
+
|
648 |
+
Also add information on how to contact you by electronic and paper mail.
|
649 |
+
|
650 |
+
If your software can interact with users remotely through a computer
|
651 |
+
network, you should also make sure that it provides a way for users to
|
652 |
+
get its source. For example, if your program is a web application, its
|
653 |
+
interface could display a "Source" link that leads users to an archive
|
654 |
+
of the code. There are many ways you could offer source, and different
|
655 |
+
solutions will be better for different programs; see section 13 for the
|
656 |
+
specific requirements.
|
657 |
+
|
658 |
+
You should also get your employer (if you work as a programmer) or school,
|
659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
661 |
+
<https://www.gnu.org/licenses/>.
|
Merge.bat
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chcp 65001 > NUL
|
2 |
+
|
3 |
+
@echo off
|
4 |
+
|
5 |
+
pushd %~dp0
|
6 |
+
|
7 |
+
echo Running webui_merge.py...
|
8 |
+
venv\Scripts\python webui_merge.py
|
9 |
+
|
10 |
+
if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
|
11 |
+
|
12 |
+
popd
|
13 |
+
pause
|
README.md
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
---
|
2 |
title: Style Bert VITS2 Editor Demo
|
3 |
-
emoji:
|
4 |
colorFrom: gray
|
5 |
colorTo: yellow
|
6 |
sdk: docker
|
|
|
1 |
---
|
2 |
title: Style Bert VITS2 Editor Demo
|
3 |
+
emoji: 😊🎙️📖
|
4 |
colorFrom: gray
|
5 |
colorTo: yellow
|
6 |
sdk: docker
|
Style.bat
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chcp 65001 > NUL
|
2 |
+
|
3 |
+
@echo off
|
4 |
+
|
5 |
+
pushd %~dp0
|
6 |
+
echo Running webui_style_vectors.py...
|
7 |
+
venv\Scripts\python webui_style_vectors.py
|
8 |
+
|
9 |
+
if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
|
10 |
+
|
11 |
+
popd
|
12 |
+
pause
|
Train.bat
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chcp 65001 > NUL
|
2 |
+
|
3 |
+
@echo off
|
4 |
+
|
5 |
+
pushd %~dp0
|
6 |
+
|
7 |
+
echo Running webui_train.py...
|
8 |
+
venv\Scripts\python webui_train.py
|
9 |
+
|
10 |
+
if %errorlevel% neq 0 ( pause & popd & exit /b %errorlevel% )
|
11 |
+
|
12 |
+
popd
|
13 |
+
pause
|
app.py
ADDED
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import datetime
|
3 |
+
import json
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
from pathlib import Path
|
7 |
+
from typing import Optional
|
8 |
+
|
9 |
+
import gradio as gr
|
10 |
+
import torch
|
11 |
+
import yaml
|
12 |
+
|
13 |
+
from common.constants import (
|
14 |
+
DEFAULT_ASSIST_TEXT_WEIGHT,
|
15 |
+
DEFAULT_LENGTH,
|
16 |
+
DEFAULT_LINE_SPLIT,
|
17 |
+
DEFAULT_NOISE,
|
18 |
+
DEFAULT_NOISEW,
|
19 |
+
DEFAULT_SDP_RATIO,
|
20 |
+
DEFAULT_SPLIT_INTERVAL,
|
21 |
+
DEFAULT_STYLE,
|
22 |
+
DEFAULT_STYLE_WEIGHT,
|
23 |
+
GRADIO_THEME,
|
24 |
+
LATEST_VERSION,
|
25 |
+
Languages,
|
26 |
+
)
|
27 |
+
from common.log import logger
|
28 |
+
from common.tts_model import ModelHolder
|
29 |
+
from infer import InvalidToneError
|
30 |
+
from text.japanese import g2kata_tone, kata_tone2phone_tone, text_normalize
|
31 |
+
|
32 |
+
# Get path settings
|
33 |
+
with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
|
34 |
+
path_config: dict[str, str] = yaml.safe_load(f.read())
|
35 |
+
# dataset_root = path_config["dataset_root"]
|
36 |
+
assets_root = path_config["assets_root"]
|
37 |
+
|
38 |
+
languages = [l.value for l in Languages]
|
39 |
+
|
40 |
+
|
41 |
+
def tts_fn(
|
42 |
+
model_name,
|
43 |
+
model_path,
|
44 |
+
text,
|
45 |
+
language,
|
46 |
+
reference_audio_path,
|
47 |
+
sdp_ratio,
|
48 |
+
noise_scale,
|
49 |
+
noise_scale_w,
|
50 |
+
length_scale,
|
51 |
+
line_split,
|
52 |
+
split_interval,
|
53 |
+
assist_text,
|
54 |
+
assist_text_weight,
|
55 |
+
use_assist_text,
|
56 |
+
style,
|
57 |
+
style_weight,
|
58 |
+
kata_tone_json_str,
|
59 |
+
use_tone,
|
60 |
+
speaker,
|
61 |
+
pitch_scale,
|
62 |
+
intonation_scale,
|
63 |
+
):
|
64 |
+
model_holder.load_model_gr(model_name, model_path)
|
65 |
+
|
66 |
+
wrong_tone_message = ""
|
67 |
+
kata_tone: Optional[list[tuple[str, int]]] = None
|
68 |
+
if use_tone and kata_tone_json_str != "":
|
69 |
+
if language != "JP":
|
70 |
+
logger.warning("Only Japanese is supported for tone generation.")
|
71 |
+
wrong_tone_message = "アクセント指定は現在日本語のみ対応しています。"
|
72 |
+
if line_split:
|
73 |
+
logger.warning("Tone generation is not supported for line split.")
|
74 |
+
wrong_tone_message = (
|
75 |
+
"アクセント指定は改行で分けて生成を使わない場合のみ対応しています。"
|
76 |
+
)
|
77 |
+
try:
|
78 |
+
kata_tone = []
|
79 |
+
json_data = json.loads(kata_tone_json_str)
|
80 |
+
# tupleを使うように変換
|
81 |
+
for kana, tone in json_data:
|
82 |
+
assert isinstance(kana, str) and tone in (0, 1), f"{kana}, {tone}"
|
83 |
+
kata_tone.append((kana, tone))
|
84 |
+
except Exception as e:
|
85 |
+
logger.warning(f"Error occurred when parsing kana_tone_json: {e}")
|
86 |
+
wrong_tone_message = f"アクセント指定が不正です: {e}"
|
87 |
+
kata_tone = None
|
88 |
+
|
89 |
+
# toneは実際に音声合成に代入される際のみnot Noneになる
|
90 |
+
tone: Optional[list[int]] = None
|
91 |
+
if kata_tone is not None:
|
92 |
+
phone_tone = kata_tone2phone_tone(kata_tone)
|
93 |
+
tone = [t for _, t in phone_tone]
|
94 |
+
|
95 |
+
speaker_id = model_holder.current_model.spk2id[speaker]
|
96 |
+
|
97 |
+
start_time = datetime.datetime.now()
|
98 |
+
|
99 |
+
try:
|
100 |
+
sr, audio = model_holder.current_model.infer(
|
101 |
+
text=text,
|
102 |
+
language=language,
|
103 |
+
reference_audio_path=reference_audio_path,
|
104 |
+
sdp_ratio=sdp_ratio,
|
105 |
+
noise=noise_scale,
|
106 |
+
noisew=noise_scale_w,
|
107 |
+
length=length_scale,
|
108 |
+
line_split=line_split,
|
109 |
+
split_interval=split_interval,
|
110 |
+
assist_text=assist_text,
|
111 |
+
assist_text_weight=assist_text_weight,
|
112 |
+
use_assist_text=use_assist_text,
|
113 |
+
style=style,
|
114 |
+
style_weight=style_weight,
|
115 |
+
given_tone=tone,
|
116 |
+
sid=speaker_id,
|
117 |
+
pitch_scale=pitch_scale,
|
118 |
+
intonation_scale=intonation_scale,
|
119 |
+
)
|
120 |
+
except InvalidToneError as e:
|
121 |
+
logger.error(f"Tone error: {e}")
|
122 |
+
return f"Error: アクセント指定が不正です:\n{e}", None, kata_tone_json_str
|
123 |
+
except ValueError as e:
|
124 |
+
logger.error(f"Value error: {e}")
|
125 |
+
return f"Error: {e}", None, kata_tone_json_str
|
126 |
+
|
127 |
+
end_time = datetime.datetime.now()
|
128 |
+
duration = (end_time - start_time).total_seconds()
|
129 |
+
|
130 |
+
if tone is None and language == "JP":
|
131 |
+
# アクセント指定に使えるようにアクセント情報を返す
|
132 |
+
norm_text = text_normalize(text)
|
133 |
+
kata_tone = g2kata_tone(norm_text)
|
134 |
+
kata_tone_json_str = json.dumps(kata_tone, ensure_ascii=False)
|
135 |
+
elif tone is None:
|
136 |
+
kata_tone_json_str = ""
|
137 |
+
message = f"Success, time: {duration} seconds."
|
138 |
+
if wrong_tone_message != "":
|
139 |
+
message = wrong_tone_message + "\n" + message
|
140 |
+
return message, (sr, audio), kata_tone_json_str
|
141 |
+
|
142 |
+
|
143 |
+
initial_text = "こんにちは、初めまして。あなたの名前はなんていうの?"
|
144 |
+
|
145 |
+
examples = [
|
146 |
+
[initial_text, "JP"],
|
147 |
+
[
|
148 |
+
"""あなたがそんなこと言うなんて、私はとっても嬉しい。
|
149 |
+
あなたがそんなこと言うなんて、私はとっても怒ってる。
|
150 |
+
あなたがそんなこと言うなんて、私はとっても驚いてる。
|
151 |
+
あなたがそんなこと言うなんて、私はとっても辛い。""",
|
152 |
+
"JP",
|
153 |
+
],
|
154 |
+
[ # ChatGPTに考えてもらった告白セリフ
|
155 |
+
"""私、ずっと前からあなたのことを見てきました。あなたの笑顔、優しさ、強さに、心惹かれていたんです。
|
156 |
+
友達として過ごす中で、あなたのことがだんだんと特別な存在になっていくのがわかりました。
|
157 |
+
えっと、私、あなたのことが好きです!もしよければ、私と付き合ってくれませんか?""",
|
158 |
+
"JP",
|
159 |
+
],
|
160 |
+
[ # 夏目漱石『吾輩は猫である』
|
161 |
+
"""吾輩は猫である。名前はまだ無い。
|
162 |
+
どこで生れたかとんと見当がつかぬ。なんでも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。
|
163 |
+
吾輩はここで初めて人間というものを見た。しかもあとで聞くと、それは書生という、人間中で一番獰悪な種族であったそうだ。
|
164 |
+
この書生というのは時々我々を捕まえて煮て食うという話である。""",
|
165 |
+
"JP",
|
166 |
+
],
|
167 |
+
[ # 梶井基次郎『桜の樹の下には』
|
168 |
+
"""桜の樹の下には屍体が埋まっている!これは信じていいことなんだよ。
|
169 |
+
何故って、桜の花があんなにも見事に咲くなんて信じられないことじゃないか。俺はあの美しさが信じられないので、このにさんにち不安だった。
|
170 |
+
しかしいま、やっとわかるときが来た。桜の樹の下には屍体が埋まっている。これは信じていいことだ。""",
|
171 |
+
"JP",
|
172 |
+
],
|
173 |
+
[ # ChatGPTと考えた、感情を表すセリフ
|
174 |
+
"""やったー!テストで満点取れた!私とっても嬉しいな!
|
175 |
+
どうして私の意見を無視するの?許せない!ムカつく!あんたなんか死ねばいいのに。
|
176 |
+
あはははっ!この漫画めっちゃ笑える、見てよこれ、ふふふ、あはは。
|
177 |
+
あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しい。""",
|
178 |
+
"JP",
|
179 |
+
],
|
180 |
+
[ # 上の丁寧語バージョン
|
181 |
+
"""やりました!テストで満点取れましたよ!私とっても嬉しいです!
|
182 |
+
どうして私の意見を無視するんですか?許せません!ムカつきます!あんたなんか死んでください。
|
183 |
+
あはははっ!この漫画めっちゃ笑えます、見てくださいこれ、ふふふ、あはは。
|
184 |
+
あなたがいなくなって、私は一人になっちゃって、泣いちゃいそうなほど悲しいです。""",
|
185 |
+
"JP",
|
186 |
+
],
|
187 |
+
[ # ChatGPTに考えてもらった音声合成の説明文章
|
188 |
+
"""音声合成は、機械学習を活用して、テキストから人の声を再現する技術です。この技術は、言語の構造を解析し、それに基づいて音声を生成します。
|
189 |
+
この分野の最新の研究成果を使うと、より自然で表現豊かな音声の生成が可能である。深層学習の応用により、感情やアクセントを含む声質の微妙な変化も再現することが出来る。""",
|
190 |
+
"JP",
|
191 |
+
],
|
192 |
+
[
|
193 |
+
"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.",
|
194 |
+
"EN",
|
195 |
+
],
|
196 |
+
[
|
197 |
+
"语音合成是人工制造人类语音。用于此目的的计算机系统称为语音合成器,可以通过软件或硬件产品实现。",
|
198 |
+
"ZH",
|
199 |
+
],
|
200 |
+
]
|
201 |
+
|
202 |
+
initial_md = f"""
|
203 |
+
# Style-Bert-VITS2 ver {LATEST_VERSION} 音声合成
|
204 |
+
|
205 |
+
- Ver 2.3で追加されたエディターのほうが実際に読み上げさせるには使いやすいかもしれません。`Editor.bat`か`python server_editor.py`で起動できます。
|
206 |
+
|
207 |
+
- 初期からある[jvnvのモデル](https://huggingface.co/litagin/style_bert_vits2_jvnv)は、[JVNVコーパス(言語音声と非言語音声を持つ日本語感情音声コーパス)](https://sites.google.com/site/shinnosuketakamichi/research-topics/jvnv_corpus)で学習されたモデルです。ライセンスは[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.ja)です。
|
208 |
+
"""
|
209 |
+
|
210 |
+
how_to_md = """
|
211 |
+
下のように`model_assets`ディレクトリの中にモデルファイルたちを置いてください。
|
212 |
+
```
|
213 |
+
model_assets
|
214 |
+
├── your_model
|
215 |
+
│ ├── config.json
|
216 |
+
│ ├── your_model_file1.safetensors
|
217 |
+
│ ├── your_model_file2.safetensors
|
218 |
+
│ ├── ...
|
219 |
+
│ └── style_vectors.npy
|
220 |
+
└── another_model
|
221 |
+
├── ...
|
222 |
+
```
|
223 |
+
各モデルにはファイルたちが必要です:
|
224 |
+
- `config.json`:学習時の設定ファイル
|
225 |
+
- `*.safetensors`:学習済みモデルファイル(1つ以上が必要、複数可)
|
226 |
+
- `style_vectors.npy`:スタイルベクトルファイル
|
227 |
+
|
228 |
+
上2つは`Train.bat`による学習で自動的に正しい位置に保存されます。`style_vectors.npy`は`Style.bat`を実行して指示に従って生成してください。
|
229 |
+
"""
|
230 |
+
|
231 |
+
style_md = f"""
|
232 |
+
- プリセットまたは音声ファイルから読み上げの声音・感情・スタイルのようなものを制御できます。
|
233 |
+
- デフォルトの{DEFAULT_STYLE}でも、十分に読み上げる文に応じた感情で感情豊かに読み上げられます。このスタイル制御は、それを重み付きで上書きするような感じです。
|
234 |
+
- 強さを大きくしすぎると発音が変になったり声にならなかったりと崩壊することがあります。
|
235 |
+
- どのくらいに強さがいいかはモデルやスタイルによって異なるようです。
|
236 |
+
- 音声ファイルを入力する場合は、学習データと似た声音の話者(特に同じ性別)でないとよい効果が出ないかもしれません。
|
237 |
+
"""
|
238 |
+
|
239 |
+
|
240 |
+
def make_interactive():
|
241 |
+
return gr.update(interactive=True, value="音声合成")
|
242 |
+
|
243 |
+
|
244 |
+
def make_non_interactive():
|
245 |
+
return gr.update(interactive=False, value="音声合成(モデルをロードしてください)")
|
246 |
+
|
247 |
+
|
248 |
+
def gr_util(item):
|
249 |
+
if item == "プリセットから選ぶ":
|
250 |
+
return (gr.update(visible=True), gr.Audio(visible=False, value=None))
|
251 |
+
else:
|
252 |
+
return (gr.update(visible=False), gr.update(visible=True))
|
253 |
+
|
254 |
+
|
255 |
+
if __name__ == "__main__":
|
256 |
+
parser = argparse.ArgumentParser()
|
257 |
+
parser.add_argument("--cpu", action="store_true", help="Use CPU instead of GPU")
|
258 |
+
parser.add_argument(
|
259 |
+
"--dir", "-d", type=str, help="Model directory", default=assets_root
|
260 |
+
)
|
261 |
+
parser.add_argument(
|
262 |
+
"--share", action="store_true", help="Share this app publicly", default=False
|
263 |
+
)
|
264 |
+
parser.add_argument(
|
265 |
+
"--server-name",
|
266 |
+
type=str,
|
267 |
+
default=None,
|
268 |
+
help="Server name for Gradio app",
|
269 |
+
)
|
270 |
+
parser.add_argument(
|
271 |
+
"--no-autolaunch",
|
272 |
+
action="store_true",
|
273 |
+
default=False,
|
274 |
+
help="Do not launch app automatically",
|
275 |
+
)
|
276 |
+
args = parser.parse_args()
|
277 |
+
model_dir = Path(args.dir)
|
278 |
+
|
279 |
+
if args.cpu:
|
280 |
+
device = "cpu"
|
281 |
+
else:
|
282 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
283 |
+
|
284 |
+
model_holder = ModelHolder(model_dir, device)
|
285 |
+
|
286 |
+
model_names = model_holder.model_names
|
287 |
+
if len(model_names) == 0:
|
288 |
+
logger.error(
|
289 |
+
f"モデルが見つかりませんでした。{model_dir}にモデルを置いてください。"
|
290 |
+
)
|
291 |
+
sys.exit(1)
|
292 |
+
initial_id = 0
|
293 |
+
initial_pth_files = model_holder.model_files_dict[model_names[initial_id]]
|
294 |
+
|
295 |
+
with gr.Blocks(theme=GRADIO_THEME) as app:
|
296 |
+
gr.Markdown(initial_md)
|
297 |
+
with gr.Accordion(label="使い方", open=False):
|
298 |
+
gr.Markdown(how_to_md)
|
299 |
+
with gr.Row():
|
300 |
+
with gr.Column():
|
301 |
+
with gr.Row():
|
302 |
+
with gr.Column(scale=3):
|
303 |
+
model_name = gr.Dropdown(
|
304 |
+
label="モデル一覧",
|
305 |
+
choices=model_names,
|
306 |
+
value=model_names[initial_id],
|
307 |
+
)
|
308 |
+
model_path = gr.Dropdown(
|
309 |
+
label="モデルファイル",
|
310 |
+
choices=initial_pth_files,
|
311 |
+
value=initial_pth_files[0],
|
312 |
+
)
|
313 |
+
refresh_button = gr.Button("更新", scale=1, visible=True)
|
314 |
+
load_button = gr.Button("ロード", scale=1, variant="primary")
|
315 |
+
text_input = gr.TextArea(label="テキスト", value=initial_text)
|
316 |
+
pitch_scale = gr.Slider(
|
317 |
+
minimum=0.8,
|
318 |
+
maximum=1.5,
|
319 |
+
value=1,
|
320 |
+
step=0.05,
|
321 |
+
label="音程(1以外では音質劣化)",
|
322 |
+
visible=False, # pyworldが必要
|
323 |
+
)
|
324 |
+
intonation_scale = gr.Slider(
|
325 |
+
minimum=0,
|
326 |
+
maximum=2,
|
327 |
+
value=1,
|
328 |
+
step=0.1,
|
329 |
+
label="抑揚(1以外では音質劣化)",
|
330 |
+
visible=False, # pyworldが必要
|
331 |
+
)
|
332 |
+
|
333 |
+
line_split = gr.Checkbox(
|
334 |
+
label="改行で分けて生成(分けたほうが感情が乗ります)",
|
335 |
+
value=DEFAULT_LINE_SPLIT,
|
336 |
+
)
|
337 |
+
split_interval = gr.Slider(
|
338 |
+
minimum=0.0,
|
339 |
+
maximum=2,
|
340 |
+
value=DEFAULT_SPLIT_INTERVAL,
|
341 |
+
step=0.1,
|
342 |
+
label="改行ごとに挟む無音の長さ(秒)",
|
343 |
+
)
|
344 |
+
line_split.change(
|
345 |
+
lambda x: (gr.Slider(visible=x)),
|
346 |
+
inputs=[line_split],
|
347 |
+
outputs=[split_interval],
|
348 |
+
)
|
349 |
+
tone = gr.Textbox(
|
350 |
+
label="アクセント調整(数値は 0=低 か1=高 のみ)",
|
351 |
+
info="改行で分けない場合のみ使えます。万能ではありません。",
|
352 |
+
)
|
353 |
+
use_tone = gr.Checkbox(label="アクセント調整を使う", value=False)
|
354 |
+
use_tone.change(
|
355 |
+
lambda x: (gr.Checkbox(value=False) if x else gr.Checkbox()),
|
356 |
+
inputs=[use_tone],
|
357 |
+
outputs=[line_split],
|
358 |
+
)
|
359 |
+
language = gr.Dropdown(choices=languages, value="JP", label="Language")
|
360 |
+
speaker = gr.Dropdown(label="話者")
|
361 |
+
with gr.Accordion(label="詳細設定", open=False):
|
362 |
+
sdp_ratio = gr.Slider(
|
363 |
+
minimum=0,
|
364 |
+
maximum=1,
|
365 |
+
value=DEFAULT_SDP_RATIO,
|
366 |
+
step=0.1,
|
367 |
+
label="SDP Ratio",
|
368 |
+
)
|
369 |
+
noise_scale = gr.Slider(
|
370 |
+
minimum=0.1,
|
371 |
+
maximum=2,
|
372 |
+
value=DEFAULT_NOISE,
|
373 |
+
step=0.1,
|
374 |
+
label="Noise",
|
375 |
+
)
|
376 |
+
noise_scale_w = gr.Slider(
|
377 |
+
minimum=0.1,
|
378 |
+
maximum=2,
|
379 |
+
value=DEFAULT_NOISEW,
|
380 |
+
step=0.1,
|
381 |
+
label="Noise_W",
|
382 |
+
)
|
383 |
+
length_scale = gr.Slider(
|
384 |
+
minimum=0.1,
|
385 |
+
maximum=2,
|
386 |
+
value=DEFAULT_LENGTH,
|
387 |
+
step=0.1,
|
388 |
+
label="Length",
|
389 |
+
)
|
390 |
+
use_assist_text = gr.Checkbox(
|
391 |
+
label="Assist textを使う", value=False
|
392 |
+
)
|
393 |
+
assist_text = gr.Textbox(
|
394 |
+
label="Assist text",
|
395 |
+
placeholder="どうして私の意見を無視するの?許せない、ムカつく!死ねばいいのに。",
|
396 |
+
info="このテキストの読み上げと似た声音・感情になりやすくなります。ただ抑揚やテンポ等が犠牲になる傾向があります。",
|
397 |
+
visible=False,
|
398 |
+
)
|
399 |
+
assist_text_weight = gr.Slider(
|
400 |
+
minimum=0,
|
401 |
+
maximum=1,
|
402 |
+
value=DEFAULT_ASSIST_TEXT_WEIGHT,
|
403 |
+
step=0.1,
|
404 |
+
label="Assist textの強さ",
|
405 |
+
visible=False,
|
406 |
+
)
|
407 |
+
use_assist_text.change(
|
408 |
+
lambda x: (gr.Textbox(visible=x), gr.Slider(visible=x)),
|
409 |
+
inputs=[use_assist_text],
|
410 |
+
outputs=[assist_text, assist_text_weight],
|
411 |
+
)
|
412 |
+
with gr.Column():
|
413 |
+
with gr.Accordion("スタイルについて詳細", open=False):
|
414 |
+
gr.Markdown(style_md)
|
415 |
+
style_mode = gr.Radio(
|
416 |
+
["プリセットから選ぶ", "音声ファイルを入力"],
|
417 |
+
label="スタイルの指定方法",
|
418 |
+
value="プリセットから選ぶ",
|
419 |
+
)
|
420 |
+
style = gr.Dropdown(
|
421 |
+
label=f"スタイル({DEFAULT_STYLE}が平均スタイル)",
|
422 |
+
choices=["モデルをロードしてください"],
|
423 |
+
value="モデルをロードしてください",
|
424 |
+
)
|
425 |
+
style_weight = gr.Slider(
|
426 |
+
minimum=0,
|
427 |
+
maximum=50,
|
428 |
+
value=DEFAULT_STYLE_WEIGHT,
|
429 |
+
step=0.1,
|
430 |
+
label="スタイルの強さ",
|
431 |
+
)
|
432 |
+
ref_audio_path = gr.Audio(
|
433 |
+
label="参照音声", type="filepath", visible=False
|
434 |
+
)
|
435 |
+
tts_button = gr.Button(
|
436 |
+
"音声合成(モデルをロードしてください)",
|
437 |
+
variant="primary",
|
438 |
+
interactive=False,
|
439 |
+
)
|
440 |
+
text_output = gr.Textbox(label="情報")
|
441 |
+
audio_output = gr.Audio(label="結果")
|
442 |
+
with gr.Accordion("テキスト例", open=False):
|
443 |
+
gr.Examples(examples, inputs=[text_input, language])
|
444 |
+
|
445 |
+
tts_button.click(
|
446 |
+
tts_fn,
|
447 |
+
inputs=[
|
448 |
+
model_name,
|
449 |
+
model_path,
|
450 |
+
text_input,
|
451 |
+
language,
|
452 |
+
ref_audio_path,
|
453 |
+
sdp_ratio,
|
454 |
+
noise_scale,
|
455 |
+
noise_scale_w,
|
456 |
+
length_scale,
|
457 |
+
line_split,
|
458 |
+
split_interval,
|
459 |
+
assist_text,
|
460 |
+
assist_text_weight,
|
461 |
+
use_assist_text,
|
462 |
+
style,
|
463 |
+
style_weight,
|
464 |
+
tone,
|
465 |
+
use_tone,
|
466 |
+
speaker,
|
467 |
+
pitch_scale,
|
468 |
+
intonation_scale,
|
469 |
+
],
|
470 |
+
outputs=[text_output, audio_output, tone],
|
471 |
+
)
|
472 |
+
|
473 |
+
model_name.change(
|
474 |
+
model_holder.update_model_files_gr,
|
475 |
+
inputs=[model_name],
|
476 |
+
outputs=[model_path],
|
477 |
+
)
|
478 |
+
|
479 |
+
model_path.change(make_non_interactive, outputs=[tts_button])
|
480 |
+
|
481 |
+
refresh_button.click(
|
482 |
+
model_holder.update_model_names_gr,
|
483 |
+
outputs=[model_name, model_path, tts_button],
|
484 |
+
)
|
485 |
+
|
486 |
+
load_button.click(
|
487 |
+
model_holder.load_model_gr,
|
488 |
+
inputs=[model_name, model_path],
|
489 |
+
outputs=[style, tts_button, speaker],
|
490 |
+
)
|
491 |
+
|
492 |
+
style_mode.change(
|
493 |
+
gr_util,
|
494 |
+
inputs=[style_mode],
|
495 |
+
outputs=[style, ref_audio_path],
|
496 |
+
)
|
497 |
+
|
498 |
+
app.launch(
|
499 |
+
inbrowser=not args.no_autolaunch, share=args.share, server_name=args.server_name
|
500 |
+
)
|
attentions.py
ADDED
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch import nn
|
4 |
+
from torch.nn import functional as F
|
5 |
+
|
6 |
+
import commons
|
7 |
+
from common.log import logger as logging
|
8 |
+
|
9 |
+
|
10 |
+
class LayerNorm(nn.Module):
|
11 |
+
def __init__(self, channels, eps=1e-5):
|
12 |
+
super().__init__()
|
13 |
+
self.channels = channels
|
14 |
+
self.eps = eps
|
15 |
+
|
16 |
+
self.gamma = nn.Parameter(torch.ones(channels))
|
17 |
+
self.beta = nn.Parameter(torch.zeros(channels))
|
18 |
+
|
19 |
+
def forward(self, x):
|
20 |
+
x = x.transpose(1, -1)
|
21 |
+
x = F.layer_norm(x, (self.channels,), self.gamma, self.beta, self.eps)
|
22 |
+
return x.transpose(1, -1)
|
23 |
+
|
24 |
+
|
25 |
+
@torch.jit.script
|
26 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
27 |
+
n_channels_int = n_channels[0]
|
28 |
+
in_act = input_a + input_b
|
29 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
30 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
31 |
+
acts = t_act * s_act
|
32 |
+
return acts
|
33 |
+
|
34 |
+
|
35 |
+
class Encoder(nn.Module):
|
36 |
+
def __init__(
|
37 |
+
self,
|
38 |
+
hidden_channels,
|
39 |
+
filter_channels,
|
40 |
+
n_heads,
|
41 |
+
n_layers,
|
42 |
+
kernel_size=1,
|
43 |
+
p_dropout=0.0,
|
44 |
+
window_size=4,
|
45 |
+
isflow=True,
|
46 |
+
**kwargs
|
47 |
+
):
|
48 |
+
super().__init__()
|
49 |
+
self.hidden_channels = hidden_channels
|
50 |
+
self.filter_channels = filter_channels
|
51 |
+
self.n_heads = n_heads
|
52 |
+
self.n_layers = n_layers
|
53 |
+
self.kernel_size = kernel_size
|
54 |
+
self.p_dropout = p_dropout
|
55 |
+
self.window_size = window_size
|
56 |
+
# if isflow:
|
57 |
+
# cond_layer = torch.nn.Conv1d(256, 2*hidden_channels*n_layers, 1)
|
58 |
+
# self.cond_pre = torch.nn.Conv1d(hidden_channels, 2*hidden_channels, 1)
|
59 |
+
# self.cond_layer = weight_norm(cond_layer, name='weight')
|
60 |
+
# self.gin_channels = 256
|
61 |
+
self.cond_layer_idx = self.n_layers
|
62 |
+
if "gin_channels" in kwargs:
|
63 |
+
self.gin_channels = kwargs["gin_channels"]
|
64 |
+
if self.gin_channels != 0:
|
65 |
+
self.spk_emb_linear = nn.Linear(self.gin_channels, self.hidden_channels)
|
66 |
+
# vits2 says 3rd block, so idx is 2 by default
|
67 |
+
self.cond_layer_idx = (
|
68 |
+
kwargs["cond_layer_idx"] if "cond_layer_idx" in kwargs else 2
|
69 |
+
)
|
70 |
+
# logging.debug(self.gin_channels, self.cond_layer_idx)
|
71 |
+
assert (
|
72 |
+
self.cond_layer_idx < self.n_layers
|
73 |
+
), "cond_layer_idx should be less than n_layers"
|
74 |
+
self.drop = nn.Dropout(p_dropout)
|
75 |
+
self.attn_layers = nn.ModuleList()
|
76 |
+
self.norm_layers_1 = nn.ModuleList()
|
77 |
+
self.ffn_layers = nn.ModuleList()
|
78 |
+
self.norm_layers_2 = nn.ModuleList()
|
79 |
+
for i in range(self.n_layers):
|
80 |
+
self.attn_layers.append(
|
81 |
+
MultiHeadAttention(
|
82 |
+
hidden_channels,
|
83 |
+
hidden_channels,
|
84 |
+
n_heads,
|
85 |
+
p_dropout=p_dropout,
|
86 |
+
window_size=window_size,
|
87 |
+
)
|
88 |
+
)
|
89 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
90 |
+
self.ffn_layers.append(
|
91 |
+
FFN(
|
92 |
+
hidden_channels,
|
93 |
+
hidden_channels,
|
94 |
+
filter_channels,
|
95 |
+
kernel_size,
|
96 |
+
p_dropout=p_dropout,
|
97 |
+
)
|
98 |
+
)
|
99 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
100 |
+
|
101 |
+
def forward(self, x, x_mask, g=None):
|
102 |
+
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
103 |
+
x = x * x_mask
|
104 |
+
for i in range(self.n_layers):
|
105 |
+
if i == self.cond_layer_idx and g is not None:
|
106 |
+
g = self.spk_emb_linear(g.transpose(1, 2))
|
107 |
+
g = g.transpose(1, 2)
|
108 |
+
x = x + g
|
109 |
+
x = x * x_mask
|
110 |
+
y = self.attn_layers[i](x, x, attn_mask)
|
111 |
+
y = self.drop(y)
|
112 |
+
x = self.norm_layers_1[i](x + y)
|
113 |
+
|
114 |
+
y = self.ffn_layers[i](x, x_mask)
|
115 |
+
y = self.drop(y)
|
116 |
+
x = self.norm_layers_2[i](x + y)
|
117 |
+
x = x * x_mask
|
118 |
+
return x
|
119 |
+
|
120 |
+
|
121 |
+
class Decoder(nn.Module):
|
122 |
+
def __init__(
|
123 |
+
self,
|
124 |
+
hidden_channels,
|
125 |
+
filter_channels,
|
126 |
+
n_heads,
|
127 |
+
n_layers,
|
128 |
+
kernel_size=1,
|
129 |
+
p_dropout=0.0,
|
130 |
+
proximal_bias=False,
|
131 |
+
proximal_init=True,
|
132 |
+
**kwargs
|
133 |
+
):
|
134 |
+
super().__init__()
|
135 |
+
self.hidden_channels = hidden_channels
|
136 |
+
self.filter_channels = filter_channels
|
137 |
+
self.n_heads = n_heads
|
138 |
+
self.n_layers = n_layers
|
139 |
+
self.kernel_size = kernel_size
|
140 |
+
self.p_dropout = p_dropout
|
141 |
+
self.proximal_bias = proximal_bias
|
142 |
+
self.proximal_init = proximal_init
|
143 |
+
|
144 |
+
self.drop = nn.Dropout(p_dropout)
|
145 |
+
self.self_attn_layers = nn.ModuleList()
|
146 |
+
self.norm_layers_0 = nn.ModuleList()
|
147 |
+
self.encdec_attn_layers = nn.ModuleList()
|
148 |
+
self.norm_layers_1 = nn.ModuleList()
|
149 |
+
self.ffn_layers = nn.ModuleList()
|
150 |
+
self.norm_layers_2 = nn.ModuleList()
|
151 |
+
for i in range(self.n_layers):
|
152 |
+
self.self_attn_layers.append(
|
153 |
+
MultiHeadAttention(
|
154 |
+
hidden_channels,
|
155 |
+
hidden_channels,
|
156 |
+
n_heads,
|
157 |
+
p_dropout=p_dropout,
|
158 |
+
proximal_bias=proximal_bias,
|
159 |
+
proximal_init=proximal_init,
|
160 |
+
)
|
161 |
+
)
|
162 |
+
self.norm_layers_0.append(LayerNorm(hidden_channels))
|
163 |
+
self.encdec_attn_layers.append(
|
164 |
+
MultiHeadAttention(
|
165 |
+
hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout
|
166 |
+
)
|
167 |
+
)
|
168 |
+
self.norm_layers_1.append(LayerNorm(hidden_channels))
|
169 |
+
self.ffn_layers.append(
|
170 |
+
FFN(
|
171 |
+
hidden_channels,
|
172 |
+
hidden_channels,
|
173 |
+
filter_channels,
|
174 |
+
kernel_size,
|
175 |
+
p_dropout=p_dropout,
|
176 |
+
causal=True,
|
177 |
+
)
|
178 |
+
)
|
179 |
+
self.norm_layers_2.append(LayerNorm(hidden_channels))
|
180 |
+
|
181 |
+
def forward(self, x, x_mask, h, h_mask):
|
182 |
+
"""
|
183 |
+
x: decoder input
|
184 |
+
h: encoder output
|
185 |
+
"""
|
186 |
+
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
|
187 |
+
device=x.device, dtype=x.dtype
|
188 |
+
)
|
189 |
+
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
|
190 |
+
x = x * x_mask
|
191 |
+
for i in range(self.n_layers):
|
192 |
+
y = self.self_attn_layers[i](x, x, self_attn_mask)
|
193 |
+
y = self.drop(y)
|
194 |
+
x = self.norm_layers_0[i](x + y)
|
195 |
+
|
196 |
+
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
|
197 |
+
y = self.drop(y)
|
198 |
+
x = self.norm_layers_1[i](x + y)
|
199 |
+
|
200 |
+
y = self.ffn_layers[i](x, x_mask)
|
201 |
+
y = self.drop(y)
|
202 |
+
x = self.norm_layers_2[i](x + y)
|
203 |
+
x = x * x_mask
|
204 |
+
return x
|
205 |
+
|
206 |
+
|
207 |
+
class MultiHeadAttention(nn.Module):
|
208 |
+
def __init__(
|
209 |
+
self,
|
210 |
+
channels,
|
211 |
+
out_channels,
|
212 |
+
n_heads,
|
213 |
+
p_dropout=0.0,
|
214 |
+
window_size=None,
|
215 |
+
heads_share=True,
|
216 |
+
block_length=None,
|
217 |
+
proximal_bias=False,
|
218 |
+
proximal_init=False,
|
219 |
+
):
|
220 |
+
super().__init__()
|
221 |
+
assert channels % n_heads == 0
|
222 |
+
|
223 |
+
self.channels = channels
|
224 |
+
self.out_channels = out_channels
|
225 |
+
self.n_heads = n_heads
|
226 |
+
self.p_dropout = p_dropout
|
227 |
+
self.window_size = window_size
|
228 |
+
self.heads_share = heads_share
|
229 |
+
self.block_length = block_length
|
230 |
+
self.proximal_bias = proximal_bias
|
231 |
+
self.proximal_init = proximal_init
|
232 |
+
self.attn = None
|
233 |
+
|
234 |
+
self.k_channels = channels // n_heads
|
235 |
+
self.conv_q = nn.Conv1d(channels, channels, 1)
|
236 |
+
self.conv_k = nn.Conv1d(channels, channels, 1)
|
237 |
+
self.conv_v = nn.Conv1d(channels, channels, 1)
|
238 |
+
self.conv_o = nn.Conv1d(channels, out_channels, 1)
|
239 |
+
self.drop = nn.Dropout(p_dropout)
|
240 |
+
|
241 |
+
if window_size is not None:
|
242 |
+
n_heads_rel = 1 if heads_share else n_heads
|
243 |
+
rel_stddev = self.k_channels**-0.5
|
244 |
+
self.emb_rel_k = nn.Parameter(
|
245 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
246 |
+
* rel_stddev
|
247 |
+
)
|
248 |
+
self.emb_rel_v = nn.Parameter(
|
249 |
+
torch.randn(n_heads_rel, window_size * 2 + 1, self.k_channels)
|
250 |
+
* rel_stddev
|
251 |
+
)
|
252 |
+
|
253 |
+
nn.init.xavier_uniform_(self.conv_q.weight)
|
254 |
+
nn.init.xavier_uniform_(self.conv_k.weight)
|
255 |
+
nn.init.xavier_uniform_(self.conv_v.weight)
|
256 |
+
if proximal_init:
|
257 |
+
with torch.no_grad():
|
258 |
+
self.conv_k.weight.copy_(self.conv_q.weight)
|
259 |
+
self.conv_k.bias.copy_(self.conv_q.bias)
|
260 |
+
|
261 |
+
def forward(self, x, c, attn_mask=None):
|
262 |
+
q = self.conv_q(x)
|
263 |
+
k = self.conv_k(c)
|
264 |
+
v = self.conv_v(c)
|
265 |
+
|
266 |
+
x, self.attn = self.attention(q, k, v, mask=attn_mask)
|
267 |
+
|
268 |
+
x = self.conv_o(x)
|
269 |
+
return x
|
270 |
+
|
271 |
+
def attention(self, query, key, value, mask=None):
|
272 |
+
# reshape [b, d, t] -> [b, n_h, t, d_k]
|
273 |
+
b, d, t_s, t_t = (*key.size(), query.size(2))
|
274 |
+
query = query.view(b, self.n_heads, self.k_channels, t_t).transpose(2, 3)
|
275 |
+
key = key.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
276 |
+
value = value.view(b, self.n_heads, self.k_channels, t_s).transpose(2, 3)
|
277 |
+
|
278 |
+
scores = torch.matmul(query / math.sqrt(self.k_channels), key.transpose(-2, -1))
|
279 |
+
if self.window_size is not None:
|
280 |
+
assert (
|
281 |
+
t_s == t_t
|
282 |
+
), "Relative attention is only available for self-attention."
|
283 |
+
key_relative_embeddings = self._get_relative_embeddings(self.emb_rel_k, t_s)
|
284 |
+
rel_logits = self._matmul_with_relative_keys(
|
285 |
+
query / math.sqrt(self.k_channels), key_relative_embeddings
|
286 |
+
)
|
287 |
+
scores_local = self._relative_position_to_absolute_position(rel_logits)
|
288 |
+
scores = scores + scores_local
|
289 |
+
if self.proximal_bias:
|
290 |
+
assert t_s == t_t, "Proximal bias is only available for self-attention."
|
291 |
+
scores = scores + self._attention_bias_proximal(t_s).to(
|
292 |
+
device=scores.device, dtype=scores.dtype
|
293 |
+
)
|
294 |
+
if mask is not None:
|
295 |
+
scores = scores.masked_fill(mask == 0, -1e4)
|
296 |
+
if self.block_length is not None:
|
297 |
+
assert (
|
298 |
+
t_s == t_t
|
299 |
+
), "Local attention is only available for self-attention."
|
300 |
+
block_mask = (
|
301 |
+
torch.ones_like(scores)
|
302 |
+
.triu(-self.block_length)
|
303 |
+
.tril(self.block_length)
|
304 |
+
)
|
305 |
+
scores = scores.masked_fill(block_mask == 0, -1e4)
|
306 |
+
p_attn = F.softmax(scores, dim=-1) # [b, n_h, t_t, t_s]
|
307 |
+
p_attn = self.drop(p_attn)
|
308 |
+
output = torch.matmul(p_attn, value)
|
309 |
+
if self.window_size is not None:
|
310 |
+
relative_weights = self._absolute_position_to_relative_position(p_attn)
|
311 |
+
value_relative_embeddings = self._get_relative_embeddings(
|
312 |
+
self.emb_rel_v, t_s
|
313 |
+
)
|
314 |
+
output = output + self._matmul_with_relative_values(
|
315 |
+
relative_weights, value_relative_embeddings
|
316 |
+
)
|
317 |
+
output = (
|
318 |
+
output.transpose(2, 3).contiguous().view(b, d, t_t)
|
319 |
+
) # [b, n_h, t_t, d_k] -> [b, d, t_t]
|
320 |
+
return output, p_attn
|
321 |
+
|
322 |
+
def _matmul_with_relative_values(self, x, y):
|
323 |
+
"""
|
324 |
+
x: [b, h, l, m]
|
325 |
+
y: [h or 1, m, d]
|
326 |
+
ret: [b, h, l, d]
|
327 |
+
"""
|
328 |
+
ret = torch.matmul(x, y.unsqueeze(0))
|
329 |
+
return ret
|
330 |
+
|
331 |
+
def _matmul_with_relative_keys(self, x, y):
|
332 |
+
"""
|
333 |
+
x: [b, h, l, d]
|
334 |
+
y: [h or 1, m, d]
|
335 |
+
ret: [b, h, l, m]
|
336 |
+
"""
|
337 |
+
ret = torch.matmul(x, y.unsqueeze(0).transpose(-2, -1))
|
338 |
+
return ret
|
339 |
+
|
340 |
+
def _get_relative_embeddings(self, relative_embeddings, length):
|
341 |
+
2 * self.window_size + 1
|
342 |
+
# Pad first before slice to avoid using cond ops.
|
343 |
+
pad_length = max(length - (self.window_size + 1), 0)
|
344 |
+
slice_start_position = max((self.window_size + 1) - length, 0)
|
345 |
+
slice_end_position = slice_start_position + 2 * length - 1
|
346 |
+
if pad_length > 0:
|
347 |
+
padded_relative_embeddings = F.pad(
|
348 |
+
relative_embeddings,
|
349 |
+
commons.convert_pad_shape([[0, 0], [pad_length, pad_length], [0, 0]]),
|
350 |
+
)
|
351 |
+
else:
|
352 |
+
padded_relative_embeddings = relative_embeddings
|
353 |
+
used_relative_embeddings = padded_relative_embeddings[
|
354 |
+
:, slice_start_position:slice_end_position
|
355 |
+
]
|
356 |
+
return used_relative_embeddings
|
357 |
+
|
358 |
+
def _relative_position_to_absolute_position(self, x):
|
359 |
+
"""
|
360 |
+
x: [b, h, l, 2*l-1]
|
361 |
+
ret: [b, h, l, l]
|
362 |
+
"""
|
363 |
+
batch, heads, length, _ = x.size()
|
364 |
+
# Concat columns of pad to shift from relative to absolute indexing.
|
365 |
+
x = F.pad(x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, 1]]))
|
366 |
+
|
367 |
+
# Concat extra elements so to add up to shape (len+1, 2*len-1).
|
368 |
+
x_flat = x.view([batch, heads, length * 2 * length])
|
369 |
+
x_flat = F.pad(
|
370 |
+
x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [0, length - 1]])
|
371 |
+
)
|
372 |
+
|
373 |
+
# Reshape and slice out the padded elements.
|
374 |
+
x_final = x_flat.view([batch, heads, length + 1, 2 * length - 1])[
|
375 |
+
:, :, :length, length - 1 :
|
376 |
+
]
|
377 |
+
return x_final
|
378 |
+
|
379 |
+
def _absolute_position_to_relative_position(self, x):
|
380 |
+
"""
|
381 |
+
x: [b, h, l, l]
|
382 |
+
ret: [b, h, l, 2*l-1]
|
383 |
+
"""
|
384 |
+
batch, heads, length, _ = x.size()
|
385 |
+
# pad along column
|
386 |
+
x = F.pad(
|
387 |
+
x, commons.convert_pad_shape([[0, 0], [0, 0], [0, 0], [0, length - 1]])
|
388 |
+
)
|
389 |
+
x_flat = x.view([batch, heads, length**2 + length * (length - 1)])
|
390 |
+
# add 0's in the beginning that will skew the elements after reshape
|
391 |
+
x_flat = F.pad(x_flat, commons.convert_pad_shape([[0, 0], [0, 0], [length, 0]]))
|
392 |
+
x_final = x_flat.view([batch, heads, length, 2 * length])[:, :, :, 1:]
|
393 |
+
return x_final
|
394 |
+
|
395 |
+
def _attention_bias_proximal(self, length):
|
396 |
+
"""Bias for self-attention to encourage attention to close positions.
|
397 |
+
Args:
|
398 |
+
length: an integer scalar.
|
399 |
+
Returns:
|
400 |
+
a Tensor with shape [1, 1, length, length]
|
401 |
+
"""
|
402 |
+
r = torch.arange(length, dtype=torch.float32)
|
403 |
+
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
|
404 |
+
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
|
405 |
+
|
406 |
+
|
407 |
+
class FFN(nn.Module):
|
408 |
+
def __init__(
|
409 |
+
self,
|
410 |
+
in_channels,
|
411 |
+
out_channels,
|
412 |
+
filter_channels,
|
413 |
+
kernel_size,
|
414 |
+
p_dropout=0.0,
|
415 |
+
activation=None,
|
416 |
+
causal=False,
|
417 |
+
):
|
418 |
+
super().__init__()
|
419 |
+
self.in_channels = in_channels
|
420 |
+
self.out_channels = out_channels
|
421 |
+
self.filter_channels = filter_channels
|
422 |
+
self.kernel_size = kernel_size
|
423 |
+
self.p_dropout = p_dropout
|
424 |
+
self.activation = activation
|
425 |
+
self.causal = causal
|
426 |
+
|
427 |
+
if causal:
|
428 |
+
self.padding = self._causal_padding
|
429 |
+
else:
|
430 |
+
self.padding = self._same_padding
|
431 |
+
|
432 |
+
self.conv_1 = nn.Conv1d(in_channels, filter_channels, kernel_size)
|
433 |
+
self.conv_2 = nn.Conv1d(filter_channels, out_channels, kernel_size)
|
434 |
+
self.drop = nn.Dropout(p_dropout)
|
435 |
+
|
436 |
+
def forward(self, x, x_mask):
|
437 |
+
x = self.conv_1(self.padding(x * x_mask))
|
438 |
+
if self.activation == "gelu":
|
439 |
+
x = x * torch.sigmoid(1.702 * x)
|
440 |
+
else:
|
441 |
+
x = torch.relu(x)
|
442 |
+
x = self.drop(x)
|
443 |
+
x = self.conv_2(self.padding(x * x_mask))
|
444 |
+
return x * x_mask
|
445 |
+
|
446 |
+
def _causal_padding(self, x):
|
447 |
+
if self.kernel_size == 1:
|
448 |
+
return x
|
449 |
+
pad_l = self.kernel_size - 1
|
450 |
+
pad_r = 0
|
451 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
452 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
453 |
+
return x
|
454 |
+
|
455 |
+
def _same_padding(self, x):
|
456 |
+
if self.kernel_size == 1:
|
457 |
+
return x
|
458 |
+
pad_l = (self.kernel_size - 1) // 2
|
459 |
+
pad_r = self.kernel_size // 2
|
460 |
+
padding = [[0, 0], [0, 0], [pad_l, pad_r]]
|
461 |
+
x = F.pad(x, commons.convert_pad_shape(padding))
|
462 |
+
return x
|
bert/bert_models.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"deberta-v2-large-japanese-char-wwm": {
|
3 |
+
"repo_id": "ku-nlp/deberta-v2-large-japanese-char-wwm",
|
4 |
+
"files": ["pytorch_model.bin"]
|
5 |
+
},
|
6 |
+
"chinese-roberta-wwm-ext-large": {
|
7 |
+
"repo_id": "hfl/chinese-roberta-wwm-ext-large",
|
8 |
+
"files": ["pytorch_model.bin"]
|
9 |
+
},
|
10 |
+
"deberta-v3-large": {
|
11 |
+
"repo_id": "microsoft/deberta-v3-large",
|
12 |
+
"files": ["spm.model", "pytorch_model.bin"]
|
13 |
+
}
|
14 |
+
}
|
bert/chinese-roberta-wwm-ext-large/.gitattributes
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.tar.gz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
bert/chinese-roberta-wwm-ext-large/README.md
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language:
|
3 |
+
- zh
|
4 |
+
tags:
|
5 |
+
- bert
|
6 |
+
license: "apache-2.0"
|
7 |
+
---
|
8 |
+
|
9 |
+
# Please use 'Bert' related functions to load this model!
|
10 |
+
|
11 |
+
## Chinese BERT with Whole Word Masking
|
12 |
+
For further accelerating Chinese natural language processing, we provide **Chinese pre-trained BERT with Whole Word Masking**.
|
13 |
+
|
14 |
+
**[Pre-Training with Whole Word Masking for Chinese BERT](https://arxiv.org/abs/1906.08101)**
|
15 |
+
Yiming Cui, Wanxiang Che, Ting Liu, Bing Qin, Ziqing Yang, Shijin Wang, Guoping Hu
|
16 |
+
|
17 |
+
This repository is developed based on:https://github.com/google-research/bert
|
18 |
+
|
19 |
+
You may also interested in,
|
20 |
+
- Chinese BERT series: https://github.com/ymcui/Chinese-BERT-wwm
|
21 |
+
- Chinese MacBERT: https://github.com/ymcui/MacBERT
|
22 |
+
- Chinese ELECTRA: https://github.com/ymcui/Chinese-ELECTRA
|
23 |
+
- Chinese XLNet: https://github.com/ymcui/Chinese-XLNet
|
24 |
+
- Knowledge Distillation Toolkit - TextBrewer: https://github.com/airaria/TextBrewer
|
25 |
+
|
26 |
+
More resources by HFL: https://github.com/ymcui/HFL-Anthology
|
27 |
+
|
28 |
+
## Citation
|
29 |
+
If you find the technical report or resource is useful, please cite the following technical report in your paper.
|
30 |
+
- Primary: https://arxiv.org/abs/2004.13922
|
31 |
+
```
|
32 |
+
@inproceedings{cui-etal-2020-revisiting,
|
33 |
+
title = "Revisiting Pre-Trained Models for {C}hinese Natural Language Processing",
|
34 |
+
author = "Cui, Yiming and
|
35 |
+
Che, Wanxiang and
|
36 |
+
Liu, Ting and
|
37 |
+
Qin, Bing and
|
38 |
+
Wang, Shijin and
|
39 |
+
Hu, Guoping",
|
40 |
+
booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing: Findings",
|
41 |
+
month = nov,
|
42 |
+
year = "2020",
|
43 |
+
address = "Online",
|
44 |
+
publisher = "Association for Computational Linguistics",
|
45 |
+
url = "https://www.aclweb.org/anthology/2020.findings-emnlp.58",
|
46 |
+
pages = "657--668",
|
47 |
+
}
|
48 |
+
```
|
49 |
+
- Secondary: https://arxiv.org/abs/1906.08101
|
50 |
+
```
|
51 |
+
@article{chinese-bert-wwm,
|
52 |
+
title={Pre-Training with Whole Word Masking for Chinese BERT},
|
53 |
+
author={Cui, Yiming and Che, Wanxiang and Liu, Ting and Qin, Bing and Yang, Ziqing and Wang, Shijin and Hu, Guoping},
|
54 |
+
journal={arXiv preprint arXiv:1906.08101},
|
55 |
+
year={2019}
|
56 |
+
}
|
57 |
+
```
|
bert/chinese-roberta-wwm-ext-large/added_tokens.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{}
|
bert/chinese-roberta-wwm-ext-large/config.json
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"BertForMaskedLM"
|
4 |
+
],
|
5 |
+
"attention_probs_dropout_prob": 0.1,
|
6 |
+
"bos_token_id": 0,
|
7 |
+
"directionality": "bidi",
|
8 |
+
"eos_token_id": 2,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 1024,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 4096,
|
14 |
+
"layer_norm_eps": 1e-12,
|
15 |
+
"max_position_embeddings": 512,
|
16 |
+
"model_type": "bert",
|
17 |
+
"num_attention_heads": 16,
|
18 |
+
"num_hidden_layers": 24,
|
19 |
+
"output_past": true,
|
20 |
+
"pad_token_id": 0,
|
21 |
+
"pooler_fc_size": 768,
|
22 |
+
"pooler_num_attention_heads": 12,
|
23 |
+
"pooler_num_fc_layers": 3,
|
24 |
+
"pooler_size_per_head": 128,
|
25 |
+
"pooler_type": "first_token_transform",
|
26 |
+
"type_vocab_size": 2,
|
27 |
+
"vocab_size": 21128
|
28 |
+
}
|
bert/chinese-roberta-wwm-ext-large/special_tokens_map.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"unk_token": "[UNK]", "sep_token": "[SEP]", "pad_token": "[PAD]", "cls_token": "[CLS]", "mask_token": "[MASK]"}
|
bert/chinese-roberta-wwm-ext-large/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
bert/chinese-roberta-wwm-ext-large/tokenizer_config.json
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"init_inputs": []}
|
bert/chinese-roberta-wwm-ext-large/vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
bert/deberta-v2-large-japanese-char-wwm/.gitattributes
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
bert/deberta-v2-large-japanese-char-wwm/README.md
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language: ja
|
3 |
+
license: cc-by-sa-4.0
|
4 |
+
library_name: transformers
|
5 |
+
tags:
|
6 |
+
- deberta
|
7 |
+
- deberta-v2
|
8 |
+
- fill-mask
|
9 |
+
- character
|
10 |
+
- wwm
|
11 |
+
datasets:
|
12 |
+
- wikipedia
|
13 |
+
- cc100
|
14 |
+
- oscar
|
15 |
+
metrics:
|
16 |
+
- accuracy
|
17 |
+
mask_token: "[MASK]"
|
18 |
+
widget:
|
19 |
+
- text: "京都大学で自然言語処理を[MASK][MASK]する。"
|
20 |
+
---
|
21 |
+
|
22 |
+
# Model Card for Japanese character-level DeBERTa V2 large
|
23 |
+
|
24 |
+
## Model description
|
25 |
+
|
26 |
+
This is a Japanese DeBERTa V2 large model pre-trained on Japanese Wikipedia, the Japanese portion of CC-100, and the Japanese portion of OSCAR.
|
27 |
+
This model is trained with character-level tokenization and whole word masking.
|
28 |
+
|
29 |
+
## How to use
|
30 |
+
|
31 |
+
You can use this model for masked language modeling as follows:
|
32 |
+
|
33 |
+
```python
|
34 |
+
from transformers import AutoTokenizer, AutoModelForMaskedLM
|
35 |
+
tokenizer = AutoTokenizer.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
|
36 |
+
model = AutoModelForMaskedLM.from_pretrained('ku-nlp/deberta-v2-large-japanese-char-wwm')
|
37 |
+
|
38 |
+
sentence = '京都大学で自然言語処理を[MASK][MASK]する。'
|
39 |
+
encoding = tokenizer(sentence, return_tensors='pt')
|
40 |
+
...
|
41 |
+
```
|
42 |
+
|
43 |
+
You can also fine-tune this model on downstream tasks.
|
44 |
+
|
45 |
+
## Tokenization
|
46 |
+
|
47 |
+
There is no need to tokenize texts in advance, and you can give raw texts to the tokenizer.
|
48 |
+
The texts are tokenized into character-level tokens by [sentencepiece](https://github.com/google/sentencepiece).
|
49 |
+
|
50 |
+
## Training data
|
51 |
+
|
52 |
+
We used the following corpora for pre-training:
|
53 |
+
|
54 |
+
- Japanese Wikipedia (as of 20221020, 3.2GB, 27M sentences, 1.3M documents)
|
55 |
+
- Japanese portion of CC-100 (85GB, 619M sentences, 66M documents)
|
56 |
+
- Japanese portion of OSCAR (54GB, 326M sentences, 25M documents)
|
57 |
+
|
58 |
+
Note that we filtered out documents annotated with "header", "footer", or "noisy" tags in OSCAR.
|
59 |
+
Also note that Japanese Wikipedia was duplicated 10 times to make the total size of the corpus comparable to that of CC-100 and OSCAR. As a result, the total size of the training data is 171GB.
|
60 |
+
|
61 |
+
## Training procedure
|
62 |
+
|
63 |
+
We first segmented texts in the corpora into words using [Juman++ 2.0.0-rc3](https://github.com/ku-nlp/jumanpp/releases/tag/v2.0.0-rc3) for whole word masking.
|
64 |
+
Then, we built a sentencepiece model with 22,012 tokens including all characters that appear in the training corpus.
|
65 |
+
|
66 |
+
We tokenized raw corpora into character-level subwords using the sentencepiece model and trained the Japanese DeBERTa model using [transformers](https://github.com/huggingface/transformers) library.
|
67 |
+
The training took 26 days using 16 NVIDIA A100-SXM4-40GB GPUs.
|
68 |
+
|
69 |
+
The following hyperparameters were used during pre-training:
|
70 |
+
|
71 |
+
- learning_rate: 1e-4
|
72 |
+
- per_device_train_batch_size: 26
|
73 |
+
- distributed_type: multi-GPU
|
74 |
+
- num_devices: 16
|
75 |
+
- gradient_accumulation_steps: 8
|
76 |
+
- total_train_batch_size: 3,328
|
77 |
+
- max_seq_length: 512
|
78 |
+
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-06
|
79 |
+
- lr_scheduler_type: linear schedule with warmup (lr = 0 at 300k steps)
|
80 |
+
- training_steps: 260,000
|
81 |
+
- warmup_steps: 10,000
|
82 |
+
|
83 |
+
The accuracy of the trained model on the masked language modeling task was 0.795.
|
84 |
+
The evaluation set consists of 5,000 randomly sampled documents from each of the training corpora.
|
85 |
+
|
86 |
+
## Acknowledgments
|
87 |
+
|
88 |
+
This work was supported by Joint Usage/Research Center for Interdisciplinary Large-scale Information Infrastructures (JHPCN) through General Collaboration Project no. jh221004, "Developing a Platform for Constructing and Sharing of Large-Scale Japanese Language Models".
|
89 |
+
For training models, we used the mdx: a platform for the data-driven future.
|
bert/deberta-v2-large-japanese-char-wwm/config.json
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"DebertaV2ForMaskedLM"
|
4 |
+
],
|
5 |
+
"attention_head_size": 64,
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"conv_act": "gelu",
|
8 |
+
"conv_kernel_size": 3,
|
9 |
+
"hidden_act": "gelu",
|
10 |
+
"hidden_dropout_prob": 0.1,
|
11 |
+
"hidden_size": 1024,
|
12 |
+
"initializer_range": 0.02,
|
13 |
+
"intermediate_size": 4096,
|
14 |
+
"layer_norm_eps": 1e-07,
|
15 |
+
"max_position_embeddings": 512,
|
16 |
+
"max_relative_positions": -1,
|
17 |
+
"model_type": "deberta-v2",
|
18 |
+
"norm_rel_ebd": "layer_norm",
|
19 |
+
"num_attention_heads": 16,
|
20 |
+
"num_hidden_layers": 24,
|
21 |
+
"pad_token_id": 0,
|
22 |
+
"pooler_dropout": 0,
|
23 |
+
"pooler_hidden_act": "gelu",
|
24 |
+
"pooler_hidden_size": 1024,
|
25 |
+
"pos_att_type": [
|
26 |
+
"p2c",
|
27 |
+
"c2p"
|
28 |
+
],
|
29 |
+
"position_biased_input": false,
|
30 |
+
"position_buckets": 256,
|
31 |
+
"relative_attention": true,
|
32 |
+
"share_att_key": true,
|
33 |
+
"torch_dtype": "float16",
|
34 |
+
"transformers_version": "4.25.1",
|
35 |
+
"type_vocab_size": 0,
|
36 |
+
"vocab_size": 22012
|
37 |
+
}
|
bert/deberta-v2-large-japanese-char-wwm/special_tokens_map.json
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cls_token": "[CLS]",
|
3 |
+
"mask_token": "[MASK]",
|
4 |
+
"pad_token": "[PAD]",
|
5 |
+
"sep_token": "[SEP]",
|
6 |
+
"unk_token": "[UNK]"
|
7 |
+
}
|
bert/deberta-v2-large-japanese-char-wwm/tokenizer_config.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cls_token": "[CLS]",
|
3 |
+
"do_lower_case": false,
|
4 |
+
"do_subword_tokenize": true,
|
5 |
+
"do_word_tokenize": true,
|
6 |
+
"jumanpp_kwargs": null,
|
7 |
+
"mask_token": "[MASK]",
|
8 |
+
"mecab_kwargs": null,
|
9 |
+
"model_max_length": 1000000000000000019884624838656,
|
10 |
+
"never_split": null,
|
11 |
+
"pad_token": "[PAD]",
|
12 |
+
"sep_token": "[SEP]",
|
13 |
+
"special_tokens_map_file": null,
|
14 |
+
"subword_tokenizer_type": "character",
|
15 |
+
"sudachi_kwargs": null,
|
16 |
+
"tokenizer_class": "BertJapaneseTokenizer",
|
17 |
+
"unk_token": "[UNK]",
|
18 |
+
"word_tokenizer_type": "basic"
|
19 |
+
}
|
bert/deberta-v2-large-japanese-char-wwm/vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
bert/deberta-v3-large/.gitattributes
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
4 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
11 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
13 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
14 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
15 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
16 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
17 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
18 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
19 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
20 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
21 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
22 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
23 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
24 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
25 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
26 |
+
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
27 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
bert/deberta-v3-large/README.md
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language: en
|
3 |
+
tags:
|
4 |
+
- deberta
|
5 |
+
- deberta-v3
|
6 |
+
- fill-mask
|
7 |
+
thumbnail: https://huggingface.co/front/thumbnails/microsoft.png
|
8 |
+
license: mit
|
9 |
+
---
|
10 |
+
|
11 |
+
## DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing
|
12 |
+
|
13 |
+
[DeBERTa](https://arxiv.org/abs/2006.03654) improves the BERT and RoBERTa models using disentangled attention and enhanced mask decoder. With those two improvements, DeBERTa out perform RoBERTa on a majority of NLU tasks with 80GB training data.
|
14 |
+
|
15 |
+
In [DeBERTa V3](https://arxiv.org/abs/2111.09543), we further improved the efficiency of DeBERTa using ELECTRA-Style pre-training with Gradient Disentangled Embedding Sharing. Compared to DeBERTa, our V3 version significantly improves the model performance on downstream tasks. You can find more technique details about the new model from our [paper](https://arxiv.org/abs/2111.09543).
|
16 |
+
|
17 |
+
Please check the [official repository](https://github.com/microsoft/DeBERTa) for more implementation details and updates.
|
18 |
+
|
19 |
+
The DeBERTa V3 large model comes with 24 layers and a hidden size of 1024. It has 304M backbone parameters with a vocabulary containing 128K tokens which introduces 131M parameters in the Embedding layer. This model was trained using the 160GB data as DeBERTa V2.
|
20 |
+
|
21 |
+
|
22 |
+
#### Fine-tuning on NLU tasks
|
23 |
+
|
24 |
+
We present the dev results on SQuAD 2.0 and MNLI tasks.
|
25 |
+
|
26 |
+
| Model |Vocabulary(K)|Backbone #Params(M)| SQuAD 2.0(F1/EM) | MNLI-m/mm(ACC)|
|
27 |
+
|-------------------|----------|-------------------|-----------|----------|
|
28 |
+
| RoBERTa-large |50 |304 | 89.4/86.5 | 90.2 |
|
29 |
+
| XLNet-large |32 |- | 90.6/87.9 | 90.8 |
|
30 |
+
| DeBERTa-large |50 |- | 90.7/88.0 | 91.3 |
|
31 |
+
| **DeBERTa-v3-large**|128|304 | **91.5/89.0**| **91.8/91.9**|
|
32 |
+
|
33 |
+
|
34 |
+
#### Fine-tuning with HF transformers
|
35 |
+
|
36 |
+
```bash
|
37 |
+
#!/bin/bash
|
38 |
+
|
39 |
+
cd transformers/examples/pytorch/text-classification/
|
40 |
+
|
41 |
+
pip install datasets
|
42 |
+
export TASK_NAME=mnli
|
43 |
+
|
44 |
+
output_dir="ds_results"
|
45 |
+
|
46 |
+
num_gpus=8
|
47 |
+
|
48 |
+
batch_size=8
|
49 |
+
|
50 |
+
python -m torch.distributed.launch --nproc_per_node=${num_gpus} \
|
51 |
+
run_glue.py \
|
52 |
+
--model_name_or_path microsoft/deberta-v3-large \
|
53 |
+
--task_name $TASK_NAME \
|
54 |
+
--do_train \
|
55 |
+
--do_eval \
|
56 |
+
--evaluation_strategy steps \
|
57 |
+
--max_seq_length 256 \
|
58 |
+
--warmup_steps 50 \
|
59 |
+
--per_device_train_batch_size ${batch_size} \
|
60 |
+
--learning_rate 6e-6 \
|
61 |
+
--num_train_epochs 2 \
|
62 |
+
--output_dir $output_dir \
|
63 |
+
--overwrite_output_dir \
|
64 |
+
--logging_steps 1000 \
|
65 |
+
--logging_dir $output_dir
|
66 |
+
|
67 |
+
```
|
68 |
+
|
69 |
+
### Citation
|
70 |
+
|
71 |
+
If you find DeBERTa useful for your work, please cite the following papers:
|
72 |
+
|
73 |
+
``` latex
|
74 |
+
@misc{he2021debertav3,
|
75 |
+
title={DeBERTaV3: Improving DeBERTa using ELECTRA-Style Pre-Training with Gradient-Disentangled Embedding Sharing},
|
76 |
+
author={Pengcheng He and Jianfeng Gao and Weizhu Chen},
|
77 |
+
year={2021},
|
78 |
+
eprint={2111.09543},
|
79 |
+
archivePrefix={arXiv},
|
80 |
+
primaryClass={cs.CL}
|
81 |
+
}
|
82 |
+
```
|
83 |
+
|
84 |
+
``` latex
|
85 |
+
@inproceedings{
|
86 |
+
he2021deberta,
|
87 |
+
title={DEBERTA: DECODING-ENHANCED BERT WITH DISENTANGLED ATTENTION},
|
88 |
+
author={Pengcheng He and Xiaodong Liu and Jianfeng Gao and Weizhu Chen},
|
89 |
+
booktitle={International Conference on Learning Representations},
|
90 |
+
year={2021},
|
91 |
+
url={https://openreview.net/forum?id=XPZIaotutsD}
|
92 |
+
}
|
93 |
+
```
|
bert/deberta-v3-large/config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_type": "deberta-v2",
|
3 |
+
"attention_probs_dropout_prob": 0.1,
|
4 |
+
"hidden_act": "gelu",
|
5 |
+
"hidden_dropout_prob": 0.1,
|
6 |
+
"hidden_size": 1024,
|
7 |
+
"initializer_range": 0.02,
|
8 |
+
"intermediate_size": 4096,
|
9 |
+
"max_position_embeddings": 512,
|
10 |
+
"relative_attention": true,
|
11 |
+
"position_buckets": 256,
|
12 |
+
"norm_rel_ebd": "layer_norm",
|
13 |
+
"share_att_key": true,
|
14 |
+
"pos_att_type": "p2c|c2p",
|
15 |
+
"layer_norm_eps": 1e-7,
|
16 |
+
"max_relative_positions": -1,
|
17 |
+
"position_biased_input": false,
|
18 |
+
"num_attention_heads": 16,
|
19 |
+
"num_hidden_layers": 24,
|
20 |
+
"type_vocab_size": 0,
|
21 |
+
"vocab_size": 128100
|
22 |
+
}
|
bert/deberta-v3-large/generator_config.json
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_type": "deberta-v2",
|
3 |
+
"attention_probs_dropout_prob": 0.1,
|
4 |
+
"hidden_act": "gelu",
|
5 |
+
"hidden_dropout_prob": 0.1,
|
6 |
+
"hidden_size": 1024,
|
7 |
+
"initializer_range": 0.02,
|
8 |
+
"intermediate_size": 4096,
|
9 |
+
"max_position_embeddings": 512,
|
10 |
+
"relative_attention": true,
|
11 |
+
"position_buckets": 256,
|
12 |
+
"norm_rel_ebd": "layer_norm",
|
13 |
+
"share_att_key": true,
|
14 |
+
"pos_att_type": "p2c|c2p",
|
15 |
+
"layer_norm_eps": 1e-7,
|
16 |
+
"max_relative_positions": -1,
|
17 |
+
"position_biased_input": false,
|
18 |
+
"num_attention_heads": 16,
|
19 |
+
"num_hidden_layers": 12,
|
20 |
+
"type_vocab_size": 0,
|
21 |
+
"vocab_size": 128100
|
22 |
+
}
|
bert/deberta-v3-large/tokenizer_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"do_lower_case": false,
|
3 |
+
"vocab_type": "spm"
|
4 |
+
}
|
bert_gen.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from concurrent.futures import ThreadPoolExecutor
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.multiprocessing as mp
|
6 |
+
from tqdm import tqdm
|
7 |
+
|
8 |
+
import commons
|
9 |
+
import utils
|
10 |
+
from common.log import logger
|
11 |
+
from common.stdout_wrapper import SAFE_STDOUT
|
12 |
+
from config import config
|
13 |
+
from text import cleaned_text_to_sequence, get_bert
|
14 |
+
|
15 |
+
|
16 |
+
def process_line(x):
|
17 |
+
line, add_blank = x
|
18 |
+
device = config.bert_gen_config.device
|
19 |
+
if config.bert_gen_config.use_multi_device:
|
20 |
+
rank = mp.current_process()._identity
|
21 |
+
rank = rank[0] if len(rank) > 0 else 0
|
22 |
+
if torch.cuda.is_available():
|
23 |
+
gpu_id = rank % torch.cuda.device_count()
|
24 |
+
device = torch.device(f"cuda:{gpu_id}")
|
25 |
+
else:
|
26 |
+
device = torch.device("cpu")
|
27 |
+
wav_path, _, language_str, text, phones, tone, word2ph = line.strip().split("|")
|
28 |
+
phone = phones.split(" ")
|
29 |
+
tone = [int(i) for i in tone.split(" ")]
|
30 |
+
word2ph = [int(i) for i in word2ph.split(" ")]
|
31 |
+
word2ph = [i for i in word2ph]
|
32 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
33 |
+
|
34 |
+
if add_blank:
|
35 |
+
phone = commons.intersperse(phone, 0)
|
36 |
+
tone = commons.intersperse(tone, 0)
|
37 |
+
language = commons.intersperse(language, 0)
|
38 |
+
for i in range(len(word2ph)):
|
39 |
+
word2ph[i] = word2ph[i] * 2
|
40 |
+
word2ph[0] += 1
|
41 |
+
|
42 |
+
bert_path = wav_path.replace(".WAV", ".wav").replace(".wav", ".bert.pt")
|
43 |
+
|
44 |
+
try:
|
45 |
+
bert = torch.load(bert_path)
|
46 |
+
assert bert.shape[-1] == len(phone)
|
47 |
+
except Exception:
|
48 |
+
bert = get_bert(text, word2ph, language_str, device)
|
49 |
+
assert bert.shape[-1] == len(phone)
|
50 |
+
torch.save(bert, bert_path)
|
51 |
+
|
52 |
+
|
53 |
+
preprocess_text_config = config.preprocess_text_config
|
54 |
+
|
55 |
+
if __name__ == "__main__":
|
56 |
+
parser = argparse.ArgumentParser()
|
57 |
+
parser.add_argument(
|
58 |
+
"-c", "--config", type=str, default=config.bert_gen_config.config_path
|
59 |
+
)
|
60 |
+
parser.add_argument(
|
61 |
+
"--num_processes", type=int, default=config.bert_gen_config.num_processes
|
62 |
+
)
|
63 |
+
args, _ = parser.parse_known_args()
|
64 |
+
config_path = args.config
|
65 |
+
hps = utils.get_hparams_from_file(config_path)
|
66 |
+
lines = []
|
67 |
+
with open(hps.data.training_files, encoding="utf-8") as f:
|
68 |
+
lines.extend(f.readlines())
|
69 |
+
|
70 |
+
with open(hps.data.validation_files, encoding="utf-8") as f:
|
71 |
+
lines.extend(f.readlines())
|
72 |
+
add_blank = [hps.data.add_blank] * len(lines)
|
73 |
+
|
74 |
+
if len(lines) != 0:
|
75 |
+
num_processes = args.num_processes
|
76 |
+
with ThreadPoolExecutor(max_workers=num_processes) as executor:
|
77 |
+
_ = list(
|
78 |
+
tqdm(
|
79 |
+
executor.map(process_line, zip(lines, add_blank)),
|
80 |
+
total=len(lines),
|
81 |
+
file=SAFE_STDOUT,
|
82 |
+
)
|
83 |
+
)
|
84 |
+
|
85 |
+
logger.info(f"bert.pt is generated! total: {len(lines)} bert.pt files.")
|
clustering.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
colab.ipynb
ADDED
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {},
|
6 |
+
"source": [
|
7 |
+
"# Style-Bert-VITS2 (ver 2.3) のGoogle Colabでの学習\n",
|
8 |
+
"\n",
|
9 |
+
"Google Colab上でStyle-Bert-VITS2の学習を行うことができます。\n",
|
10 |
+
"\n",
|
11 |
+
"このnotebookでは、通常使用ではあなたのGoogle Driveにフォルダ`Style-Bert-VITS2`を作り、その内部での作業を行います。他のフォルダには触れません。\n",
|
12 |
+
"Google Driveを使わない場合は、初期設定のところで適切なパスを指定してください。\n",
|
13 |
+
"\n",
|
14 |
+
"## 流れ\n",
|
15 |
+
"\n",
|
16 |
+
"### 学習を最初からやりたいとき\n",
|
17 |
+
"上から順に実行していけばいいです。音声合成に必要なファイルはGoogle Driveの`Style-Bert-VITS2/model_assets/`に保存されます。また、途中経過も`Style-Bert-VITS2/Data/`に保存されるので、学習を中断したり、途中から再開することもできます。\n",
|
18 |
+
"\n",
|
19 |
+
"### 学習を途中から再開したいとき\n",
|
20 |
+
"0と1を行い、3の前処理は飛ばして、4から始めてください。スタイル分け5は、学習が終わったら必要なら行ってください。\n"
|
21 |
+
]
|
22 |
+
},
|
23 |
+
{
|
24 |
+
"cell_type": "markdown",
|
25 |
+
"metadata": {},
|
26 |
+
"source": [
|
27 |
+
"## 0. 環境構築\n",
|
28 |
+
"\n",
|
29 |
+
"Style-Bert-VITS2の環境をcolab上に構築します。グラボモードが有効になっていることを確認し、以下のセルを順に実行してください。"
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "code",
|
34 |
+
"execution_count": null,
|
35 |
+
"metadata": {},
|
36 |
+
"outputs": [],
|
37 |
+
"source": [
|
38 |
+
"#@title このセルを実行して環境構築してください。\n",
|
39 |
+
"#@markdown 最後に赤文字でエラーや警告が出ても何故かうまくいくみたいです。\n",
|
40 |
+
"\n",
|
41 |
+
"!git clone https://github.com/litagin02/Style-Bert-VITS2.git\n",
|
42 |
+
"%cd Style-Bert-VITS2/\n",
|
43 |
+
"!pip install -r requirements.txt\n",
|
44 |
+
"!apt install libcublas11\n",
|
45 |
+
"!python initialize.py --skip_jvnv"
|
46 |
+
]
|
47 |
+
},
|
48 |
+
{
|
49 |
+
"cell_type": "code",
|
50 |
+
"execution_count": null,
|
51 |
+
"metadata": {},
|
52 |
+
"outputs": [],
|
53 |
+
"source": [
|
54 |
+
"# Google driveを使う方はこちらを実行してください。\n",
|
55 |
+
"\n",
|
56 |
+
"from google.colab import drive\n",
|
57 |
+
"drive.mount(\"/content/drive\")"
|
58 |
+
]
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"cell_type": "markdown",
|
62 |
+
"metadata": {},
|
63 |
+
"source": [
|
64 |
+
"## 1. 初期設定\n",
|
65 |
+
"\n",
|
66 |
+
"学習とその結果を保存するディレクトリ名を指定します。\n",
|
67 |
+
"Google driveの場合はそのまま実行、カスタマイズしたい方は変更して実行してください。"
|
68 |
+
]
|
69 |
+
},
|
70 |
+
{
|
71 |
+
"cell_type": "code",
|
72 |
+
"execution_count": 1,
|
73 |
+
"metadata": {},
|
74 |
+
"outputs": [],
|
75 |
+
"source": [
|
76 |
+
"# 学習に必要なファイルや途中経過が保存されるディレクトリ\n",
|
77 |
+
"dataset_root = \"/content/drive/MyDrive/Style-Bert-VITS2/Data\"\n",
|
78 |
+
"\n",
|
79 |
+
"# 学習結果(音声合成に必要なファイルたち)が保存されるディレクトリ\n",
|
80 |
+
"assets_root = \"/content/drive/MyDrive/Style-Bert-VITS2/model_assets\"\n",
|
81 |
+
"\n",
|
82 |
+
"import yaml\n",
|
83 |
+
"\n",
|
84 |
+
"\n",
|
85 |
+
"with open(\"configs/paths.yml\", \"w\", encoding=\"utf-8\") as f:\n",
|
86 |
+
" yaml.dump({\"dataset_root\": dataset_root, \"assets_root\": assets_root}, f)"
|
87 |
+
]
|
88 |
+
},
|
89 |
+
{
|
90 |
+
"cell_type": "markdown",
|
91 |
+
"metadata": {},
|
92 |
+
"source": [
|
93 |
+
"## 2. 学習に使うデータ準備\n",
|
94 |
+
"\n",
|
95 |
+
"すでに音声ファイル(1ファイル2-12秒程度)とその書き起こしデータがある場合は2.2を、ない場合は2.1を実行してください。"
|
96 |
+
]
|
97 |
+
},
|
98 |
+
{
|
99 |
+
"cell_type": "markdown",
|
100 |
+
"metadata": {},
|
101 |
+
"source": [
|
102 |
+
"### 2.1 音声ファイルからのデータセットの作成(ある人はスキップ可)\n",
|
103 |
+
"\n",
|
104 |
+
"音声ファイル(1ファイル2-12秒程度)とその書き起こしのデータセットを持っていない方は、(日本語の)音声ファイルのみから以下の手順でデータセットを作成することができます。Google drive上の`Style-Bert-VITS2/inputs/`フォルダに音声ファイル(wavファイル形式、1ファイルでも複数ファイルでも可)を置いて、下を実行すると、データセットが作られ、自動的に正しい場所へ配置されます。"
|
105 |
+
]
|
106 |
+
},
|
107 |
+
{
|
108 |
+
"cell_type": "code",
|
109 |
+
"execution_count": null,
|
110 |
+
"metadata": {},
|
111 |
+
"outputs": [],
|
112 |
+
"source": [
|
113 |
+
"# 元となる音声ファイル(wav形式)を入れるディレクトリ\n",
|
114 |
+
"input_dir = \"/content/drive/MyDrive/Style-Bert-VITS2/inputs\"\n",
|
115 |
+
"# モデル名(話者名)を入力\n",
|
116 |
+
"model_name = \"your_model_name\"\n",
|
117 |
+
"\n",
|
118 |
+
"# こういうふうに書き起こして欲しいという例文(句読点の入れ方・笑い方や固有名詞等)\n",
|
119 |
+
"initial_prompt = \"こんにちは。元気、ですかー?ふふっ、私は……ちゃんと元気だよ!\"\n",
|
120 |
+
"\n",
|
121 |
+
"!python slice.py -i {input_dir} -o {dataset_root}/{model_name}/raw\n",
|
122 |
+
"!python transcribe.py -i {dataset_root}/{model_name}/raw -o {dataset_root}/{model_name}/esd.list --speaker_name {model_name} --compute_type float16 --initial_prompt {initial_prompt}"
|
123 |
+
]
|
124 |
+
},
|
125 |
+
{
|
126 |
+
"cell_type": "markdown",
|
127 |
+
"metadata": {},
|
128 |
+
"source": [
|
129 |
+
"成功したらそのまま3へ進んでください"
|
130 |
+
]
|
131 |
+
},
|
132 |
+
{
|
133 |
+
"cell_type": "markdown",
|
134 |
+
"metadata": {},
|
135 |
+
"source": [
|
136 |
+
"### 2.2 音声ファイルと書き起こしデータがすでにある場合\n",
|
137 |
+
"\n",
|
138 |
+
"指示に従って適切にデータセットを配置してください。\n",
|
139 |
+
"\n",
|
140 |
+
"次のセルを実行して、学習データをいれるフォルダ(1で設定した`dataset_root`)を作成します。"
|
141 |
+
]
|
142 |
+
},
|
143 |
+
{
|
144 |
+
"cell_type": "code",
|
145 |
+
"execution_count": 5,
|
146 |
+
"metadata": {
|
147 |
+
"id": "esCNJl704h52"
|
148 |
+
},
|
149 |
+
"outputs": [],
|
150 |
+
"source": [
|
151 |
+
"import os\n",
|
152 |
+
"\n",
|
153 |
+
"os.makedirs(dataset_root, exist_ok=True)"
|
154 |
+
]
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"cell_type": "markdown",
|
158 |
+
"metadata": {},
|
159 |
+
"source": [
|
160 |
+
"次に、学習に必要なデータを、Google driveに作成された`Style-Bert-VITS2/Data`フォルダに配置します。\n",
|
161 |
+
"\n",
|
162 |
+
"まず音声データ(wavファイルで1ファイルが2-12秒程度の、長すぎず短すぎない発話のものをいくつか)と、書き起こしテキストを用意してください。wavファイル名やモデルの名前は空白を含まない半角で、wavファイルの拡張子は小文字`.wav`である必要があります。\n",
|
163 |
+
"\n",
|
164 |
+
"書き起こしテキストは、次の形式で記述してください。\n",
|
165 |
+
"```\n",
|
166 |
+
"****.wav|{話者名}|{言語ID、ZHかJPかEN}|{書き起こしテキスト}\n",
|
167 |
+
"```\n",
|
168 |
+
"\n",
|
169 |
+
"例:\n",
|
170 |
+
"```\n",
|
171 |
+
"wav_number1.wav|hanako|JP|こんにちは、聞こえて、いますか?\n",
|
172 |
+
"wav_next.wav|taro|JP|はい、聞こえています……。\n",
|
173 |
+
"english_teacher.wav|Mary|EN|How are you? I'm fine, thank you, and you?\n",
|
174 |
+
"...\n",
|
175 |
+
"```\n",
|
176 |
+
"日本語話者の単一話者データセットで構いません。\n",
|
177 |
+
"\n",
|
178 |
+
"### データセットの配置\n",
|
179 |
+
"\n",
|
180 |
+
"次にモデルの名前を適当に決めてください(空白を含まない半角英数字がよいです)。\n",
|
181 |
+
"そして、書き起こしファイルを`esd.list`という名前で保存し、またwavファイルも`raw`というフォルダを作成し、あなたのGoogle Driveの中の(上で自動的に作られるはずの)`Data`フォルダのなかに、次のように配置します。\n",
|
182 |
+
"```\n",
|
183 |
+
"├── Data\n",
|
184 |
+
"│ ├── {モデルの名前}\n",
|
185 |
+
"│ │ ├── esd.list\n",
|
186 |
+
"│ │ ├── raw\n",
|
187 |
+
"│ │ │ ├── ****.wav\n",
|
188 |
+
"│ │ │ ├── ****.wav\n",
|
189 |
+
"│ │ │ ├── ...\n",
|
190 |
+
"```"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "markdown",
|
195 |
+
"metadata": {
|
196 |
+
"id": "5r85-W20ECcr"
|
197 |
+
},
|
198 |
+
"source": [
|
199 |
+
"## 3. 学習の前処理\n",
|
200 |
+
"\n",
|
201 |
+
"次に学習の前処理を行います。必要なパラメータをここで指定します。次のセルに設定等を入力して実行してください。「~~かどうか」は`True`もしくは`False`を指定してください。"
|
202 |
+
]
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"cell_type": "code",
|
206 |
+
"execution_count": 6,
|
207 |
+
"metadata": {
|
208 |
+
"id": "CXR7kjuF5GlE"
|
209 |
+
},
|
210 |
+
"outputs": [],
|
211 |
+
"source": [
|
212 |
+
"# 上でつけたフォルダの名前`Data/{model_name}/`\n",
|
213 |
+
"model_name = \"your_model_name\"\n",
|
214 |
+
"\n",
|
215 |
+
"# JP-Extra (日本語特化版)を使うかどうか。日本語の能力が向上する代わりに英語と中国語は使えなくなります。\n",
|
216 |
+
"use_jp_extra = True\n",
|
217 |
+
"\n",
|
218 |
+
"# 学習のバッチサイズ。VRAMのはみ出具合に応じて調整してください。\n",
|
219 |
+
"batch_size = 4\n",
|
220 |
+
"\n",
|
221 |
+
"# 学習のエポック数(データセットを合計何周するか)。\n",
|
222 |
+
"# 100ぐらいで十分かもしれませんが、もっと多くやると質が上がるのかもしれません。\n",
|
223 |
+
"epochs = 100\n",
|
224 |
+
"\n",
|
225 |
+
"# 保存頻度。何ステップごとにモデルを保存するか。分からなければデフォルトのままで。\n",
|
226 |
+
"save_every_steps = 1000\n",
|
227 |
+
"\n",
|
228 |
+
"# 音声ファイルの音量を正規化するかどうか\n",
|
229 |
+
"normalize = False\n",
|
230 |
+
"\n",
|
231 |
+
"# 音声ファイルの開始・終了にある無音区間を削除するかどうか\n",
|
232 |
+
"trim = False"
|
233 |
+
]
|
234 |
+
},
|
235 |
+
{
|
236 |
+
"cell_type": "markdown",
|
237 |
+
"metadata": {},
|
238 |
+
"source": [
|
239 |
+
"上のセルが実行されたら、次のセルを実行して学習の前処理を行います。"
|
240 |
+
]
|
241 |
+
},
|
242 |
+
{
|
243 |
+
"cell_type": "code",
|
244 |
+
"execution_count": null,
|
245 |
+
"metadata": {
|
246 |
+
"colab": {
|
247 |
+
"base_uri": "https://localhost:8080/"
|
248 |
+
},
|
249 |
+
"id": "xMVaOIPLabV5",
|
250 |
+
"outputId": "15fac868-9132-45d9-9f5f-365b6aeb67b0"
|
251 |
+
},
|
252 |
+
"outputs": [],
|
253 |
+
"source": [
|
254 |
+
"from webui_train import preprocess_all\n",
|
255 |
+
"\n",
|
256 |
+
"preprocess_all(\n",
|
257 |
+
" model_name=model_name,\n",
|
258 |
+
" batch_size=batch_size,\n",
|
259 |
+
" epochs=epochs,\n",
|
260 |
+
" save_every_steps=save_every_steps,\n",
|
261 |
+
" num_processes=2,\n",
|
262 |
+
" normalize=normalize,\n",
|
263 |
+
" trim=trim,\n",
|
264 |
+
" freeze_EN_bert=False,\n",
|
265 |
+
" freeze_JP_bert=False,\n",
|
266 |
+
" freeze_ZH_bert=False,\n",
|
267 |
+
" freeze_style=False,\n",
|
268 |
+
" freeze_decoder=False, # ここをTrueにするともしかしたら違う結果になるかもしれません。\n",
|
269 |
+
" use_jp_extra=use_jp_extra,\n",
|
270 |
+
" val_per_lang=0,\n",
|
271 |
+
" log_interval=200,\n",
|
272 |
+
")"
|
273 |
+
]
|
274 |
+
},
|
275 |
+
{
|
276 |
+
"cell_type": "markdown",
|
277 |
+
"metadata": {},
|
278 |
+
"source": [
|
279 |
+
"## 4. 学習\n",
|
280 |
+
"\n",
|
281 |
+
"前処理が正常に終わったら、学習を行います。次のセルを実行すると学習が始まります。\n",
|
282 |
+
"\n",
|
283 |
+
"学習の結果は、上で指定した`save_every_steps`の間隔で、Google Driveの中の`Style-Bert-VITS2/Data/{モデルの名前}/model_assets/`フォルダに保存されます。\n",
|
284 |
+
"\n",
|
285 |
+
"このフォルダをダウンロードし、ローカルのStyle-Bert-VITS2の`model_assets`フォルダに上書きすれば、学習結果を使うことができます。"
|
286 |
+
]
|
287 |
+
},
|
288 |
+
{
|
289 |
+
"cell_type": "code",
|
290 |
+
"execution_count": null,
|
291 |
+
"metadata": {
|
292 |
+
"colab": {
|
293 |
+
"base_uri": "https://localhost:8080/"
|
294 |
+
},
|
295 |
+
"id": "laieKrbEb6Ij",
|
296 |
+
"outputId": "72238c88-f294-4ed9-84f6-84c1c17999ca"
|
297 |
+
},
|
298 |
+
"outputs": [],
|
299 |
+
"source": [
|
300 |
+
"# 上でつけたモデル名を入力。学習を途中からする場合はきちんとモデルが保存されているフォルダ名を入力。\n",
|
301 |
+
"model_name = \"your_model_name\"\n",
|
302 |
+
"\n",
|
303 |
+
"\n",
|
304 |
+
"import yaml\n",
|
305 |
+
"from webui_train import get_path\n",
|
306 |
+
"\n",
|
307 |
+
"dataset_path, _, _, _, config_path = get_path(model_name)\n",
|
308 |
+
"\n",
|
309 |
+
"with open(\"default_config.yml\", \"r\", encoding=\"utf-8\") as f:\n",
|
310 |
+
" yml_data = yaml.safe_load(f)\n",
|
311 |
+
"yml_data[\"model_name\"] = model_name\n",
|
312 |
+
"with open(\"config.yml\", \"w\", encoding=\"utf-8\") as f:\n",
|
313 |
+
" yaml.dump(yml_data, f, allow_unicode=True)"
|
314 |
+
]
|
315 |
+
},
|
316 |
+
{
|
317 |
+
"cell_type": "code",
|
318 |
+
"execution_count": null,
|
319 |
+
"metadata": {},
|
320 |
+
"outputs": [],
|
321 |
+
"source": [
|
322 |
+
"# 日本語特化版を「使う」場合\n",
|
323 |
+
"!python train_ms_jp_extra.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
|
324 |
+
]
|
325 |
+
},
|
326 |
+
{
|
327 |
+
"cell_type": "code",
|
328 |
+
"execution_count": null,
|
329 |
+
"metadata": {},
|
330 |
+
"outputs": [],
|
331 |
+
"source": [
|
332 |
+
"# 日本語特化版を「使わない」場合\n",
|
333 |
+
"!python train_ms.py --config {config_path} --model {dataset_path} --assets_root {assets_root}"
|
334 |
+
]
|
335 |
+
},
|
336 |
+
{
|
337 |
+
"cell_type": "code",
|
338 |
+
"execution_count": null,
|
339 |
+
"metadata": {
|
340 |
+
"colab": {
|
341 |
+
"base_uri": "https://localhost:8080/"
|
342 |
+
},
|
343 |
+
"id": "c7g0hrdeP1Tl",
|
344 |
+
"outputId": "94f9a6f6-027f-4554-ce0c-60ac56251c22"
|
345 |
+
},
|
346 |
+
"outputs": [],
|
347 |
+
"source": [
|
348 |
+
"#@title 学習結果を試すならここから\n",
|
349 |
+
"!python app.py --share --dir {assets_root}"
|
350 |
+
]
|
351 |
+
},
|
352 |
+
{
|
353 |
+
"cell_type": "markdown",
|
354 |
+
"metadata": {},
|
355 |
+
"source": [
|
356 |
+
"## 5. スタイル分け"
|
357 |
+
]
|
358 |
+
},
|
359 |
+
{
|
360 |
+
"cell_type": "code",
|
361 |
+
"execution_count": null,
|
362 |
+
"metadata": {},
|
363 |
+
"outputs": [],
|
364 |
+
"source": [
|
365 |
+
"!python webui_style_vectors.py --share"
|
366 |
+
]
|
367 |
+
},
|
368 |
+
{
|
369 |
+
"cell_type": "markdown",
|
370 |
+
"metadata": {},
|
371 |
+
"source": [
|
372 |
+
"## 6. マージ"
|
373 |
+
]
|
374 |
+
},
|
375 |
+
{
|
376 |
+
"cell_type": "code",
|
377 |
+
"execution_count": null,
|
378 |
+
"metadata": {},
|
379 |
+
"outputs": [],
|
380 |
+
"source": [
|
381 |
+
"!python webui_merge.py --share"
|
382 |
+
]
|
383 |
+
}
|
384 |
+
],
|
385 |
+
"metadata": {
|
386 |
+
"accelerator": "GPU",
|
387 |
+
"colab": {
|
388 |
+
"gpuType": "T4",
|
389 |
+
"provenance": []
|
390 |
+
},
|
391 |
+
"kernelspec": {
|
392 |
+
"display_name": "Python 3",
|
393 |
+
"name": "python3"
|
394 |
+
},
|
395 |
+
"language_info": {
|
396 |
+
"codemirror_mode": {
|
397 |
+
"name": "ipython",
|
398 |
+
"version": 3
|
399 |
+
},
|
400 |
+
"file_extension": ".py",
|
401 |
+
"mimetype": "text/x-python",
|
402 |
+
"name": "python",
|
403 |
+
"nbconvert_exporter": "python",
|
404 |
+
"pygments_lexer": "ipython3",
|
405 |
+
"version": "3.10.11"
|
406 |
+
}
|
407 |
+
},
|
408 |
+
"nbformat": 4,
|
409 |
+
"nbformat_minor": 0
|
410 |
+
}
|
common/constants.py
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import enum
|
2 |
+
|
3 |
+
# Built-in theme: "default", "base", "monochrome", "soft", "glass"
|
4 |
+
# See https://huggingface.co/spaces/gradio/theme-gallery for more themes
|
5 |
+
GRADIO_THEME: str = "NoCrypt/miku"
|
6 |
+
|
7 |
+
LATEST_VERSION: str = "2.3"
|
8 |
+
|
9 |
+
USER_DICT_DIR = "dict_data"
|
10 |
+
|
11 |
+
DEFAULT_STYLE: str = "Neutral"
|
12 |
+
DEFAULT_STYLE_WEIGHT: float = 5.0
|
13 |
+
|
14 |
+
|
15 |
+
class Languages(str, enum.Enum):
|
16 |
+
JP = "JP"
|
17 |
+
EN = "EN"
|
18 |
+
ZH = "ZH"
|
19 |
+
|
20 |
+
|
21 |
+
DEFAULT_SDP_RATIO: float = 0.2
|
22 |
+
DEFAULT_NOISE: float = 0.6
|
23 |
+
DEFAULT_NOISEW: float = 0.8
|
24 |
+
DEFAULT_LENGTH: float = 1.0
|
25 |
+
DEFAULT_LINE_SPLIT: bool = True
|
26 |
+
DEFAULT_SPLIT_INTERVAL: float = 0.5
|
27 |
+
DEFAULT_ASSIST_TEXT_WEIGHT: float = 0.7
|
28 |
+
DEFAULT_ASSIST_TEXT_WEIGHT: float = 1.0
|
common/log.py
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
logger封装
|
3 |
+
"""
|
4 |
+
from loguru import logger
|
5 |
+
|
6 |
+
from .stdout_wrapper import SAFE_STDOUT
|
7 |
+
|
8 |
+
# 移除所有默认的处理器
|
9 |
+
logger.remove()
|
10 |
+
|
11 |
+
# 自定义格式并添加到标准输出
|
12 |
+
log_format = (
|
13 |
+
"<g>{time:MM-DD HH:mm:ss}</g> |<lvl>{level:^8}</lvl>| {file}:{line} | {message}"
|
14 |
+
)
|
15 |
+
|
16 |
+
logger.add(SAFE_STDOUT, format=log_format, backtrace=True, diagnose=True)
|
common/stdout_wrapper.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
`sys.stdout` wrapper for both Google Colab and local environment.
|
3 |
+
"""
|
4 |
+
|
5 |
+
import sys
|
6 |
+
import tempfile
|
7 |
+
|
8 |
+
|
9 |
+
class StdoutWrapper:
|
10 |
+
def __init__(self):
|
11 |
+
self.temp_file = tempfile.NamedTemporaryFile(mode="w+", delete=False)
|
12 |
+
self.original_stdout = sys.stdout
|
13 |
+
|
14 |
+
def write(self, message: str):
|
15 |
+
self.temp_file.write(message)
|
16 |
+
self.temp_file.flush()
|
17 |
+
print(message, end="", file=self.original_stdout)
|
18 |
+
|
19 |
+
def flush(self):
|
20 |
+
self.temp_file.flush()
|
21 |
+
|
22 |
+
def read(self):
|
23 |
+
self.temp_file.seek(0)
|
24 |
+
return self.temp_file.read()
|
25 |
+
|
26 |
+
def close(self):
|
27 |
+
self.temp_file.close()
|
28 |
+
|
29 |
+
def fileno(self):
|
30 |
+
return self.temp_file.fileno()
|
31 |
+
|
32 |
+
|
33 |
+
try:
|
34 |
+
import google.colab
|
35 |
+
|
36 |
+
SAFE_STDOUT = StdoutWrapper()
|
37 |
+
except ImportError:
|
38 |
+
SAFE_STDOUT = sys.stdout
|
common/subprocess_utils.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import subprocess
|
2 |
+
import sys
|
3 |
+
|
4 |
+
from .log import logger
|
5 |
+
from .stdout_wrapper import SAFE_STDOUT
|
6 |
+
|
7 |
+
python = sys.executable
|
8 |
+
|
9 |
+
|
10 |
+
def run_script_with_log(cmd: list[str], ignore_warning=False) -> tuple[bool, str]:
|
11 |
+
logger.info(f"Running: {' '.join(cmd)}")
|
12 |
+
result = subprocess.run(
|
13 |
+
[python] + cmd,
|
14 |
+
stdout=SAFE_STDOUT, # type: ignore
|
15 |
+
stderr=subprocess.PIPE,
|
16 |
+
text=True,
|
17 |
+
)
|
18 |
+
if result.returncode != 0:
|
19 |
+
logger.error(f"Error: {' '.join(cmd)}\n{result.stderr}")
|
20 |
+
return False, result.stderr
|
21 |
+
elif result.stderr and not ignore_warning:
|
22 |
+
logger.warning(f"Warning: {' '.join(cmd)}\n{result.stderr}")
|
23 |
+
return True, result.stderr
|
24 |
+
logger.success(f"Success: {' '.join(cmd)}")
|
25 |
+
return True, ""
|
26 |
+
|
27 |
+
|
28 |
+
def second_elem_of(original_function):
|
29 |
+
def inner_function(*args, **kwargs):
|
30 |
+
return original_function(*args, **kwargs)[1]
|
31 |
+
|
32 |
+
return inner_function
|
common/tts_model.py
ADDED
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import warnings
|
3 |
+
from pathlib import Path
|
4 |
+
from typing import Optional, Union
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
import torch
|
10 |
+
from gradio.processing_utils import convert_to_16_bit_wav
|
11 |
+
|
12 |
+
import utils
|
13 |
+
from infer import get_net_g, infer
|
14 |
+
from models import SynthesizerTrn
|
15 |
+
from models_jp_extra import SynthesizerTrn as SynthesizerTrnJPExtra
|
16 |
+
|
17 |
+
from .constants import (
|
18 |
+
DEFAULT_ASSIST_TEXT_WEIGHT,
|
19 |
+
DEFAULT_LENGTH,
|
20 |
+
DEFAULT_LINE_SPLIT,
|
21 |
+
DEFAULT_NOISE,
|
22 |
+
DEFAULT_NOISEW,
|
23 |
+
DEFAULT_SDP_RATIO,
|
24 |
+
DEFAULT_SPLIT_INTERVAL,
|
25 |
+
DEFAULT_STYLE,
|
26 |
+
DEFAULT_STYLE_WEIGHT,
|
27 |
+
)
|
28 |
+
from .log import logger
|
29 |
+
|
30 |
+
|
31 |
+
def adjust_voice(fs, wave, pitch_scale, intonation_scale):
|
32 |
+
if pitch_scale == 1.0 and intonation_scale == 1.0:
|
33 |
+
# 初期値の場合は、音質劣化を避けるためにそのまま返す
|
34 |
+
return fs, wave
|
35 |
+
|
36 |
+
try:
|
37 |
+
import pyworld
|
38 |
+
except ImportError:
|
39 |
+
raise ImportError(
|
40 |
+
"pyworld is not installed. Please install it by `pip install pyworld`"
|
41 |
+
)
|
42 |
+
|
43 |
+
# pyworldでf0を加工して合成
|
44 |
+
# pyworldよりもよいのがあるかもしれないが……
|
45 |
+
|
46 |
+
wave = wave.astype(np.double)
|
47 |
+
f0, t = pyworld.harvest(wave, fs)
|
48 |
+
# 質が高そうだしとりあえずharvestにしておく
|
49 |
+
|
50 |
+
sp = pyworld.cheaptrick(wave, f0, t, fs)
|
51 |
+
ap = pyworld.d4c(wave, f0, t, fs)
|
52 |
+
|
53 |
+
non_zero_f0 = [f for f in f0 if f != 0]
|
54 |
+
f0_mean = sum(non_zero_f0) / len(non_zero_f0)
|
55 |
+
|
56 |
+
for i, f in enumerate(f0):
|
57 |
+
if f == 0:
|
58 |
+
continue
|
59 |
+
f0[i] = pitch_scale * f0_mean + intonation_scale * (f - f0_mean)
|
60 |
+
|
61 |
+
wave = pyworld.synthesize(f0, sp, ap, fs)
|
62 |
+
return fs, wave
|
63 |
+
|
64 |
+
|
65 |
+
class Model:
|
66 |
+
def __init__(
|
67 |
+
self, model_path: Path, config_path: Path, style_vec_path: Path, device: str
|
68 |
+
):
|
69 |
+
self.model_path: Path = model_path
|
70 |
+
self.config_path: Path = config_path
|
71 |
+
self.style_vec_path: Path = style_vec_path
|
72 |
+
self.device: str = device
|
73 |
+
self.hps: utils.HParams = utils.get_hparams_from_file(self.config_path)
|
74 |
+
self.spk2id: dict[str, int] = self.hps.data.spk2id
|
75 |
+
self.id2spk: dict[int, str] = {v: k for k, v in self.spk2id.items()}
|
76 |
+
|
77 |
+
self.num_styles: int = self.hps.data.num_styles
|
78 |
+
if hasattr(self.hps.data, "style2id"):
|
79 |
+
self.style2id: dict[str, int] = self.hps.data.style2id
|
80 |
+
else:
|
81 |
+
self.style2id: dict[str, int] = {str(i): i for i in range(self.num_styles)}
|
82 |
+
if len(self.style2id) != self.num_styles:
|
83 |
+
raise ValueError(
|
84 |
+
f"Number of styles ({self.num_styles}) does not match the number of style2id ({len(self.style2id)})"
|
85 |
+
)
|
86 |
+
|
87 |
+
self.style_vectors: np.ndarray = np.load(self.style_vec_path)
|
88 |
+
if self.style_vectors.shape[0] != self.num_styles:
|
89 |
+
raise ValueError(
|
90 |
+
f"The number of styles ({self.num_styles}) does not match the number of style vectors ({self.style_vectors.shape[0]})"
|
91 |
+
)
|
92 |
+
|
93 |
+
self.net_g: Union[SynthesizerTrn, SynthesizerTrnJPExtra, None] = None
|
94 |
+
|
95 |
+
def load_net_g(self):
|
96 |
+
self.net_g = get_net_g(
|
97 |
+
model_path=str(self.model_path),
|
98 |
+
version=self.hps.version,
|
99 |
+
device=self.device,
|
100 |
+
hps=self.hps,
|
101 |
+
)
|
102 |
+
|
103 |
+
def get_style_vector(self, style_id: int, weight: float = 1.0) -> np.ndarray:
|
104 |
+
mean = self.style_vectors[0]
|
105 |
+
style_vec = self.style_vectors[style_id]
|
106 |
+
style_vec = mean + (style_vec - mean) * weight
|
107 |
+
return style_vec
|
108 |
+
|
109 |
+
def get_style_vector_from_audio(
|
110 |
+
self, audio_path: str, weight: float = 1.0
|
111 |
+
) -> np.ndarray:
|
112 |
+
from style_gen import get_style_vector
|
113 |
+
|
114 |
+
xvec = get_style_vector(audio_path)
|
115 |
+
mean = self.style_vectors[0]
|
116 |
+
xvec = mean + (xvec - mean) * weight
|
117 |
+
return xvec
|
118 |
+
|
119 |
+
def infer(
|
120 |
+
self,
|
121 |
+
text: str,
|
122 |
+
language: str = "JP",
|
123 |
+
sid: int = 0,
|
124 |
+
reference_audio_path: Optional[str] = None,
|
125 |
+
sdp_ratio: float = DEFAULT_SDP_RATIO,
|
126 |
+
noise: float = DEFAULT_NOISE,
|
127 |
+
noisew: float = DEFAULT_NOISEW,
|
128 |
+
length: float = DEFAULT_LENGTH,
|
129 |
+
line_split: bool = DEFAULT_LINE_SPLIT,
|
130 |
+
split_interval: float = DEFAULT_SPLIT_INTERVAL,
|
131 |
+
assist_text: Optional[str] = None,
|
132 |
+
assist_text_weight: float = DEFAULT_ASSIST_TEXT_WEIGHT,
|
133 |
+
use_assist_text: bool = False,
|
134 |
+
style: str = DEFAULT_STYLE,
|
135 |
+
style_weight: float = DEFAULT_STYLE_WEIGHT,
|
136 |
+
given_tone: Optional[list[int]] = None,
|
137 |
+
pitch_scale: float = 1.0,
|
138 |
+
intonation_scale: float = 1.0,
|
139 |
+
ignore_unknown: bool = False,
|
140 |
+
) -> tuple[int, np.ndarray]:
|
141 |
+
logger.info(f"Start generating audio data from text:\n{text}")
|
142 |
+
if language != "JP" and self.hps.version.endswith("JP-Extra"):
|
143 |
+
raise ValueError(
|
144 |
+
"The model is trained with JP-Extra, but the language is not JP"
|
145 |
+
)
|
146 |
+
if reference_audio_path == "":
|
147 |
+
reference_audio_path = None
|
148 |
+
if assist_text == "" or not use_assist_text:
|
149 |
+
assist_text = None
|
150 |
+
|
151 |
+
if self.net_g is None:
|
152 |
+
self.load_net_g()
|
153 |
+
if reference_audio_path is None:
|
154 |
+
style_id = self.style2id[style]
|
155 |
+
style_vector = self.get_style_vector(style_id, style_weight)
|
156 |
+
else:
|
157 |
+
style_vector = self.get_style_vector_from_audio(
|
158 |
+
reference_audio_path, style_weight
|
159 |
+
)
|
160 |
+
if not line_split:
|
161 |
+
with torch.no_grad():
|
162 |
+
audio = infer(
|
163 |
+
text=text,
|
164 |
+
sdp_ratio=sdp_ratio,
|
165 |
+
noise_scale=noise,
|
166 |
+
noise_scale_w=noisew,
|
167 |
+
length_scale=length,
|
168 |
+
sid=sid,
|
169 |
+
language=language,
|
170 |
+
hps=self.hps,
|
171 |
+
net_g=self.net_g,
|
172 |
+
device=self.device,
|
173 |
+
assist_text=assist_text,
|
174 |
+
assist_text_weight=assist_text_weight,
|
175 |
+
style_vec=style_vector,
|
176 |
+
given_tone=given_tone,
|
177 |
+
ignore_unknown=ignore_unknown,
|
178 |
+
)
|
179 |
+
else:
|
180 |
+
texts = text.split("\n")
|
181 |
+
texts = [t for t in texts if t != ""]
|
182 |
+
audios = []
|
183 |
+
with torch.no_grad():
|
184 |
+
for i, t in enumerate(texts):
|
185 |
+
audios.append(
|
186 |
+
infer(
|
187 |
+
text=t,
|
188 |
+
sdp_ratio=sdp_ratio,
|
189 |
+
noise_scale=noise,
|
190 |
+
noise_scale_w=noisew,
|
191 |
+
length_scale=length,
|
192 |
+
sid=sid,
|
193 |
+
language=language,
|
194 |
+
hps=self.hps,
|
195 |
+
net_g=self.net_g,
|
196 |
+
device=self.device,
|
197 |
+
assist_text=assist_text,
|
198 |
+
assist_text_weight=assist_text_weight,
|
199 |
+
style_vec=style_vector,
|
200 |
+
ignore_unknown=ignore_unknown,
|
201 |
+
)
|
202 |
+
)
|
203 |
+
if i != len(texts) - 1:
|
204 |
+
audios.append(np.zeros(int(44100 * split_interval)))
|
205 |
+
audio = np.concatenate(audios)
|
206 |
+
logger.info("Audio data generated successfully")
|
207 |
+
if not (pitch_scale == 1.0 and intonation_scale == 1.0):
|
208 |
+
_, audio = adjust_voice(
|
209 |
+
fs=self.hps.data.sampling_rate,
|
210 |
+
wave=audio,
|
211 |
+
pitch_scale=pitch_scale,
|
212 |
+
intonation_scale=intonation_scale,
|
213 |
+
)
|
214 |
+
with warnings.catch_warnings():
|
215 |
+
warnings.simplefilter("ignore")
|
216 |
+
audio = convert_to_16_bit_wav(audio)
|
217 |
+
return (self.hps.data.sampling_rate, audio)
|
218 |
+
|
219 |
+
|
220 |
+
class ModelHolder:
|
221 |
+
def __init__(self, root_dir: Path, device: str):
|
222 |
+
self.root_dir: Path = root_dir
|
223 |
+
self.device: str = device
|
224 |
+
self.model_files_dict: dict[str, list[Path]] = {}
|
225 |
+
self.current_model: Optional[Model] = None
|
226 |
+
self.model_names: list[str] = []
|
227 |
+
self.models: list[Model] = []
|
228 |
+
self.refresh()
|
229 |
+
|
230 |
+
def refresh(self):
|
231 |
+
self.model_files_dict = {}
|
232 |
+
self.model_names = []
|
233 |
+
self.current_model = None
|
234 |
+
|
235 |
+
model_dirs = [d for d in self.root_dir.iterdir() if d.is_dir()]
|
236 |
+
for model_dir in model_dirs:
|
237 |
+
model_files = [
|
238 |
+
f
|
239 |
+
for f in model_dir.iterdir()
|
240 |
+
if f.suffix in [".pth", ".pt", ".safetensors"]
|
241 |
+
]
|
242 |
+
if len(model_files) == 0:
|
243 |
+
logger.warning(f"No model files found in {model_dir}, so skip it")
|
244 |
+
continue
|
245 |
+
config_path = model_dir / "config.json"
|
246 |
+
if not config_path.exists():
|
247 |
+
logger.warning(
|
248 |
+
f"Config file {config_path} not found, so skip {model_dir}"
|
249 |
+
)
|
250 |
+
continue
|
251 |
+
self.model_files_dict[model_dir.name] = model_files
|
252 |
+
self.model_names.append(model_dir.name)
|
253 |
+
|
254 |
+
def models_info(self):
|
255 |
+
if hasattr(self, "_models_info"):
|
256 |
+
return self._models_info
|
257 |
+
result = []
|
258 |
+
for name, files in self.model_files_dict.items():
|
259 |
+
# Get styles
|
260 |
+
config_path = self.root_dir / name / "config.json"
|
261 |
+
hps = utils.get_hparams_from_file(config_path)
|
262 |
+
style2id: dict[str, int] = hps.data.style2id
|
263 |
+
styles = list(style2id.keys())
|
264 |
+
result.append(
|
265 |
+
{
|
266 |
+
"name": name,
|
267 |
+
"files": [str(f) for f in files],
|
268 |
+
"styles": styles,
|
269 |
+
}
|
270 |
+
)
|
271 |
+
self._models_info = result
|
272 |
+
return result
|
273 |
+
|
274 |
+
def load_model(self, model_name: str, model_path_str: str):
|
275 |
+
model_path = Path(model_path_str)
|
276 |
+
if model_name not in self.model_files_dict:
|
277 |
+
raise ValueError(f"Model `{model_name}` is not found")
|
278 |
+
if model_path not in self.model_files_dict[model_name]:
|
279 |
+
raise ValueError(f"Model file `{model_path}` is not found")
|
280 |
+
if self.current_model is None or self.current_model.model_path != model_path:
|
281 |
+
self.current_model = Model(
|
282 |
+
model_path=model_path,
|
283 |
+
config_path=self.root_dir / model_name / "config.json",
|
284 |
+
style_vec_path=self.root_dir / model_name / "style_vectors.npy",
|
285 |
+
device=self.device,
|
286 |
+
)
|
287 |
+
return self.current_model
|
288 |
+
|
289 |
+
def load_model_gr(
|
290 |
+
self, model_name: str, model_path_str: str
|
291 |
+
) -> tuple[gr.Dropdown, gr.Button, gr.Dropdown]:
|
292 |
+
model_path = Path(model_path_str)
|
293 |
+
if model_name not in self.model_files_dict:
|
294 |
+
raise ValueError(f"Model `{model_name}` is not found")
|
295 |
+
if model_path not in self.model_files_dict[model_name]:
|
296 |
+
raise ValueError(f"Model file `{model_path}` is not found")
|
297 |
+
if (
|
298 |
+
self.current_model is not None
|
299 |
+
and self.current_model.model_path == model_path
|
300 |
+
):
|
301 |
+
# Already loaded
|
302 |
+
speakers = list(self.current_model.spk2id.keys())
|
303 |
+
styles = list(self.current_model.style2id.keys())
|
304 |
+
return (
|
305 |
+
gr.Dropdown(choices=styles, value=styles[0]),
|
306 |
+
gr.Button(interactive=True, value="音声合成"),
|
307 |
+
gr.Dropdown(choices=speakers, value=speakers[0]),
|
308 |
+
)
|
309 |
+
self.current_model = Model(
|
310 |
+
model_path=model_path,
|
311 |
+
config_path=self.root_dir / model_name / "config.json",
|
312 |
+
style_vec_path=self.root_dir / model_name / "style_vectors.npy",
|
313 |
+
device=self.device,
|
314 |
+
)
|
315 |
+
speakers = list(self.current_model.spk2id.keys())
|
316 |
+
styles = list(self.current_model.style2id.keys())
|
317 |
+
return (
|
318 |
+
gr.Dropdown(choices=styles, value=styles[0]),
|
319 |
+
gr.Button(interactive=True, value="音声合成"),
|
320 |
+
gr.Dropdown(choices=speakers, value=speakers[0]),
|
321 |
+
)
|
322 |
+
|
323 |
+
def update_model_files_gr(self, model_name: str) -> gr.Dropdown:
|
324 |
+
model_files = self.model_files_dict[model_name]
|
325 |
+
return gr.Dropdown(choices=model_files, value=model_files[0])
|
326 |
+
|
327 |
+
def update_model_names_gr(self) -> tuple[gr.Dropdown, gr.Dropdown, gr.Button]:
|
328 |
+
self.refresh()
|
329 |
+
initial_model_name = self.model_names[0]
|
330 |
+
initial_model_files = self.model_files_dict[initial_model_name]
|
331 |
+
return (
|
332 |
+
gr.Dropdown(choices=self.model_names, value=initial_model_name),
|
333 |
+
gr.Dropdown(choices=initial_model_files, value=initial_model_files[0]),
|
334 |
+
gr.Button(interactive=False), # For tts_button
|
335 |
+
)
|
commons.py
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import torch
|
3 |
+
from torch.nn import functional as F
|
4 |
+
|
5 |
+
|
6 |
+
def init_weights(m, mean=0.0, std=0.01):
|
7 |
+
classname = m.__class__.__name__
|
8 |
+
if classname.find("Conv") != -1:
|
9 |
+
m.weight.data.normal_(mean, std)
|
10 |
+
|
11 |
+
|
12 |
+
def get_padding(kernel_size, dilation=1):
|
13 |
+
return int((kernel_size * dilation - dilation) / 2)
|
14 |
+
|
15 |
+
|
16 |
+
def convert_pad_shape(pad_shape):
|
17 |
+
layer = pad_shape[::-1]
|
18 |
+
pad_shape = [item for sublist in layer for item in sublist]
|
19 |
+
return pad_shape
|
20 |
+
|
21 |
+
|
22 |
+
def intersperse(lst, item):
|
23 |
+
result = [item] * (len(lst) * 2 + 1)
|
24 |
+
result[1::2] = lst
|
25 |
+
return result
|
26 |
+
|
27 |
+
|
28 |
+
def kl_divergence(m_p, logs_p, m_q, logs_q):
|
29 |
+
"""KL(P||Q)"""
|
30 |
+
kl = (logs_q - logs_p) - 0.5
|
31 |
+
kl += (
|
32 |
+
0.5 * (torch.exp(2.0 * logs_p) + ((m_p - m_q) ** 2)) * torch.exp(-2.0 * logs_q)
|
33 |
+
)
|
34 |
+
return kl
|
35 |
+
|
36 |
+
|
37 |
+
def rand_gumbel(shape):
|
38 |
+
"""Sample from the Gumbel distribution, protect from overflows."""
|
39 |
+
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
|
40 |
+
return -torch.log(-torch.log(uniform_samples))
|
41 |
+
|
42 |
+
|
43 |
+
def rand_gumbel_like(x):
|
44 |
+
g = rand_gumbel(x.size()).to(dtype=x.dtype, device=x.device)
|
45 |
+
return g
|
46 |
+
|
47 |
+
|
48 |
+
def slice_segments(x, ids_str, segment_size=4):
|
49 |
+
gather_indices = ids_str.view(x.size(0), 1, 1).repeat(
|
50 |
+
1, x.size(1), 1
|
51 |
+
) + torch.arange(segment_size, device=x.device)
|
52 |
+
return torch.gather(x, 2, gather_indices)
|
53 |
+
|
54 |
+
|
55 |
+
def rand_slice_segments(x, x_lengths=None, segment_size=4):
|
56 |
+
b, d, t = x.size()
|
57 |
+
if x_lengths is None:
|
58 |
+
x_lengths = t
|
59 |
+
ids_str_max = torch.clamp(x_lengths - segment_size + 1, min=0)
|
60 |
+
ids_str = (torch.rand([b], device=x.device) * ids_str_max).to(dtype=torch.long)
|
61 |
+
ret = slice_segments(x, ids_str, segment_size)
|
62 |
+
return ret, ids_str
|
63 |
+
|
64 |
+
|
65 |
+
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
|
66 |
+
position = torch.arange(length, dtype=torch.float)
|
67 |
+
num_timescales = channels // 2
|
68 |
+
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / (
|
69 |
+
num_timescales - 1
|
70 |
+
)
|
71 |
+
inv_timescales = min_timescale * torch.exp(
|
72 |
+
torch.arange(num_timescales, dtype=torch.float) * -log_timescale_increment
|
73 |
+
)
|
74 |
+
scaled_time = position.unsqueeze(0) * inv_timescales.unsqueeze(1)
|
75 |
+
signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 0)
|
76 |
+
signal = F.pad(signal, [0, 0, 0, channels % 2])
|
77 |
+
signal = signal.view(1, channels, length)
|
78 |
+
return signal
|
79 |
+
|
80 |
+
|
81 |
+
def add_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4):
|
82 |
+
b, channels, length = x.size()
|
83 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
84 |
+
return x + signal.to(dtype=x.dtype, device=x.device)
|
85 |
+
|
86 |
+
|
87 |
+
def cat_timing_signal_1d(x, min_timescale=1.0, max_timescale=1.0e4, axis=1):
|
88 |
+
b, channels, length = x.size()
|
89 |
+
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale)
|
90 |
+
return torch.cat([x, signal.to(dtype=x.dtype, device=x.device)], axis)
|
91 |
+
|
92 |
+
|
93 |
+
def subsequent_mask(length):
|
94 |
+
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
|
95 |
+
return mask
|
96 |
+
|
97 |
+
|
98 |
+
@torch.jit.script
|
99 |
+
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
100 |
+
n_channels_int = n_channels[0]
|
101 |
+
in_act = input_a + input_b
|
102 |
+
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
103 |
+
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
104 |
+
acts = t_act * s_act
|
105 |
+
return acts
|
106 |
+
|
107 |
+
|
108 |
+
def shift_1d(x):
|
109 |
+
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
|
110 |
+
return x
|
111 |
+
|
112 |
+
|
113 |
+
def sequence_mask(length, max_length=None):
|
114 |
+
if max_length is None:
|
115 |
+
max_length = length.max()
|
116 |
+
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
|
117 |
+
return x.unsqueeze(0) < length.unsqueeze(1)
|
118 |
+
|
119 |
+
|
120 |
+
def generate_path(duration, mask):
|
121 |
+
"""
|
122 |
+
duration: [b, 1, t_x]
|
123 |
+
mask: [b, 1, t_y, t_x]
|
124 |
+
"""
|
125 |
+
|
126 |
+
b, _, t_y, t_x = mask.shape
|
127 |
+
cum_duration = torch.cumsum(duration, -1)
|
128 |
+
|
129 |
+
cum_duration_flat = cum_duration.view(b * t_x)
|
130 |
+
path = sequence_mask(cum_duration_flat, t_y).to(mask.dtype)
|
131 |
+
path = path.view(b, t_x, t_y)
|
132 |
+
path = path - F.pad(path, convert_pad_shape([[0, 0], [1, 0], [0, 0]]))[:, :-1]
|
133 |
+
path = path.unsqueeze(1).transpose(2, 3) * mask
|
134 |
+
return path
|
135 |
+
|
136 |
+
|
137 |
+
def clip_grad_value_(parameters, clip_value, norm_type=2):
|
138 |
+
if isinstance(parameters, torch.Tensor):
|
139 |
+
parameters = [parameters]
|
140 |
+
parameters = list(filter(lambda p: p.grad is not None, parameters))
|
141 |
+
norm_type = float(norm_type)
|
142 |
+
if clip_value is not None:
|
143 |
+
clip_value = float(clip_value)
|
144 |
+
|
145 |
+
total_norm = 0
|
146 |
+
for p in parameters:
|
147 |
+
param_norm = p.grad.data.norm(norm_type)
|
148 |
+
total_norm += param_norm.item() ** norm_type
|
149 |
+
if clip_value is not None:
|
150 |
+
p.grad.data.clamp_(min=-clip_value, max=clip_value)
|
151 |
+
total_norm = total_norm ** (1.0 / norm_type)
|
152 |
+
return total_norm
|
config.py
ADDED
@@ -0,0 +1,291 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
@Desc: 全局配置文件读取
|
3 |
+
"""
|
4 |
+
|
5 |
+
import os
|
6 |
+
import shutil
|
7 |
+
from typing import Dict, List
|
8 |
+
|
9 |
+
import torch
|
10 |
+
import yaml
|
11 |
+
|
12 |
+
from common.log import logger
|
13 |
+
|
14 |
+
# If not cuda available, set possible devices to cpu
|
15 |
+
cuda_available = torch.cuda.is_available()
|
16 |
+
|
17 |
+
|
18 |
+
class Resample_config:
|
19 |
+
"""重采样配置"""
|
20 |
+
|
21 |
+
def __init__(self, in_dir: str, out_dir: str, sampling_rate: int = 44100):
|
22 |
+
self.sampling_rate: int = sampling_rate # 目标采样率
|
23 |
+
self.in_dir: str = in_dir # 待处理音频目录路径
|
24 |
+
self.out_dir: str = out_dir # 重采样输出路径
|
25 |
+
|
26 |
+
@classmethod
|
27 |
+
def from_dict(cls, dataset_path: str, data: Dict[str, any]):
|
28 |
+
"""从字典中生成实例"""
|
29 |
+
|
30 |
+
# 不检查路径是否有效,此逻辑在resample.py中处理
|
31 |
+
data["in_dir"] = os.path.join(dataset_path, data["in_dir"])
|
32 |
+
data["out_dir"] = os.path.join(dataset_path, data["out_dir"])
|
33 |
+
|
34 |
+
return cls(**data)
|
35 |
+
|
36 |
+
|
37 |
+
class Preprocess_text_config:
|
38 |
+
"""数据预处理配置"""
|
39 |
+
|
40 |
+
def __init__(
|
41 |
+
self,
|
42 |
+
transcription_path: str,
|
43 |
+
cleaned_path: str,
|
44 |
+
train_path: str,
|
45 |
+
val_path: str,
|
46 |
+
config_path: str,
|
47 |
+
val_per_lang: int = 5,
|
48 |
+
max_val_total: int = 10000,
|
49 |
+
clean: bool = True,
|
50 |
+
):
|
51 |
+
self.transcription_path: str = (
|
52 |
+
transcription_path # 原始文本文件路径,文本格式应为{wav_path}|{speaker_name}|{language}|{text}。
|
53 |
+
)
|
54 |
+
self.cleaned_path: str = (
|
55 |
+
cleaned_path # 数据清洗后文本路径,可以不填。不填则将在原始文本目录生成
|
56 |
+
)
|
57 |
+
self.train_path: str = (
|
58 |
+
train_path # 训练集路径,可以不填。不填则将在原始文本目录生成
|
59 |
+
)
|
60 |
+
self.val_path: str = (
|
61 |
+
val_path # 验证集路径,可以不填。不填则将在原始文本目录生成
|
62 |
+
)
|
63 |
+
self.config_path: str = config_path # 配置文件路径
|
64 |
+
self.val_per_lang: int = val_per_lang # 每个speaker的验证集条数
|
65 |
+
self.max_val_total: int = (
|
66 |
+
max_val_total # 验证集最大条数,多于的会被截断并放到训练集中
|
67 |
+
)
|
68 |
+
self.clean: bool = clean # 是否进行数据清洗
|
69 |
+
|
70 |
+
@classmethod
|
71 |
+
def from_dict(cls, dataset_path: str, data: Dict[str, any]):
|
72 |
+
"""从字典中生成实例"""
|
73 |
+
|
74 |
+
data["transcription_path"] = os.path.join(
|
75 |
+
dataset_path, data["transcription_path"]
|
76 |
+
)
|
77 |
+
if data["cleaned_path"] == "" or data["cleaned_path"] is None:
|
78 |
+
data["cleaned_path"] = None
|
79 |
+
else:
|
80 |
+
data["cleaned_path"] = os.path.join(dataset_path, data["cleaned_path"])
|
81 |
+
data["train_path"] = os.path.join(dataset_path, data["train_path"])
|
82 |
+
data["val_path"] = os.path.join(dataset_path, data["val_path"])
|
83 |
+
data["config_path"] = os.path.join(dataset_path, data["config_path"])
|
84 |
+
|
85 |
+
return cls(**data)
|
86 |
+
|
87 |
+
|
88 |
+
class Bert_gen_config:
|
89 |
+
"""bert_gen 配置"""
|
90 |
+
|
91 |
+
def __init__(
|
92 |
+
self,
|
93 |
+
config_path: str,
|
94 |
+
num_processes: int = 2,
|
95 |
+
device: str = "cuda",
|
96 |
+
use_multi_device: bool = False,
|
97 |
+
):
|
98 |
+
self.config_path = config_path
|
99 |
+
self.num_processes = num_processes
|
100 |
+
if not cuda_available:
|
101 |
+
device = "cpu"
|
102 |
+
self.device = device
|
103 |
+
self.use_multi_device = use_multi_device
|
104 |
+
|
105 |
+
@classmethod
|
106 |
+
def from_dict(cls, dataset_path: str, data: Dict[str, any]):
|
107 |
+
data["config_path"] = os.path.join(dataset_path, data["config_path"])
|
108 |
+
|
109 |
+
return cls(**data)
|
110 |
+
|
111 |
+
|
112 |
+
class Style_gen_config:
|
113 |
+
"""style_gen 配置"""
|
114 |
+
|
115 |
+
def __init__(
|
116 |
+
self,
|
117 |
+
config_path: str,
|
118 |
+
num_processes: int = 4,
|
119 |
+
device: str = "cuda",
|
120 |
+
):
|
121 |
+
self.config_path = config_path
|
122 |
+
self.num_processes = num_processes
|
123 |
+
if not cuda_available:
|
124 |
+
device = "cpu"
|
125 |
+
self.device = device
|
126 |
+
|
127 |
+
@classmethod
|
128 |
+
def from_dict(cls, dataset_path: str, data: Dict[str, any]):
|
129 |
+
data["config_path"] = os.path.join(dataset_path, data["config_path"])
|
130 |
+
|
131 |
+
return cls(**data)
|
132 |
+
|
133 |
+
|
134 |
+
class Train_ms_config:
|
135 |
+
"""训练配置"""
|
136 |
+
|
137 |
+
def __init__(
|
138 |
+
self,
|
139 |
+
config_path: str,
|
140 |
+
env: Dict[str, any],
|
141 |
+
# base: Dict[str, any],
|
142 |
+
model_dir: str,
|
143 |
+
num_workers: int,
|
144 |
+
spec_cache: bool,
|
145 |
+
keep_ckpts: int,
|
146 |
+
):
|
147 |
+
self.env = env # 需要加载的环境变量
|
148 |
+
# self.base = base # 底模配置
|
149 |
+
self.model_dir = model_dir # 训练模型存储目录,该路径为相对于dataset_path的路径,而非项目根目录
|
150 |
+
self.config_path = config_path # 配置文件路径
|
151 |
+
self.num_workers = num_workers # worker数量
|
152 |
+
self.spec_cache = spec_cache # 是否启用spec缓存
|
153 |
+
self.keep_ckpts = keep_ckpts # ckpt数量
|
154 |
+
|
155 |
+
@classmethod
|
156 |
+
def from_dict(cls, dataset_path: str, data: Dict[str, any]):
|
157 |
+
# data["model"] = os.path.join(dataset_path, data["model"])
|
158 |
+
data["config_path"] = os.path.join(dataset_path, data["config_path"])
|
159 |
+
|
160 |
+
return cls(**data)
|
161 |
+
|
162 |
+
|
163 |
+
class Webui_config:
|
164 |
+
"""webui 配置 (for webui.py, not supported now)"""
|
165 |
+
|
166 |
+
def __init__(
|
167 |
+
self,
|
168 |
+
device: str,
|
169 |
+
model: str,
|
170 |
+
config_path: str,
|
171 |
+
language_identification_library: str,
|
172 |
+
port: int = 7860,
|
173 |
+
share: bool = False,
|
174 |
+
debug: bool = False,
|
175 |
+
):
|
176 |
+
if not cuda_available:
|
177 |
+
device = "cpu"
|
178 |
+
self.device: str = device
|
179 |
+
self.model: str = model # 端口号
|
180 |
+
self.config_path: str = config_path # 是否公开部署,对外网开放
|
181 |
+
self.port: int = port # 是否开启debug模式
|
182 |
+
self.share: bool = share # 模型路径
|
183 |
+
self.debug: bool = debug # 配置文件路径
|
184 |
+
self.language_identification_library: str = (
|
185 |
+
language_identification_library # 语种识别库
|
186 |
+
)
|
187 |
+
|
188 |
+
@classmethod
|
189 |
+
def from_dict(cls, dataset_path: str, data: Dict[str, any]):
|
190 |
+
data["config_path"] = os.path.join(dataset_path, data["config_path"])
|
191 |
+
data["model"] = os.path.join(dataset_path, data["model"])
|
192 |
+
return cls(**data)
|
193 |
+
|
194 |
+
|
195 |
+
class Server_config:
|
196 |
+
def __init__(
|
197 |
+
self,
|
198 |
+
port: int = 5000,
|
199 |
+
device: str = "cuda",
|
200 |
+
limit: int = 100,
|
201 |
+
language: str = "JP",
|
202 |
+
origins: List[str] = None,
|
203 |
+
):
|
204 |
+
self.port: int = port
|
205 |
+
if not cuda_available:
|
206 |
+
device = "cpu"
|
207 |
+
self.device: str = device
|
208 |
+
self.language: str = language
|
209 |
+
self.limit: int = limit
|
210 |
+
self.origins: List[str] = origins
|
211 |
+
|
212 |
+
@classmethod
|
213 |
+
def from_dict(cls, data: Dict[str, any]):
|
214 |
+
return cls(**data)
|
215 |
+
|
216 |
+
|
217 |
+
class Translate_config:
|
218 |
+
"""翻译api配置"""
|
219 |
+
|
220 |
+
def __init__(self, app_key: str, secret_key: str):
|
221 |
+
self.app_key = app_key
|
222 |
+
self.secret_key = secret_key
|
223 |
+
|
224 |
+
@classmethod
|
225 |
+
def from_dict(cls, data: Dict[str, any]):
|
226 |
+
return cls(**data)
|
227 |
+
|
228 |
+
|
229 |
+
class Config:
|
230 |
+
def __init__(self, config_path: str, path_config: dict[str, str]):
|
231 |
+
if not os.path.isfile(config_path) and os.path.isfile("default_config.yml"):
|
232 |
+
shutil.copy(src="default_config.yml", dst=config_path)
|
233 |
+
logger.info(
|
234 |
+
f"A configuration file {config_path} has been generated based on the default configuration file default_config.yml."
|
235 |
+
)
|
236 |
+
logger.info(
|
237 |
+
"If you have no special needs, please do not modify default_config.yml."
|
238 |
+
)
|
239 |
+
# sys.exit(0)
|
240 |
+
with open(file=config_path, mode="r", encoding="utf-8") as file:
|
241 |
+
yaml_config: Dict[str, any] = yaml.safe_load(file.read())
|
242 |
+
model_name: str = yaml_config["model_name"]
|
243 |
+
self.model_name: str = model_name
|
244 |
+
if "dataset_path" in yaml_config:
|
245 |
+
dataset_path = yaml_config["dataset_path"]
|
246 |
+
else:
|
247 |
+
dataset_path = os.path.join(path_config["dataset_root"], model_name)
|
248 |
+
self.dataset_path: str = dataset_path
|
249 |
+
self.assets_root: str = path_config["assets_root"]
|
250 |
+
self.out_dir = os.path.join(self.assets_root, model_name)
|
251 |
+
self.resample_config: Resample_config = Resample_config.from_dict(
|
252 |
+
dataset_path, yaml_config["resample"]
|
253 |
+
)
|
254 |
+
self.preprocess_text_config: Preprocess_text_config = (
|
255 |
+
Preprocess_text_config.from_dict(
|
256 |
+
dataset_path, yaml_config["preprocess_text"]
|
257 |
+
)
|
258 |
+
)
|
259 |
+
self.bert_gen_config: Bert_gen_config = Bert_gen_config.from_dict(
|
260 |
+
dataset_path, yaml_config["bert_gen"]
|
261 |
+
)
|
262 |
+
self.style_gen_config: Style_gen_config = Style_gen_config.from_dict(
|
263 |
+
dataset_path, yaml_config["style_gen"]
|
264 |
+
)
|
265 |
+
self.train_ms_config: Train_ms_config = Train_ms_config.from_dict(
|
266 |
+
dataset_path, yaml_config["train_ms"]
|
267 |
+
)
|
268 |
+
self.webui_config: Webui_config = Webui_config.from_dict(
|
269 |
+
dataset_path, yaml_config["webui"]
|
270 |
+
)
|
271 |
+
self.server_config: Server_config = Server_config.from_dict(
|
272 |
+
yaml_config["server"]
|
273 |
+
)
|
274 |
+
# self.translate_config: Translate_config = Translate_config.from_dict(
|
275 |
+
# yaml_config["translate"]
|
276 |
+
# )
|
277 |
+
|
278 |
+
|
279 |
+
with open(os.path.join("configs", "paths.yml"), "r", encoding="utf-8") as f:
|
280 |
+
path_config: dict[str, str] = yaml.safe_load(f.read())
|
281 |
+
# Should contain the following keys:
|
282 |
+
# - dataset_root: the root directory of the dataset, default to "Data"
|
283 |
+
# - assets_root: the root directory of the assets, default to "model_assets"
|
284 |
+
|
285 |
+
|
286 |
+
try:
|
287 |
+
config = Config("config.yml", path_config)
|
288 |
+
except (TypeError, KeyError):
|
289 |
+
logger.warning("Old config.yml found. Replace it with default_config.yml.")
|
290 |
+
shutil.copy(src="default_config.yml", dst="config.yml")
|
291 |
+
config = Config("config.yml", path_config)
|
configs/config.json
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"model_name": "your_model_name",
|
3 |
+
"train": {
|
4 |
+
"log_interval": 200,
|
5 |
+
"eval_interval": 1000,
|
6 |
+
"seed": 42,
|
7 |
+
"epochs": 1000,
|
8 |
+
"learning_rate": 0.0002,
|
9 |
+
"betas": [0.8, 0.99],
|
10 |
+
"eps": 1e-9,
|
11 |
+
"batch_size": 2,
|
12 |
+
"bf16_run": false,
|
13 |
+
"lr_decay": 0.99995,
|
14 |
+
"segment_size": 16384,
|
15 |
+
"init_lr_ratio": 1,
|
16 |
+
"warmup_epochs": 0,
|
17 |
+
"c_mel": 45,
|
18 |
+
"c_kl": 1.0,
|
19 |
+
"skip_optimizer": false,
|
20 |
+
"freeze_ZH_bert": false,
|
21 |
+
"freeze_JP_bert": false,
|
22 |
+
"freeze_EN_bert": false,
|
23 |
+
"freeze_style": false,
|
24 |
+
"freeze_encoder": false
|
25 |
+
},
|
26 |
+
"data": {
|
27 |
+
"training_files": "Data/your_model_name/filelists/train.list",
|
28 |
+
"validation_files": "Data/your_model_name/filelists/val.list",
|
29 |
+
"max_wav_value": 32768.0,
|
30 |
+
"sampling_rate": 44100,
|
31 |
+
"filter_length": 2048,
|
32 |
+
"hop_length": 512,
|
33 |
+
"win_length": 2048,
|
34 |
+
"n_mel_channels": 128,
|
35 |
+
"mel_fmin": 0.0,
|
36 |
+
"mel_fmax": null,
|
37 |
+
"add_blank": true,
|
38 |
+
"n_speakers": 1,
|
39 |
+
"cleaned_text": true,
|
40 |
+
"num_styles": 1,
|
41 |
+
"style2id": {
|
42 |
+
"Neutral": 0
|
43 |
+
}
|
44 |
+
},
|
45 |
+
"model": {
|
46 |
+
"use_spk_conditioned_encoder": true,
|
47 |
+
"use_noise_scaled_mas": true,
|
48 |
+
"use_mel_posterior_encoder": false,
|
49 |
+
"use_duration_discriminator": true,
|
50 |
+
"inter_channels": 192,
|
51 |
+
"hidden_channels": 192,
|
52 |
+
"filter_channels": 768,
|
53 |
+
"n_heads": 2,
|
54 |
+
"n_layers": 6,
|
55 |
+
"kernel_size": 3,
|
56 |
+
"p_dropout": 0.1,
|
57 |
+
"resblock": "1",
|
58 |
+
"resblock_kernel_sizes": [3, 7, 11],
|
59 |
+
"resblock_dilation_sizes": [
|
60 |
+
[1, 3, 5],
|
61 |
+
[1, 3, 5],
|
62 |
+
[1, 3, 5]
|
63 |
+
],
|
64 |
+
"upsample_rates": [8, 8, 2, 2, 2],
|
65 |
+
"upsample_initial_channel": 512,
|
66 |
+
"upsample_kernel_sizes": [16, 16, 8, 2, 2],
|
67 |
+
"n_layers_q": 3,
|
68 |
+
"use_spectral_norm": false,
|
69 |
+
"gin_channels": 256
|
70 |
+
},
|
71 |
+
"version": "2.3"
|
72 |
+
}
|
configs/configs_jp_extra.json
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"train": {
|
3 |
+
"log_interval": 200,
|
4 |
+
"eval_interval": 1000,
|
5 |
+
"seed": 42,
|
6 |
+
"epochs": 1000,
|
7 |
+
"learning_rate": 0.0001,
|
8 |
+
"betas": [0.8, 0.99],
|
9 |
+
"eps": 1e-9,
|
10 |
+
"batch_size": 2,
|
11 |
+
"bf16_run": false,
|
12 |
+
"fp16_run": false,
|
13 |
+
"lr_decay": 0.99996,
|
14 |
+
"segment_size": 16384,
|
15 |
+
"init_lr_ratio": 1,
|
16 |
+
"warmup_epochs": 0,
|
17 |
+
"c_mel": 45,
|
18 |
+
"c_kl": 1.0,
|
19 |
+
"c_commit": 100,
|
20 |
+
"skip_optimizer": false,
|
21 |
+
"freeze_ZH_bert": false,
|
22 |
+
"freeze_JP_bert": false,
|
23 |
+
"freeze_EN_bert": false,
|
24 |
+
"freeze_emo": false,
|
25 |
+
"freeze_style": false,
|
26 |
+
"freeze_decoder": false
|
27 |
+
},
|
28 |
+
"data": {
|
29 |
+
"use_jp_extra": true,
|
30 |
+
"training_files": "filelists/train.list",
|
31 |
+
"validation_files": "filelists/val.list",
|
32 |
+
"max_wav_value": 32768.0,
|
33 |
+
"sampling_rate": 44100,
|
34 |
+
"filter_length": 2048,
|
35 |
+
"hop_length": 512,
|
36 |
+
"win_length": 2048,
|
37 |
+
"n_mel_channels": 128,
|
38 |
+
"mel_fmin": 0.0,
|
39 |
+
"mel_fmax": null,
|
40 |
+
"add_blank": true,
|
41 |
+
"n_speakers": 512,
|
42 |
+
"cleaned_text": true
|
43 |
+
},
|
44 |
+
"model": {
|
45 |
+
"use_spk_conditioned_encoder": true,
|
46 |
+
"use_noise_scaled_mas": true,
|
47 |
+
"use_mel_posterior_encoder": false,
|
48 |
+
"use_duration_discriminator": false,
|
49 |
+
"use_wavlm_discriminator": true,
|
50 |
+
"inter_channels": 192,
|
51 |
+
"hidden_channels": 192,
|
52 |
+
"filter_channels": 768,
|
53 |
+
"n_heads": 2,
|
54 |
+
"n_layers": 6,
|
55 |
+
"kernel_size": 3,
|
56 |
+
"p_dropout": 0.1,
|
57 |
+
"resblock": "1",
|
58 |
+
"resblock_kernel_sizes": [3, 7, 11],
|
59 |
+
"resblock_dilation_sizes": [
|
60 |
+
[1, 3, 5],
|
61 |
+
[1, 3, 5],
|
62 |
+
[1, 3, 5]
|
63 |
+
],
|
64 |
+
"upsample_rates": [8, 8, 2, 2, 2],
|
65 |
+
"upsample_initial_channel": 512,
|
66 |
+
"upsample_kernel_sizes": [16, 16, 8, 2, 2],
|
67 |
+
"n_layers_q": 3,
|
68 |
+
"use_spectral_norm": false,
|
69 |
+
"gin_channels": 512,
|
70 |
+
"slm": {
|
71 |
+
"model": "./slm/wavlm-base-plus",
|
72 |
+
"sr": 16000,
|
73 |
+
"hidden": 768,
|
74 |
+
"nlayers": 13,
|
75 |
+
"initial_channel": 64
|
76 |
+
}
|
77 |
+
},
|
78 |
+
"version": "2.3-JP-Extra"
|
79 |
+
}
|
configs/paths.yml
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Root directory of the training dataset.
|
2 |
+
# The training dataset of {model_name} should be placed in {dataset_root}/{model_name}.
|
3 |
+
dataset_root: Data
|
4 |
+
|
5 |
+
# Root directory of the model assets (for inference).
|
6 |
+
# In training, the model assets will be saved to {assets_root}/{model_name},
|
7 |
+
# and in inference, we load all the models from {assets_root}.
|
8 |
+
assets_root: model_assets
|
data_utils.py
ADDED
@@ -0,0 +1,456 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import random
|
3 |
+
import sys
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
import torch.utils.data
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
import commons
|
11 |
+
from config import config
|
12 |
+
from mel_processing import mel_spectrogram_torch, spectrogram_torch
|
13 |
+
from text import cleaned_text_to_sequence
|
14 |
+
from common.log import logger
|
15 |
+
from utils import load_filepaths_and_text, load_wav_to_torch
|
16 |
+
|
17 |
+
"""Multi speaker version"""
|
18 |
+
|
19 |
+
|
20 |
+
class TextAudioSpeakerLoader(torch.utils.data.Dataset):
|
21 |
+
"""
|
22 |
+
1) loads audio, speaker_id, text pairs
|
23 |
+
2) normalizes text and converts them to sequences of integers
|
24 |
+
3) computes spectrograms from audio files.
|
25 |
+
"""
|
26 |
+
|
27 |
+
def __init__(self, audiopaths_sid_text, hparams):
|
28 |
+
self.audiopaths_sid_text = load_filepaths_and_text(audiopaths_sid_text)
|
29 |
+
self.max_wav_value = hparams.max_wav_value
|
30 |
+
self.sampling_rate = hparams.sampling_rate
|
31 |
+
self.filter_length = hparams.filter_length
|
32 |
+
self.hop_length = hparams.hop_length
|
33 |
+
self.win_length = hparams.win_length
|
34 |
+
self.sampling_rate = hparams.sampling_rate
|
35 |
+
self.spk_map = hparams.spk2id
|
36 |
+
self.hparams = hparams
|
37 |
+
self.use_jp_extra = getattr(hparams, "use_jp_extra", False)
|
38 |
+
|
39 |
+
self.use_mel_spec_posterior = getattr(
|
40 |
+
hparams, "use_mel_posterior_encoder", False
|
41 |
+
)
|
42 |
+
if self.use_mel_spec_posterior:
|
43 |
+
self.n_mel_channels = getattr(hparams, "n_mel_channels", 80)
|
44 |
+
|
45 |
+
self.cleaned_text = getattr(hparams, "cleaned_text", False)
|
46 |
+
|
47 |
+
self.add_blank = hparams.add_blank
|
48 |
+
self.min_text_len = getattr(hparams, "min_text_len", 1)
|
49 |
+
self.max_text_len = getattr(hparams, "max_text_len", 384)
|
50 |
+
|
51 |
+
random.seed(1234)
|
52 |
+
random.shuffle(self.audiopaths_sid_text)
|
53 |
+
self._filter()
|
54 |
+
|
55 |
+
def _filter(self):
|
56 |
+
"""
|
57 |
+
Filter text & store spec lengths
|
58 |
+
"""
|
59 |
+
# Store spectrogram lengths for Bucketing
|
60 |
+
# wav_length ~= file_size / (wav_channels * Bytes per dim) = file_size / (1 * 2)
|
61 |
+
# spec_length = wav_length // hop_length
|
62 |
+
|
63 |
+
audiopaths_sid_text_new = []
|
64 |
+
lengths = []
|
65 |
+
skipped = 0
|
66 |
+
logger.info("Init dataset...")
|
67 |
+
for _id, spk, language, text, phones, tone, word2ph in tqdm(
|
68 |
+
self.audiopaths_sid_text, file=sys.stdout
|
69 |
+
):
|
70 |
+
audiopath = f"{_id}"
|
71 |
+
if self.min_text_len <= len(phones) and len(phones) <= self.max_text_len:
|
72 |
+
phones = phones.split(" ")
|
73 |
+
tone = [int(i) for i in tone.split(" ")]
|
74 |
+
word2ph = [int(i) for i in word2ph.split(" ")]
|
75 |
+
audiopaths_sid_text_new.append(
|
76 |
+
[audiopath, spk, language, text, phones, tone, word2ph]
|
77 |
+
)
|
78 |
+
lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))
|
79 |
+
else:
|
80 |
+
skipped += 1
|
81 |
+
logger.info(
|
82 |
+
"skipped: "
|
83 |
+
+ str(skipped)
|
84 |
+
+ ", total: "
|
85 |
+
+ str(len(self.audiopaths_sid_text))
|
86 |
+
)
|
87 |
+
self.audiopaths_sid_text = audiopaths_sid_text_new
|
88 |
+
self.lengths = lengths
|
89 |
+
|
90 |
+
def get_audio_text_speaker_pair(self, audiopath_sid_text):
|
91 |
+
# separate filename, speaker_id and text
|
92 |
+
audiopath, sid, language, text, phones, tone, word2ph = audiopath_sid_text
|
93 |
+
|
94 |
+
bert, ja_bert, en_bert, phones, tone, language = self.get_text(
|
95 |
+
text, word2ph, phones, tone, language, audiopath
|
96 |
+
)
|
97 |
+
|
98 |
+
spec, wav = self.get_audio(audiopath)
|
99 |
+
sid = torch.LongTensor([int(self.spk_map[sid])])
|
100 |
+
style_vec = torch.FloatTensor(np.load(f"{audiopath}.npy"))
|
101 |
+
if self.use_jp_extra:
|
102 |
+
return (phones, spec, wav, sid, tone, language, ja_bert, style_vec)
|
103 |
+
else:
|
104 |
+
return (
|
105 |
+
phones,
|
106 |
+
spec,
|
107 |
+
wav,
|
108 |
+
sid,
|
109 |
+
tone,
|
110 |
+
language,
|
111 |
+
bert,
|
112 |
+
ja_bert,
|
113 |
+
en_bert,
|
114 |
+
style_vec,
|
115 |
+
)
|
116 |
+
|
117 |
+
def get_audio(self, filename):
|
118 |
+
audio, sampling_rate = load_wav_to_torch(filename)
|
119 |
+
if sampling_rate != self.sampling_rate:
|
120 |
+
raise ValueError(
|
121 |
+
"{} {} SR doesn't match target {} SR".format(
|
122 |
+
filename, sampling_rate, self.sampling_rate
|
123 |
+
)
|
124 |
+
)
|
125 |
+
audio_norm = audio / self.max_wav_value
|
126 |
+
audio_norm = audio_norm.unsqueeze(0)
|
127 |
+
spec_filename = filename.replace(".wav", ".spec.pt")
|
128 |
+
if self.use_mel_spec_posterior:
|
129 |
+
spec_filename = spec_filename.replace(".spec.pt", ".mel.pt")
|
130 |
+
try:
|
131 |
+
spec = torch.load(spec_filename)
|
132 |
+
except:
|
133 |
+
if self.use_mel_spec_posterior:
|
134 |
+
spec = mel_spectrogram_torch(
|
135 |
+
audio_norm,
|
136 |
+
self.filter_length,
|
137 |
+
self.n_mel_channels,
|
138 |
+
self.sampling_rate,
|
139 |
+
self.hop_length,
|
140 |
+
self.win_length,
|
141 |
+
self.hparams.mel_fmin,
|
142 |
+
self.hparams.mel_fmax,
|
143 |
+
center=False,
|
144 |
+
)
|
145 |
+
else:
|
146 |
+
spec = spectrogram_torch(
|
147 |
+
audio_norm,
|
148 |
+
self.filter_length,
|
149 |
+
self.sampling_rate,
|
150 |
+
self.hop_length,
|
151 |
+
self.win_length,
|
152 |
+
center=False,
|
153 |
+
)
|
154 |
+
spec = torch.squeeze(spec, 0)
|
155 |
+
if config.train_ms_config.spec_cache:
|
156 |
+
torch.save(spec, spec_filename)
|
157 |
+
return spec, audio_norm
|
158 |
+
|
159 |
+
def get_text(self, text, word2ph, phone, tone, language_str, wav_path):
|
160 |
+
phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str)
|
161 |
+
if self.add_blank:
|
162 |
+
phone = commons.intersperse(phone, 0)
|
163 |
+
tone = commons.intersperse(tone, 0)
|
164 |
+
language = commons.intersperse(language, 0)
|
165 |
+
for i in range(len(word2ph)):
|
166 |
+
word2ph[i] = word2ph[i] * 2
|
167 |
+
word2ph[0] += 1
|
168 |
+
bert_path = wav_path.replace(".wav", ".bert.pt")
|
169 |
+
try:
|
170 |
+
bert_ori = torch.load(bert_path)
|
171 |
+
assert bert_ori.shape[-1] == len(phone)
|
172 |
+
except Exception as e:
|
173 |
+
logger.warning("Bert load Failed")
|
174 |
+
logger.warning(e)
|
175 |
+
|
176 |
+
if language_str == "ZH":
|
177 |
+
bert = bert_ori
|
178 |
+
ja_bert = torch.zeros(1024, len(phone))
|
179 |
+
en_bert = torch.zeros(1024, len(phone))
|
180 |
+
elif language_str == "JP":
|
181 |
+
bert = torch.zeros(1024, len(phone))
|
182 |
+
ja_bert = bert_ori
|
183 |
+
en_bert = torch.zeros(1024, len(phone))
|
184 |
+
elif language_str == "EN":
|
185 |
+
bert = torch.zeros(1024, len(phone))
|
186 |
+
ja_bert = torch.zeros(1024, len(phone))
|
187 |
+
en_bert = bert_ori
|
188 |
+
phone = torch.LongTensor(phone)
|
189 |
+
tone = torch.LongTensor(tone)
|
190 |
+
language = torch.LongTensor(language)
|
191 |
+
return bert, ja_bert, en_bert, phone, tone, language
|
192 |
+
|
193 |
+
def get_sid(self, sid):
|
194 |
+
sid = torch.LongTensor([int(sid)])
|
195 |
+
return sid
|
196 |
+
|
197 |
+
def __getitem__(self, index):
|
198 |
+
return self.get_audio_text_speaker_pair(self.audiopaths_sid_text[index])
|
199 |
+
|
200 |
+
def __len__(self):
|
201 |
+
return len(self.audiopaths_sid_text)
|
202 |
+
|
203 |
+
|
204 |
+
class TextAudioSpeakerCollate:
|
205 |
+
"""Zero-pads model inputs and targets"""
|
206 |
+
|
207 |
+
def __init__(self, return_ids=False, use_jp_extra=False):
|
208 |
+
self.return_ids = return_ids
|
209 |
+
self.use_jp_extra = use_jp_extra
|
210 |
+
|
211 |
+
def __call__(self, batch):
|
212 |
+
"""Collate's training batch from normalized text, audio and speaker identities
|
213 |
+
PARAMS
|
214 |
+
------
|
215 |
+
batch: [text_normalized, spec_normalized, wav_normalized, sid]
|
216 |
+
"""
|
217 |
+
# Right zero-pad all one-hot text sequences to max input length
|
218 |
+
_, ids_sorted_decreasing = torch.sort(
|
219 |
+
torch.LongTensor([x[1].size(1) for x in batch]), dim=0, descending=True
|
220 |
+
)
|
221 |
+
|
222 |
+
max_text_len = max([len(x[0]) for x in batch])
|
223 |
+
max_spec_len = max([x[1].size(1) for x in batch])
|
224 |
+
max_wav_len = max([x[2].size(1) for x in batch])
|
225 |
+
|
226 |
+
text_lengths = torch.LongTensor(len(batch))
|
227 |
+
spec_lengths = torch.LongTensor(len(batch))
|
228 |
+
wav_lengths = torch.LongTensor(len(batch))
|
229 |
+
sid = torch.LongTensor(len(batch))
|
230 |
+
|
231 |
+
text_padded = torch.LongTensor(len(batch), max_text_len)
|
232 |
+
tone_padded = torch.LongTensor(len(batch), max_text_len)
|
233 |
+
language_padded = torch.LongTensor(len(batch), max_text_len)
|
234 |
+
# This is ZH bert if not use_jp_extra, JA bert if use_jp_extra
|
235 |
+
bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
|
236 |
+
if not self.use_jp_extra:
|
237 |
+
ja_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
|
238 |
+
en_bert_padded = torch.FloatTensor(len(batch), 1024, max_text_len)
|
239 |
+
style_vec = torch.FloatTensor(len(batch), 256)
|
240 |
+
|
241 |
+
spec_padded = torch.FloatTensor(len(batch), batch[0][1].size(0), max_spec_len)
|
242 |
+
wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)
|
243 |
+
text_padded.zero_()
|
244 |
+
tone_padded.zero_()
|
245 |
+
language_padded.zero_()
|
246 |
+
spec_padded.zero_()
|
247 |
+
wav_padded.zero_()
|
248 |
+
bert_padded.zero_()
|
249 |
+
if not self.use_jp_extra:
|
250 |
+
ja_bert_padded.zero_()
|
251 |
+
en_bert_padded.zero_()
|
252 |
+
style_vec.zero_()
|
253 |
+
|
254 |
+
for i in range(len(ids_sorted_decreasing)):
|
255 |
+
row = batch[ids_sorted_decreasing[i]]
|
256 |
+
|
257 |
+
text = row[0]
|
258 |
+
text_padded[i, : text.size(0)] = text
|
259 |
+
text_lengths[i] = text.size(0)
|
260 |
+
|
261 |
+
spec = row[1]
|
262 |
+
spec_padded[i, :, : spec.size(1)] = spec
|
263 |
+
spec_lengths[i] = spec.size(1)
|
264 |
+
|
265 |
+
wav = row[2]
|
266 |
+
wav_padded[i, :, : wav.size(1)] = wav
|
267 |
+
wav_lengths[i] = wav.size(1)
|
268 |
+
|
269 |
+
sid[i] = row[3]
|
270 |
+
|
271 |
+
tone = row[4]
|
272 |
+
tone_padded[i, : tone.size(0)] = tone
|
273 |
+
|
274 |
+
language = row[5]
|
275 |
+
language_padded[i, : language.size(0)] = language
|
276 |
+
|
277 |
+
bert = row[6]
|
278 |
+
bert_padded[i, :, : bert.size(1)] = bert
|
279 |
+
|
280 |
+
if self.use_jp_extra:
|
281 |
+
style_vec[i, :] = row[7]
|
282 |
+
else:
|
283 |
+
ja_bert = row[7]
|
284 |
+
ja_bert_padded[i, :, : ja_bert.size(1)] = ja_bert
|
285 |
+
|
286 |
+
en_bert = row[8]
|
287 |
+
en_bert_padded[i, :, : en_bert.size(1)] = en_bert
|
288 |
+
style_vec[i, :] = row[9]
|
289 |
+
|
290 |
+
if self.use_jp_extra:
|
291 |
+
return (
|
292 |
+
text_padded,
|
293 |
+
text_lengths,
|
294 |
+
spec_padded,
|
295 |
+
spec_lengths,
|
296 |
+
wav_padded,
|
297 |
+
wav_lengths,
|
298 |
+
sid,
|
299 |
+
tone_padded,
|
300 |
+
language_padded,
|
301 |
+
bert_padded,
|
302 |
+
style_vec,
|
303 |
+
)
|
304 |
+
else:
|
305 |
+
return (
|
306 |
+
text_padded,
|
307 |
+
text_lengths,
|
308 |
+
spec_padded,
|
309 |
+
spec_lengths,
|
310 |
+
wav_padded,
|
311 |
+
wav_lengths,
|
312 |
+
sid,
|
313 |
+
tone_padded,
|
314 |
+
language_padded,
|
315 |
+
bert_padded,
|
316 |
+
ja_bert_padded,
|
317 |
+
en_bert_padded,
|
318 |
+
style_vec,
|
319 |
+
)
|
320 |
+
|
321 |
+
|
322 |
+
class DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):
|
323 |
+
"""
|
324 |
+
Maintain similar input lengths in a batch.
|
325 |
+
Length groups are specified by boundaries.
|
326 |
+
Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.
|
327 |
+
|
328 |
+
It removes samples which are not included in the boundaries.
|
329 |
+
Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.
|
330 |
+
"""
|
331 |
+
|
332 |
+
def __init__(
|
333 |
+
self,
|
334 |
+
dataset,
|
335 |
+
batch_size,
|
336 |
+
boundaries,
|
337 |
+
num_replicas=None,
|
338 |
+
rank=None,
|
339 |
+
shuffle=True,
|
340 |
+
):
|
341 |
+
super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)
|
342 |
+
self.lengths = dataset.lengths
|
343 |
+
self.batch_size = batch_size
|
344 |
+
self.boundaries = boundaries
|
345 |
+
|
346 |
+
self.buckets, self.num_samples_per_bucket = self._create_buckets()
|
347 |
+
logger.info(f"Bucket info: {self.num_samples_per_bucket}")
|
348 |
+
# logger.info(
|
349 |
+
# f"Unused samples: {len(self.lengths) - sum(self.num_samples_per_bucket)}"
|
350 |
+
# )
|
351 |
+
# ↑マイナスになることあるし、別にこれは使われないサンプル数ではないようだ……
|
352 |
+
# バケットの仕組みはよく分からない
|
353 |
+
|
354 |
+
self.total_size = sum(self.num_samples_per_bucket)
|
355 |
+
self.num_samples = self.total_size // self.num_replicas
|
356 |
+
|
357 |
+
def _create_buckets(self):
|
358 |
+
buckets = [[] for _ in range(len(self.boundaries) - 1)]
|
359 |
+
for i in range(len(self.lengths)):
|
360 |
+
length = self.lengths[i]
|
361 |
+
idx_bucket = self._bisect(length)
|
362 |
+
if idx_bucket != -1:
|
363 |
+
buckets[idx_bucket].append(i)
|
364 |
+
|
365 |
+
try:
|
366 |
+
for i in range(len(buckets) - 1, 0, -1):
|
367 |
+
if len(buckets[i]) == 0:
|
368 |
+
buckets.pop(i)
|
369 |
+
self.boundaries.pop(i + 1)
|
370 |
+
assert all(len(bucket) > 0 for bucket in buckets)
|
371 |
+
# When one bucket is not traversed
|
372 |
+
except Exception as e:
|
373 |
+
logger.info("Bucket warning ", e)
|
374 |
+
for i in range(len(buckets) - 1, -1, -1):
|
375 |
+
if len(buckets[i]) == 0:
|
376 |
+
buckets.pop(i)
|
377 |
+
self.boundaries.pop(i + 1)
|
378 |
+
|
379 |
+
num_samples_per_bucket = []
|
380 |
+
for i in range(len(buckets)):
|
381 |
+
len_bucket = len(buckets[i])
|
382 |
+
total_batch_size = self.num_replicas * self.batch_size
|
383 |
+
rem = (
|
384 |
+
total_batch_size - (len_bucket % total_batch_size)
|
385 |
+
) % total_batch_size
|
386 |
+
num_samples_per_bucket.append(len_bucket + rem)
|
387 |
+
return buckets, num_samples_per_bucket
|
388 |
+
|
389 |
+
def __iter__(self):
|
390 |
+
# deterministically shuffle based on epoch
|
391 |
+
g = torch.Generator()
|
392 |
+
g.manual_seed(self.epoch)
|
393 |
+
|
394 |
+
indices = []
|
395 |
+
if self.shuffle:
|
396 |
+
for bucket in self.buckets:
|
397 |
+
indices.append(torch.randperm(len(bucket), generator=g).tolist())
|
398 |
+
else:
|
399 |
+
for bucket in self.buckets:
|
400 |
+
indices.append(list(range(len(bucket))))
|
401 |
+
|
402 |
+
batches = []
|
403 |
+
for i in range(len(self.buckets)):
|
404 |
+
bucket = self.buckets[i]
|
405 |
+
len_bucket = len(bucket)
|
406 |
+
if len_bucket == 0:
|
407 |
+
continue
|
408 |
+
ids_bucket = indices[i]
|
409 |
+
num_samples_bucket = self.num_samples_per_bucket[i]
|
410 |
+
|
411 |
+
# add extra samples to make it evenly divisible
|
412 |
+
rem = num_samples_bucket - len_bucket
|
413 |
+
ids_bucket = (
|
414 |
+
ids_bucket
|
415 |
+
+ ids_bucket * (rem // len_bucket)
|
416 |
+
+ ids_bucket[: (rem % len_bucket)]
|
417 |
+
)
|
418 |
+
|
419 |
+
# subsample
|
420 |
+
ids_bucket = ids_bucket[self.rank :: self.num_replicas]
|
421 |
+
|
422 |
+
# batching
|
423 |
+
for j in range(len(ids_bucket) // self.batch_size):
|
424 |
+
batch = [
|
425 |
+
bucket[idx]
|
426 |
+
for idx in ids_bucket[
|
427 |
+
j * self.batch_size : (j + 1) * self.batch_size
|
428 |
+
]
|
429 |
+
]
|
430 |
+
batches.append(batch)
|
431 |
+
|
432 |
+
if self.shuffle:
|
433 |
+
batch_ids = torch.randperm(len(batches), generator=g).tolist()
|
434 |
+
batches = [batches[i] for i in batch_ids]
|
435 |
+
self.batches = batches
|
436 |
+
|
437 |
+
assert len(self.batches) * self.batch_size == self.num_samples
|
438 |
+
return iter(self.batches)
|
439 |
+
|
440 |
+
def _bisect(self, x, lo=0, hi=None):
|
441 |
+
if hi is None:
|
442 |
+
hi = len(self.boundaries) - 1
|
443 |
+
|
444 |
+
if hi > lo:
|
445 |
+
mid = (hi + lo) // 2
|
446 |
+
if self.boundaries[mid] < x and x <= self.boundaries[mid + 1]:
|
447 |
+
return mid
|
448 |
+
elif x <= self.boundaries[mid]:
|
449 |
+
return self._bisect(x, lo, mid)
|
450 |
+
else:
|
451 |
+
return self._bisect(x, mid + 1, hi)
|
452 |
+
else:
|
453 |
+
return -1
|
454 |
+
|
455 |
+
def __len__(self):
|
456 |
+
return self.num_samples // self.batch_size
|
default_config.yml
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
model_name: "model_name"
|
2 |
+
|
3 |
+
# If you want to use a specific dataset path, uncomment the following line.
|
4 |
+
# Otherwise, the dataset path is `{dataset_root}/{model_name}`.
|
5 |
+
|
6 |
+
# dataset_path: "your/dataset/path"
|
7 |
+
|
8 |
+
resample:
|
9 |
+
sampling_rate: 44100
|
10 |
+
in_dir: "raw"
|
11 |
+
out_dir: "wavs"
|
12 |
+
|
13 |
+
preprocess_text:
|
14 |
+
transcription_path: "esd.list"
|
15 |
+
cleaned_path: ""
|
16 |
+
train_path: "train.list"
|
17 |
+
val_path: "val.list"
|
18 |
+
config_path: "config.json"
|
19 |
+
val_per_lang: 0
|
20 |
+
max_val_total: 12
|
21 |
+
clean: true
|
22 |
+
|
23 |
+
bert_gen:
|
24 |
+
config_path: "config.json"
|
25 |
+
num_processes: 2
|
26 |
+
device: "cuda"
|
27 |
+
use_multi_device: false
|
28 |
+
|
29 |
+
style_gen:
|
30 |
+
config_path: "config.json"
|
31 |
+
num_processes: 4
|
32 |
+
device: "cuda"
|
33 |
+
|
34 |
+
train_ms:
|
35 |
+
env:
|
36 |
+
MASTER_ADDR: "localhost"
|
37 |
+
MASTER_PORT: 10086
|
38 |
+
WORLD_SIZE: 1
|
39 |
+
LOCAL_RANK: 0
|
40 |
+
RANK: 0
|
41 |
+
model_dir: "models" # The directory to save the model (for training), relative to `{dataset_root}/{model_name}`.
|
42 |
+
config_path: "config.json"
|
43 |
+
num_workers: 16
|
44 |
+
spec_cache: True
|
45 |
+
keep_ckpts: 1 # Set this to 0 to keep all checkpoints
|
46 |
+
|
47 |
+
webui: # For `webui.py`, which is not supported yet in Style-Bert-VITS2.
|
48 |
+
# 推理设备
|
49 |
+
device: "cuda"
|
50 |
+
# 模型路径
|
51 |
+
model: "models/G_8000.pth"
|
52 |
+
# 配置文件路径
|
53 |
+
config_path: "config.json"
|
54 |
+
# 端口号
|
55 |
+
port: 7860
|
56 |
+
# 是否公开部署,对外网开放
|
57 |
+
share: false
|
58 |
+
# 是否开启debug模式
|
59 |
+
debug: false
|
60 |
+
# 语种识别库,可选langid, fastlid
|
61 |
+
language_identification_library: "langid"
|
62 |
+
|
63 |
+
# server_fastapi's config
|
64 |
+
server:
|
65 |
+
port: 5000
|
66 |
+
device: "cuda"
|
67 |
+
language: "JP"
|
68 |
+
limit: 100
|
69 |
+
origins:
|
70 |
+
- "*"
|