diff --git a/README.md b/README.md index 1678e9e04..b4d505bd9 100644 --- a/README.md +++ b/README.md @@ -989,6 +989,7 @@ You are warmly welcome to submit questions in [discussions](https://github.com/P - Many thanks to [heyudage](https://github.com/heyudage)/[VoiceTyping](https://github.com/heyudage/VoiceTyping) for the real-time voice typing tool implementation of PaddleSpeech ASR streaming services. - Many thanks to [EscaticZheng](https://github.com/EscaticZheng)/[ps3.9wheel-install](https://github.com/EscaticZheng/ps3.9wheel-install) for the python3.9 prebuilt wheel for PaddleSpeech installation in Windows without Viusal Studio. Besides, PaddleSpeech depends on a lot of open source repositories. See [references](./docs/source/reference.md) for more information. +- Many thanks to [chinobing](https://github.com/chinobing)/[FastAPI-PaddleSpeech-Audio-To-Text](https://github.com/chinobing/FastAPI-PaddleSpeech-Audio-To-Text) for converting audio to text based on FastAPI and PaddleSpeech. ## License diff --git a/README_cn.md b/README_cn.md index 572f9dee6..bdb2062da 100644 --- a/README_cn.md +++ b/README_cn.md @@ -992,6 +992,7 @@ PaddleSpeech 的 **语音合成** 主要包含三个模块:文本前端、声 - 非常感谢 [chenkui164](https://github.com/chenkui164)/[FastASR](https://github.com/chenkui164/FastASR) 对 PaddleSpeech 的 ASR 进行 C++ 推理实现。 - 非常感谢 [heyudage](https://github.com/heyudage)/[VoiceTyping](https://github.com/heyudage/VoiceTyping) 基于 PaddleSpeech 的 ASR 流式服务实现的实时语音输入法工具。 - 非常感谢 [EscaticZheng](https://github.com/EscaticZheng)/[ps3.9wheel-install](https://github.com/EscaticZheng/ps3.9wheel-install) 对PaddleSpeech在Windows下的安装提供了无需Visua Studio,基于python3.9的预编译依赖安装包。 +- 非常感谢 [chinobing](https://github.com/chinobing)/[FastAPI-PaddleSpeech-Audio-To-Text](https://github.com/chinobing/FastAPI-PaddleSpeech-Audio-To-Text) 利用 FastAPI 实现 PaddleSpeech 语音转文字,文件上传、分割、转换进度显示、后台更新任务并以 csv 格式输出。 此外,PaddleSpeech 依赖于许多开源存储库。有关更多信息,请参阅 [references](./docs/source/reference.md)。 diff --git a/examples/canton/tts3/README.md b/examples/canton/tts3/README.md new file mode 100644 index 000000000..3bf4fd8ee --- /dev/null +++ b/examples/canton/tts3/README.md @@ -0,0 +1,77 @@ +# FastSpeech2 with Cantonese language + +## Dataset +### Download and Extract +If you don't have the Cantonese datasets mentioned above, please download and unzip [Guangzhou_Cantonese_Scripted_Speech_Corpus_Daily_Use_Sentence](https://magichub.com/datasets/guangzhou-cantonese-scripted-speech-corpus-daily-use-sentence/) and [Guangzhou_Cantonese_Scripted_Speech_Corpus_in_Vehicle](https://magichub.com/datasets/guangzhou-cantonese-scripted-speech-corpus-in-the-vehicle/) under `~/datasets/`. + +To obtain better performance, please combine these two datasets together as follows: + +```bash +mkdir -p ~/datasets/canton_all/WAV +cp -r ~/datasets/Guangzhou_Cantonese_Scripted_Speech_Corpus_Daily_Use_Sentence/WAV/* ~/datasets/canton_all/WAV +cp -r ~/datasets/Guangzhou_Cantonese_Scripted_Speech_Corpus_in_Vehicle/WAV/* ~/datasets/canton_all/WAV +``` + +After that, it should be look like: +``` +~/datasets/canton_all +│ └── WAV +│ └──G0001 +│ └──G0002 +│ ... +│ └──G0071 +│ └──G0072 +``` + + +### Get MFA Result and Extract +We use [MFA1.x](https://github.com/MontrealCorpusTools/Montreal-Forced-Aligner) to get durations for canton_fastspeech2. +You can train your MFA model reference to [canton_mfa example](https://github.com/PaddlePaddle/PaddleSpeech/tree/develop/examples/other/mfa) (use MFA1.x now) of our repo. +We here provide the MFA results of these two datasets. [canton_alignment.zip](https://paddlespeech.bj.bcebos.com/MFA/Canton/canton_alignment.zip) + +## Get Started +Assume the path to the Cantonese MFA result of the two datsets mentioned above is `./canton_alignment`. +Run the command below to +1. **source path**. +2. preprocess the dataset. +3. train the model. +4. synthesize wavs. + - synthesize waveform from `metadata.jsonl`. + - synthesize waveform from text file. +```bash +./run.sh +``` +You can choose a range of stages you want to run, or set `stage` equal to `stop-stage` to use only one stage, for example, running the following command will only preprocess the dataset. +```bash +./run.sh --stage 0 --stop-stage 0 +``` + +### Data Preprocessing +```bash +./local/preprocess.sh ${conf_path} +``` +When it is done. A `dump` folder is created in the current directory. The structure of the dump folder is listed below. +```text +dump +├── dev +│ ├── norm +│ └── raw +├── phone_id_map.txt +├── speaker_id_map.txt +├── test +│ ├── norm +│ └── raw +└── train + ├── energy_stats.npy + ├── norm + ├── pitch_stats.npy + ├── raw + └── speech_stats.npy +``` +The dataset is split into 3 parts, namely `train`, `dev`, and` test`, each of which contains a `norm` and `raw` subfolder. The raw folder contains speech、pitch and energy features of each utterance, while the norm folder contains normalized ones. The statistics used to normalize features are computed from the training set, which is located in `dump/train/*_stats.npy`. + +Also, there is a `metadata.jsonl` in each subfolder. It is a table-like file that contains phones, text_lengths, speech_lengths, durations, the path of speech features, the path of pitch features, a path of energy features, speaker, and id of each utterance. + +### Training details can refer to the script of [examples/aishell3/tts3](../../aishell3/tts3). + +## Pretrained Model diff --git a/examples/canton/tts3/conf/default.yaml b/examples/canton/tts3/conf/default.yaml new file mode 100644 index 000000000..a101e6eea --- /dev/null +++ b/examples/canton/tts3/conf/default.yaml @@ -0,0 +1,107 @@ +########################################################### +# FEATURE EXTRACTION SETTING # +########################################################### + +fs: 24000 # sr +n_fft: 2048 # FFT size (samples). +n_shift: 300 # Hop size (samples). 12.5ms +win_length: 1200 # Window length (samples). 50ms + # If set to null, it will be the same as fft_size. +window: "hann" # Window function. + +# Only used for feats_type != raw + +fmin: 80 # Minimum frequency of Mel basis. +fmax: 7600 # Maximum frequency of Mel basis. +n_mels: 80 # The number of mel basis. + +# Only used for the model using pitch features (e.g. FastSpeech2) +# The canton datasets we use are different from others like Databaker or LJSpeech, +# we set it to 110 to avoid too many zero-pitch problem. +# Reference: https://github.com/JeremyCCHsu/Python-Wrapper-for-World-Vocoder/issues/38 +f0min: 110 # Minimum f0 for pitch extraction. +f0max: 400 # Maximum f0 for pitch extraction. + + +########################################################### +# DATA SETTING # +########################################################### +batch_size: 32 +num_workers: 2 + + +########################################################### +# MODEL SETTING # +########################################################### +model: + adim: 384 # attention dimension + aheads: 2 # number of attention heads + elayers: 4 # number of encoder layers + eunits: 1536 # number of encoder ff units + dlayers: 4 # number of decoder layers + dunits: 1536 # number of decoder ff units + positionwise_layer_type: conv1d # type of position-wise layer + positionwise_conv_kernel_size: 3 # kernel size of position wise conv layer + duration_predictor_layers: 2 # number of layers of duration predictor + duration_predictor_chans: 256 # number of channels of duration predictor + duration_predictor_kernel_size: 3 # filter size of duration predictor + postnet_layers: 5 # number of layers of postnset + postnet_filts: 5 # filter size of conv layers in postnet + postnet_chans: 256 # number of channels of conv layers in postnet + use_scaled_pos_enc: True # whether to use scaled positional encoding + encoder_normalize_before: True # whether to perform layer normalization before the input + decoder_normalize_before: True # whether to perform layer normalization before the input + reduction_factor: 1 # reduction factor + init_type: xavier_uniform # initialization type + init_enc_alpha: 1.0 # initial value of alpha of encoder scaled position encoding + init_dec_alpha: 1.0 # initial value of alpha of decoder scaled position encoding + transformer_enc_dropout_rate: 0.2 # dropout rate for transformer encoder layer + transformer_enc_positional_dropout_rate: 0.2 # dropout rate for transformer encoder positional encoding + transformer_enc_attn_dropout_rate: 0.2 # dropout rate for transformer encoder attention layer + transformer_dec_dropout_rate: 0.2 # dropout rate for transformer decoder layer + transformer_dec_positional_dropout_rate: 0.2 # dropout rate for transformer decoder positional encoding + transformer_dec_attn_dropout_rate: 0.2 # dropout rate for transformer decoder attention layer + pitch_predictor_layers: 5 # number of conv layers in pitch predictor + pitch_predictor_chans: 256 # number of channels of conv layers in pitch predictor + pitch_predictor_kernel_size: 5 # kernel size of conv leyers in pitch predictor + pitch_predictor_dropout: 0.5 # dropout rate in pitch predictor + pitch_embed_kernel_size: 1 # kernel size of conv embedding layer for pitch + pitch_embed_dropout: 0.0 # dropout rate after conv embedding layer for pitch + stop_gradient_from_pitch_predictor: True # whether to stop the gradient from pitch predictor to encoder + energy_predictor_layers: 2 # number of conv layers in energy predictor + energy_predictor_chans: 256 # number of channels of conv layers in energy predictor + energy_predictor_kernel_size: 3 # kernel size of conv leyers in energy predictor + energy_predictor_dropout: 0.5 # dropout rate in energy predictor + energy_embed_kernel_size: 1 # kernel size of conv embedding layer for energy + energy_embed_dropout: 0.0 # dropout rate after conv embedding layer for energy + stop_gradient_from_energy_predictor: False # whether to stop the gradient from energy predictor to encoder + spk_embed_dim: 256 # speaker embedding dimension + spk_embed_integration_type: concat # speaker embedding integration type + + + +########################################################### +# UPDATER SETTING # +########################################################### +updater: + use_masking: True # whether to apply masking for padded part in loss calculation + + +########################################################### +# OPTIMIZER SETTING # +########################################################### +optimizer: + optim: adam # optimizer type + learning_rate: 0.001 # learning rate + +########################################################### +# TRAINING SETTING # +########################################################### +max_epoch: 1000 +num_snapshots: 5 + + +########################################################### +# OTHER SETTING # +########################################################### +seed: 10086 diff --git a/examples/canton/tts3/local/preprocess.sh b/examples/canton/tts3/local/preprocess.sh new file mode 100755 index 000000000..f70b1c028 --- /dev/null +++ b/examples/canton/tts3/local/preprocess.sh @@ -0,0 +1,75 @@ +#!/bin/bash + +stage=0 +stop_stage=100 + +config_path=$1 + +if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then + # get durations from MFA's result + echo "Generate durations.txt from MFA results ..." + python3 ${MAIN_ROOT}/utils/gen_duration_from_textgrid.py \ + --inputdir=./canton_alignment \ + --output durations.txt \ + --config=${config_path} +fi + +if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then + # extract features + echo "Extract features ..." + python3 ${BIN_DIR}/preprocess.py \ + --dataset=canton \ + --rootdir=~/datasets/canton_all \ + --dumpdir=dump \ + --dur-file=durations.txt \ + --config=${config_path} \ + --num-cpu=20 \ + --cut-sil=True +fi + +if [ ${stage} -le 2 ] && [ ${stop_stage} -ge 2 ]; then + # get features' stats(mean and std) + echo "Get features' stats ..." + python3 ${MAIN_ROOT}/utils/compute_statistics.py \ + --metadata=dump/train/raw/metadata.jsonl \ + --field-name="speech" + + python3 ${MAIN_ROOT}/utils/compute_statistics.py \ + --metadata=dump/train/raw/metadata.jsonl \ + --field-name="pitch" + + python3 ${MAIN_ROOT}/utils/compute_statistics.py \ + --metadata=dump/train/raw/metadata.jsonl \ + --field-name="energy" +fi + +if [ ${stage} -le 3 ] && [ ${stop_stage} -ge 3 ]; then + # normalize and covert phone/speaker to id, dev and test should use train's stats + echo "Normalize ..." + python3 ${BIN_DIR}/normalize.py \ + --metadata=dump/train/raw/metadata.jsonl \ + --dumpdir=dump/train/norm \ + --speech-stats=dump/train/speech_stats.npy \ + --pitch-stats=dump/train/pitch_stats.npy \ + --energy-stats=dump/train/energy_stats.npy \ + --phones-dict=dump/phone_id_map.txt \ + --speaker-dict=dump/speaker_id_map.txt + + python3 ${BIN_DIR}/normalize.py \ + --metadata=dump/dev/raw/metadata.jsonl \ + --dumpdir=dump/dev/norm \ + --speech-stats=dump/train/speech_stats.npy \ + --pitch-stats=dump/train/pitch_stats.npy \ + --energy-stats=dump/train/energy_stats.npy \ + --phones-dict=dump/phone_id_map.txt \ + --speaker-dict=dump/speaker_id_map.txt + + python3 ${BIN_DIR}/normalize.py \ + --metadata=dump/test/raw/metadata.jsonl \ + --dumpdir=dump/test/norm \ + --speech-stats=dump/train/speech_stats.npy \ + --pitch-stats=dump/train/pitch_stats.npy \ + --energy-stats=dump/train/energy_stats.npy \ + --phones-dict=dump/phone_id_map.txt \ + --speaker-dict=dump/speaker_id_map.txt +fi diff --git a/examples/canton/tts3/local/synthesize.sh b/examples/canton/tts3/local/synthesize.sh new file mode 120000 index 000000000..ca9966ed5 --- /dev/null +++ b/examples/canton/tts3/local/synthesize.sh @@ -0,0 +1 @@ +../../../aishell3/tts3/local/synthesize.sh \ No newline at end of file diff --git a/examples/canton/tts3/local/synthesize_e2e.sh b/examples/canton/tts3/local/synthesize_e2e.sh new file mode 100755 index 000000000..509129e3d --- /dev/null +++ b/examples/canton/tts3/local/synthesize_e2e.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +config_path=$1 +train_output_path=$2 +ckpt_name=$3 + +stage=0 +stop_stage=0 + +# pwgan +if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then + FLAGS_allocator_strategy=naive_best_fit \ + FLAGS_fraction_of_gpu_memory_to_use=0.01 \ + python3 ${BIN_DIR}/../synthesize_e2e.py \ + --am=fastspeech2_canton \ + --am_config=${config_path} \ + --am_ckpt=${train_output_path}/checkpoints/${ckpt_name} \ + --am_stat=dump/train/speech_stats.npy \ + --voc=pwgan_aishell3 \ + --voc_config=pwg_aishell3_ckpt_0.5/default.yaml \ + --voc_ckpt=pwg_aishell3_ckpt_0.5/snapshot_iter_1000000.pdz \ + --voc_stat=pwg_aishell3_ckpt_0.5/feats_stats.npy \ + --lang=canton \ + --text=${BIN_DIR}/../sentences_canton.txt \ + --output_dir=${train_output_path}/test_e2e \ + --phones_dict=dump/phone_id_map.txt \ + --speaker_dict=dump/speaker_id_map.txt \ + --spk_id=0 \ + --inference_dir=${train_output_path}/inference +fi + +# hifigan +if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then + echo "in hifigan syn_e2e" + FLAGS_allocator_strategy=naive_best_fit \ + FLAGS_fraction_of_gpu_memory_to_use=0.01 \ + python3 ${BIN_DIR}/../synthesize_e2e.py \ + --am=fastspeech2_canton \ + --am_config=${config_path} \ + --am_ckpt=${train_output_path}/checkpoints/${ckpt_name} \ + --am_stat=dump/train/speech_stats.npy \ + --voc=hifigan_aishell3 \ + --voc_config=hifigan_aishell3_ckpt_0.2.0/default.yaml \ + --voc_ckpt=hifigan_aishell3_ckpt_0.2.0/snapshot_iter_2500000.pdz \ + --voc_stat=hifigan_aishell3_ckpt_0.2.0/feats_stats.npy \ + --lang=canton \ + --text=${BIN_DIR}/../sentences_canton.txt \ + --output_dir=${train_output_path}/test_e2e \ + --phones_dict=dump/phone_id_map.txt \ + --speaker_dict=dump/speaker_id_map.txt \ + --spk_id=0 \ + --inference_dir=${train_output_path}/inference + fi diff --git a/examples/canton/tts3/local/train.sh b/examples/canton/tts3/local/train.sh new file mode 120000 index 000000000..78885a300 --- /dev/null +++ b/examples/canton/tts3/local/train.sh @@ -0,0 +1 @@ +../../../aishell3/tts3/local/train.sh \ No newline at end of file diff --git a/examples/canton/tts3/path.sh b/examples/canton/tts3/path.sh new file mode 120000 index 000000000..4785b9095 --- /dev/null +++ b/examples/canton/tts3/path.sh @@ -0,0 +1 @@ +../../csmsc/tts3/path.sh \ No newline at end of file diff --git a/examples/canton/tts3/run.sh b/examples/canton/tts3/run.sh new file mode 100755 index 000000000..0a34e5238 --- /dev/null +++ b/examples/canton/tts3/run.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +set -e +source path.sh + +gpus=0 +stage=0 +stop_stage=100 + +conf_path=conf/default.yaml +train_output_path=exp/default + +ckpt_name=snapshot_iter_280000.pdz + +# with the following command, you can choose the stage range you want to run +# such as `./run.sh --stage 0 --stop-stage 0` +# this can not be mixed use with `$1`, `$2` ... +source ${MAIN_ROOT}/utils/parse_options.sh || exit 1 + +if [ ${stage} -le 0 ] && [ ${stop_stage} -ge 0 ]; then + # prepare data + ./local/preprocess.sh ${conf_path} || exit -1 +fi + +if [ ${stage} -le 1 ] && [ ${stop_stage} -ge 1 ]; then + # train model, all `ckpt` under `train_output_path/checkpoints/` dir + CUDA_VISIBLE_DEVICES=${gpus} ./local/train.sh ${conf_path} ${train_output_path} || exit -1 +fi + +if [ ${stage} -le 2 ] && [ ${stop_stage} -ge 2 ]; then + # synthesize, vocoder is pwgan by default + CUDA_VISIBLE_DEVICES=${gpus} ./local/synthesize.sh ${conf_path} ${train_output_path} ${ckpt_name} || exit -1 +fi + +if [ ${stage} -le 3 ] && [ ${stop_stage} -ge 3 ]; then + # synthesize_e2e, vocoder is pwgan by default + CUDA_VISIBLE_DEVICES=${gpus} ./local/synthesize_e2e.sh ${conf_path} ${train_output_path} ${ckpt_name} || exit -1 +fi diff --git a/paddlespeech/s2t/exps/wav2vec2/model.py b/paddlespeech/s2t/exps/wav2vec2/model.py index 878c0d84b..86b56b876 100644 --- a/paddlespeech/s2t/exps/wav2vec2/model.py +++ b/paddlespeech/s2t/exps/wav2vec2/model.py @@ -23,9 +23,9 @@ from contextlib import nullcontext import jsonlines import numpy as np import paddle -import transformers from hyperpyyaml import load_hyperpyyaml from paddle import distributed as dist +from paddlenlp.transformers import AutoTokenizer from paddlespeech.s2t.frontend.featurizer import TextFeaturizer from paddlespeech.s2t.io.dataloader import DataLoaderFactory @@ -530,8 +530,7 @@ class Wav2Vec2ASRTrainer(Trainer): datasets = [train_data, valid_data, test_data] # Defining tokenizer and loading it - tokenizer = transformers.BertTokenizer.from_pretrained( - 'bert-base-chinese') + tokenizer = AutoTokenizer.from_pretrained('bert-base-chinese') self.tokenizer = tokenizer # 2. Define audio pipeline: @data_pipeline.takes("wav") @@ -867,8 +866,7 @@ class Wav2Vec2ASRTester(Wav2Vec2ASRTrainer): vocab_list = self.vocab_list decode_batch_size = decode_cfg.decode_batch_size - with jsonlines.open( - self.args.result_file, 'w', encoding='utf8') as fout: + with jsonlines.open(self.args.result_file, 'w') as fout: for i, batch in enumerate(self.test_loader): if self.use_sb: metrics = self.sb_compute_metrics(**batch, fout=fout) diff --git a/paddlespeech/s2t/io/dataloader.py b/paddlespeech/s2t/io/dataloader.py index 5ba891c39..db6292f2c 100644 --- a/paddlespeech/s2t/io/dataloader.py +++ b/paddlespeech/s2t/io/dataloader.py @@ -464,5 +464,5 @@ class DataLoaderFactory(): subsampling_factor=config.subsampling_factor, load_aux_output=config.get('load_transcript', None), num_encs=config.num_encs, - dist_sampler=config.dist_sampler, + dist_sampler=config.get('dist_sampler', None), shortest_first=config.shortest_first) diff --git a/paddlespeech/s2t/models/wav2vec2/wav2vec2_ASR.py b/paddlespeech/s2t/models/wav2vec2/wav2vec2_ASR.py index f91a41c32..baa7392eb 100755 --- a/paddlespeech/s2t/models/wav2vec2/wav2vec2_ASR.py +++ b/paddlespeech/s2t/models/wav2vec2/wav2vec2_ASR.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from collections import defaultdict +from turtle import Turtle from typing import Dict from typing import List from typing import Tuple @@ -83,6 +84,7 @@ class Wav2vec2ASR(nn.Layer): text_feature: Dict[str, int], decoding_method: str, beam_size: int, + tokenizer: str=None, sb_pipeline=False): batch_size = feats.shape[0] @@ -93,12 +95,15 @@ class Wav2vec2ASR(nn.Layer): logger.error(f"current batch_size is {batch_size}") if decoding_method == 'ctc_greedy_search': - if not sb_pipeline: + if tokenizer is None and sb_pipeline is False: hyps = self.ctc_greedy_search(feats) res = [text_feature.defeaturize(hyp) for hyp in hyps] res_tokenids = [hyp for hyp in hyps] else: - hyps = self.ctc_greedy_search(feats.unsqueeze(-1)) + if sb_pipeline is True: + hyps = self.ctc_greedy_search(feats.unsqueeze(-1)) + else: + hyps = self.ctc_greedy_search(feats) res = [] res_tokenids = [] for sequence in hyps: @@ -123,13 +128,16 @@ class Wav2vec2ASR(nn.Layer): # with other batch decoding mode elif decoding_method == 'ctc_prefix_beam_search': assert feats.shape[0] == 1 - if not sb_pipeline: + if tokenizer is None and sb_pipeline is False: hyp = self.ctc_prefix_beam_search(feats, beam_size) res = [text_feature.defeaturize(hyp)] res_tokenids = [hyp] else: - hyp = self.ctc_prefix_beam_search( - feats.unsqueeze(-1), beam_size) + if sb_pipeline is True: + hyp = self.ctc_prefix_beam_search( + feats.unsqueeze(-1), beam_size) + else: + hyp = self.ctc_prefix_beam_search(feats, beam_size) res = [] res_tokenids = [] predicted_tokens = text_feature.convert_ids_to_tokens(hyp) diff --git a/paddlespeech/t2s/datasets/get_feats.py b/paddlespeech/t2s/datasets/get_feats.py index 21458f152..a90f1a417 100644 --- a/paddlespeech/t2s/datasets/get_feats.py +++ b/paddlespeech/t2s/datasets/get_feats.py @@ -102,7 +102,7 @@ class Pitch(): def _convert_to_continuous_f0(self, f0: np.ndarray) -> np.ndarray: if (f0 == 0).all(): - print("All frames seems to be unvoiced.") + print("All frames seems to be unvoiced, this utt will be removed.") return f0 # padding start and end of f0 sequence diff --git a/paddlespeech/t2s/exps/fastspeech2/preprocess.py b/paddlespeech/t2s/exps/fastspeech2/preprocess.py index f4acdc60b..521b9a880 100644 --- a/paddlespeech/t2s/exps/fastspeech2/preprocess.py +++ b/paddlespeech/t2s/exps/fastspeech2/preprocess.py @@ -54,8 +54,15 @@ def process_sentence(config: Dict[str, Any], record = None if utt_id in sentences: # reading, resampling may occur - wav, _ = librosa.load(str(fp), sr=config.fs) - if len(wav.shape) != 1: + wav, _ = librosa.load( + str(fp), sr=config.fs, + mono=False) if "canton" in str(fp) else librosa.load( + str(fp), sr=config.fs) + if len(wav.shape) == 2 and "canton" in str(fp): + # Remind that Cantonese datasets should be placed in ~/datasets/canton_all. Otherwise, it may cause problem. + wav = wav[0] + wav = np.ascontiguousarray(wav) + elif len(wav.shape) != 1: return record max_value = np.abs(wav).max() if max_value > 1.0: @@ -102,6 +109,8 @@ def process_sentence(config: Dict[str, Any], np.save(mel_path, logmel) # extract pitch and energy f0 = pitch_extractor.get_pitch(wav, duration=np.array(durations)) + if (f0 == 0).all(): + return None assert f0.shape[0] == len(durations) f0_dir = output_dir / "data_pitch" f0_dir.mkdir(parents=True, exist_ok=True) @@ -282,7 +291,20 @@ def main(): test_wav_files += wav_files[-sub_num_dev:] else: train_wav_files += wav_files - + elif args.dataset == "canton": + sub_num_dev = 5 + wav_dir = rootdir / "WAV" + train_wav_files = [] + dev_wav_files = [] + test_wav_files = [] + for speaker in os.listdir(wav_dir): + wav_files = sorted(list((wav_dir / speaker).rglob("*.wav"))) + if len(wav_files) > 100: + train_wav_files += wav_files[:-sub_num_dev * 2] + dev_wav_files += wav_files[-sub_num_dev * 2:-sub_num_dev] + test_wav_files += wav_files[-sub_num_dev:] + else: + train_wav_files += wav_files elif args.dataset == "ljspeech": wav_files = sorted(list((rootdir / "wavs").rglob("*.wav"))) # split data into 3 sections diff --git a/paddlespeech/t2s/exps/sentences_canton.txt b/paddlespeech/t2s/exps/sentences_canton.txt new file mode 100644 index 000000000..dcc6019b9 --- /dev/null +++ b/paddlespeech/t2s/exps/sentences_canton.txt @@ -0,0 +1,7 @@ +001 白云山爬过一次嘅,好远啊,爬上去都成两个钟 +002 睇书咯,番屋企,而家好多人好少睇书噶喎 +003 因为如果唔考试嘅话,工资好低噶 +004 冇固定噶,你中意休边日就边日噶 +005 即系太迟嘅话咧,落班太迟嘅话就喺出边食啲咯 +006 是非有公理,慎言莫冒犯别人 +007 遇上冷风雨,休太认真 diff --git a/paddlespeech/t2s/exps/syn_utils.py b/paddlespeech/t2s/exps/syn_utils.py index 491edda30..dd3b4d553 100644 --- a/paddlespeech/t2s/exps/syn_utils.py +++ b/paddlespeech/t2s/exps/syn_utils.py @@ -33,6 +33,7 @@ from paddlespeech.t2s.datasets.am_batch_fn import * from paddlespeech.t2s.datasets.data_table import DataTable from paddlespeech.t2s.datasets.vocoder_batch_fn import Clip_static from paddlespeech.t2s.frontend import English +from paddlespeech.t2s.frontend.canton_frontend import CantonFrontend from paddlespeech.t2s.frontend.mix_frontend import MixFrontend from paddlespeech.t2s.frontend.zh_frontend import Frontend from paddlespeech.t2s.modules.normalizer import ZScore @@ -111,7 +112,7 @@ def get_sentences(text_file: Optional[os.PathLike], lang: str='zh'): if line.strip() != "": items = re.split(r"\s+", line.strip(), 1) utt_id = items[0] - if lang == 'zh': + if lang in {'zh', 'canton'}: sentence = "".join(items[1:]) elif lang == 'en': sentence = " ".join(items[1:]) @@ -132,8 +133,8 @@ def get_test_dataset(test_metadata: List[Dict[str, Any]], converters = {} if am_name == 'fastspeech2': fields = ["utt_id", "text"] - if am_dataset in {"aishell3", "vctk", - "mix"} and speaker_dict is not None: + if am_dataset in {"aishell3", "vctk", "mix", + "canton"} and speaker_dict is not None: print("multiple speaker fastspeech2!") fields += ["spk_id"] elif voice_cloning: @@ -177,8 +178,8 @@ def get_dev_dataloader(dev_metadata: List[Dict[str, Any]], converters = {} if am_name == 'fastspeech2': fields = ["utt_id", "text"] - if am_dataset in {"aishell3", "vctk", - "mix"} and speaker_dict is not None: + if am_dataset in {"aishell3", "vctk", "mix", + "canton"} and speaker_dict is not None: print("multiple speaker fastspeech2!") collate_fn = fastspeech2_multi_spk_batch_fn_static fields += ["spk_id"] @@ -266,6 +267,8 @@ def get_frontend(lang: str='zh', phone_vocab_path=phones_dict, tone_vocab_path=tones_dict, use_rhy=use_rhy) + elif lang == 'canton': + frontend = CantonFrontend(phone_vocab_path=phones_dict) elif lang == 'en': frontend = English(phone_vocab_path=phones_dict) elif lang == 'mix': @@ -302,6 +305,10 @@ def run_frontend(frontend: object, if get_tone_ids: tone_ids = input_ids["tone_ids"] outs.update({'tone_ids': tone_ids}) + elif lang == 'canton': + input_ids = frontend.get_input_ids( + text, merge_sentences=merge_sentences, to_tensor=to_tensor) + phone_ids = input_ids["phone_ids"] elif lang == 'en': input_ids = frontend.get_input_ids( text, merge_sentences=merge_sentences, to_tensor=to_tensor) @@ -311,7 +318,7 @@ def run_frontend(frontend: object, text, merge_sentences=merge_sentences, to_tensor=to_tensor) phone_ids = input_ids["phone_ids"] else: - print("lang should in {'zh', 'en', 'mix'}!") + print("lang should in {'zh', 'en', 'mix', 'canton'}!") outs.update({'phone_ids': phone_ids}) return outs @@ -411,8 +418,8 @@ def am_to_static(am_inference, am_name = am[:am.rindex('_')] am_dataset = am[am.rindex('_') + 1:] if am_name == 'fastspeech2': - if am_dataset in {"aishell3", "vctk", - "mix"} and speaker_dict is not None: + if am_dataset in {"aishell3", "vctk", "mix", + "canton"} and speaker_dict is not None: am_inference = jit.to_static( am_inference, input_spec=[ @@ -424,8 +431,8 @@ def am_to_static(am_inference, am_inference, input_spec=[InputSpec([-1], dtype=paddle.int64)]) elif am_name == 'speedyspeech': - if am_dataset in {"aishell3", "vctk", - "mix"} and speaker_dict is not None: + if am_dataset in {"aishell3", "vctk", "mix", + "canton"} and speaker_dict is not None: am_inference = jit.to_static( am_inference, input_spec=[ @@ -575,7 +582,7 @@ def get_am_output( get_tone_ids = False if am_name == 'speedyspeech': get_tone_ids = True - if am_dataset in {"aishell3", "vctk", "mix"} and speaker_dict: + if am_dataset in {"aishell3", "vctk", "mix", "canton"} and speaker_dict: get_spk_id = True spk_id = np.array([spk_id]) diff --git a/paddlespeech/t2s/exps/synthesize.py b/paddlespeech/t2s/exps/synthesize.py index a8e18150e..70e52244f 100644 --- a/paddlespeech/t2s/exps/synthesize.py +++ b/paddlespeech/t2s/exps/synthesize.py @@ -136,7 +136,8 @@ def parse_args(): choices=[ 'speedyspeech_csmsc', 'fastspeech2_csmsc', 'fastspeech2_ljspeech', 'fastspeech2_aishell3', 'fastspeech2_vctk', 'tacotron2_csmsc', - 'tacotron2_ljspeech', 'tacotron2_aishell3', 'fastspeech2_mix' + 'tacotron2_ljspeech', 'tacotron2_aishell3', 'fastspeech2_mix', + 'fastspeech2_canton' ], help='Choose acoustic model type of tts task.') parser.add_argument( diff --git a/paddlespeech/t2s/exps/synthesize_e2e.py b/paddlespeech/t2s/exps/synthesize_e2e.py index 625002477..3b87d9e16 100644 --- a/paddlespeech/t2s/exps/synthesize_e2e.py +++ b/paddlespeech/t2s/exps/synthesize_e2e.py @@ -119,7 +119,7 @@ def evaluate(args): # acoustic model if am_name == 'fastspeech2': # multi speaker - if am_dataset in {"aishell3", "vctk", "mix"}: + if am_dataset in {"aishell3", "vctk", "mix", "canton"}: spk_id = paddle.to_tensor(args.spk_id) mel = am_inference(part_phone_ids, spk_id) else: @@ -167,7 +167,8 @@ def parse_args(): choices=[ 'speedyspeech_csmsc', 'speedyspeech_aishell3', 'fastspeech2_csmsc', 'fastspeech2_ljspeech', 'fastspeech2_aishell3', 'fastspeech2_vctk', - 'tacotron2_csmsc', 'tacotron2_ljspeech', 'fastspeech2_mix' + 'tacotron2_csmsc', 'tacotron2_ljspeech', 'fastspeech2_mix', + 'fastspeech2_canton' ], help='Choose acoustic model type of tts task.') parser.add_argument( diff --git a/paddlespeech/t2s/frontend/canton_frontend.py b/paddlespeech/t2s/frontend/canton_frontend.py new file mode 100644 index 000000000..f81526839 --- /dev/null +++ b/paddlespeech/t2s/frontend/canton_frontend.py @@ -0,0 +1,106 @@ +# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Dict +from typing import List + +import numpy as np +import paddle +import ToJyutping + +from paddlespeech.t2s.frontend.zh_normalization.text_normlization import TextNormalizer + +INITIALS = [ + 'p', 'b', 't', 'd', 'ts', 'dz', 'k', 'g', 'kw', 'gw', 'f', 'h', 'l', 'm', + 'ng', 'n', 's', 'y', 'w', 'c', 'z', 'j' +] +INITIALS += ['sp', 'spl', 'spn', 'sil'] + + +def get_lines(cantons: List[str]): + phones = [] + for canton in cantons: + for consonant in INITIALS: + if canton.startswith(consonant): + c, v = canton[:len(consonant)], canton[len(consonant):] + phones = phones + [c, v] + return phones + + +class CantonFrontend(): + def __init__(self, phone_vocab_path: str): + self.text_normalizer = TextNormalizer() + self.punc = ":,;。?!“”‘’':,;.?!" + + self.vocab_phones = {} + if phone_vocab_path: + with open(phone_vocab_path, 'rt', encoding='utf-8') as f: + phn_id = [line.strip().split() for line in f.readlines()] + for phn, id in phn_id: + self.vocab_phones[phn] = int(id) + + # if merge_sentences, merge all sentences into one phone sequence + def _g2p(self, sentences: List[str], + merge_sentences: bool=True) -> List[List[str]]: + phones_list = [] + for sentence in sentences: + phones_str = ToJyutping.get_jyutping_text(sentence) + phones_split = get_lines(phones_str.split(' ')) + phones_list.append(phones_split) + return phones_list + + def _p2id(self, phonemes: List[str]) -> np.ndarray: + # replace unk phone with sp + phonemes = [ + phn if phn in self.vocab_phones else "sp" for phn in phonemes + ] + phone_ids = [self.vocab_phones[item] for item in phonemes] + return np.array(phone_ids, np.int64) + + def get_phonemes(self, + sentence: str, + merge_sentences: bool=True, + print_info: bool=False) -> List[List[str]]: + sentences = self.text_normalizer.normalize(sentence) + phonemes = self._g2p(sentences, merge_sentences=merge_sentences) + if print_info: + print("----------------------------") + print("text norm results:") + print(sentences) + print("----------------------------") + print("g2p results:") + print(phonemes) + print("----------------------------") + return phonemes + + def get_input_ids(self, + sentence: str, + merge_sentences: bool=True, + print_info: bool=False, + to_tensor: bool=True) -> Dict[str, List[paddle.Tensor]]: + + phonemes = self.get_phonemes( + sentence, merge_sentences=merge_sentences, print_info=print_info) + result = {} + temp_phone_ids = [] + + for phones in phonemes: + if phones: + phone_ids = self._p2id(phones) + # if use paddle.to_tensor() in onnxruntime, the first time will be too low + if to_tensor: + phone_ids = paddle.to_tensor(phone_ids) + temp_phone_ids.append(phone_ids) + if temp_phone_ids: + result["phone_ids"] = temp_phone_ids + return result diff --git a/setup.py b/setup.py index 014b0ed91..69739b3b8 100644 --- a/setup.py +++ b/setup.py @@ -69,7 +69,6 @@ base = [ "paddleslim>=2.3.4", "paddleaudio>=1.1.0", "hyperpyyaml", - "transformers", ] server = ["pattern_singleton", "websockets"]