diff --git a/deep_speech_2/README.md b/deep_speech_2/README.md
deleted file mode 100644
index 427331fcc7bde2a277b6d2cd8314c0d8dd9997df..0000000000000000000000000000000000000000
--- a/deep_speech_2/README.md
+++ /dev/null
@@ -1,535 +0,0 @@
-Deprecated: please check out the new repository [DeepSpeech](https://github.com/PaddlePaddle/DeepSpeech).
-
-# DeepSpeech2 on PaddlePaddle
-
-*DeepSpeech2 on PaddlePaddle* is an open-source implementation of end-to-end Automatic Speech Recognition (ASR) engine, based on [Baidu's Deep Speech 2 paper](http://proceedings.mlr.press/v48/amodei16.pdf), with [PaddlePaddle](https://github.com/PaddlePaddle/Paddle) platform. Our vision is to empower both industrial application and academic research on speech recognition, via an easy-to-use, efficient and scalable implementation, including training, inference & testing module, distributed [PaddleCloud](https://github.com/PaddlePaddle/cloud) training, and demo deployment. Besides, several pre-trained models for both English and Mandarin are also released.
-
-## Table of Contents
-- [Installation](#installation)
-- [Getting Started](#getting-started)
-- [Data Preparation](#data-preparation)
-- [Training a Model](#training-a-model)
-- [Data Augmentation Pipeline](#data-augmentation-pipeline)
-- [Inference and Evaluation](#inference-and-evaluation)
-- [Running in Docker Container](#running-in-docker-container)
-- [Distributed Cloud Training](#distributed-cloud-training)
-- [Hyper-parameters Tuning](#hyper-parameters-tuning)
-- [Training for Mandarin Language](#training-for-mandarin-language)
-- [Trying Live Demo with Your Own Voice](#trying-live-demo-with-your-own-voice)
-- [Released Models](#released-models)
-- [Experiments and Benchmarks](#experiments-and-benchmarks)
-- [Questions and Help](#questions-and-help)
-
-
-
-## Installation
-
-To avoid the trouble of environment setup, [running in docker container](#running-in-docker-container) is highly recommended. Otherwise follow the guidelines below to install the dependencies manually.
-
-### Prerequisites
-- Python 2.7 only supported
-- PaddlePaddle the latest version (please refer to the [Installation Guide](https://github.com/PaddlePaddle/Paddle#installation))
-
-### Setup
-
-```bash
-git clone https://github.com/PaddlePaddle/models.git
-cd models/deep_speech_2
-sh setup.sh
-```
-
-## Getting Started
-
-Several shell scripts provided in `./examples` will help us to quickly give it a try, for most major modules, including data preparation, model training, case inference and model evaluation, with a few public dataset (e.g. [LibriSpeech](http://www.openslr.org/12/), [Aishell](http://www.openslr.org/33)). Reading these examples will also help you to understand how to make it work with your own data.
-
-Some of the scripts in `./examples` are configured with 8 GPUs. If you don't have 8 GPUs available, please modify `CUDA_VISIBLE_DEVICES` and `--trainer_count`. If you don't have any GPU available, please set `--use_gpu` to False to use CPUs instead. Besides, if out-of-memory problem occurs, just reduce `--batch_size` to fit.
-
-Let's take a tiny sampled subset of [LibriSpeech dataset](http://www.openslr.org/12/) for instance.
-
-- Go to directory
-
- ```bash
- cd examples/tiny
- ```
-
- Notice that this is only a toy example with a tiny sampled subset of LibriSpeech. If you would like to try with the complete dataset (would take several days for training), please go to `examples/librispeech` instead.
-- Prepare the data
-
- ```bash
- sh run_data.sh
- ```
-
- `run_data.sh` will download dataset, generate manifests, collect normalizer's statistics and build vocabulary. Once the data preparation is done, you will find the data (only part of LibriSpeech) downloaded in `~/.cache/paddle/dataset/speech/libri` and the corresponding manifest files generated in `./data/tiny` as well as a mean stddev file and a vocabulary file. It has to be run for the very first time you run this dataset and is reusable for all further experiments.
-- Train your own ASR model
-
- ```bash
- sh run_train.sh
- ```
-
- `run_train.sh` will start a training job, with training logs printed to stdout and model checkpoint of every pass/epoch saved to `./checkpoints/tiny`. These checkpoints could be used for training resuming, inference, evaluation and deployment.
-- Case inference with an existing model
-
- ```bash
- sh run_infer.sh
- ```
-
- `run_infer.sh` will show us some speech-to-text decoding results for several (default: 10) samples with the trained model. The performance might not be good now as the current model is only trained with a toy subset of LibriSpeech. To see the results with a better model, you can download a well-trained (trained for several days, with the complete LibriSpeech) model and do the inference:
-
- ```bash
- sh run_infer_golden.sh
- ```
-- Evaluate an existing model
-
- ```bash
- sh run_test.sh
- ```
-
- `run_test.sh` will evaluate the model with Word Error Rate (or Character Error Rate) measurement. Similarly, you can also download a well-trained model and test its performance:
-
- ```bash
- sh run_test_golden.sh
- ```
-
-More detailed information are provided in the following sections. Wish you a happy journey with the *DeepSpeech2 on PaddlePaddle* ASR engine!
-
-
-## Data Preparation
-
-### Generate Manifest
-
-*DeepSpeech2 on PaddlePaddle* accepts a textual **manifest** file as its data set interface. A manifest file summarizes a set of speech data, with each line containing some meta data (e.g. filepath, transcription, duration) of one audio clip, in [JSON](http://www.json.org/) format, such as:
-
-```
-{"audio_filepath": "/home/work/.cache/paddle/Libri/134686/1089-134686-0001.flac", "duration": 3.275, "text": "stuff it into you his belly counselled him"}
-{"audio_filepath": "/home/work/.cache/paddle/Libri/134686/1089-134686-0007.flac", "duration": 4.275, "text": "a cold lucid indifference reigned in his soul"}
-```
-
-To use your custom data, you only need to generate such manifest files to summarize the dataset. Given such summarized manifests, training, inference and all other modules can be aware of where to access the audio files, as well as their meta data including the transcription labels.
-
-For how to generate such manifest files, please refer to `data/librispeech/librispeech.py`, which will download data and generate manifest files for LibriSpeech dataset.
-
-### Compute Mean & Stddev for Normalizer
-
-To perform z-score normalization (zero-mean, unit stddev) upon audio features, we have to estimate in advance the mean and standard deviation of the features, with some training samples:
-
-```bash
-python tools/compute_mean_std.py \
---num_samples 2000 \
---specgram_type linear \
---manifest_paths data/librispeech/manifest.train \
---output_path data/librispeech/mean_std.npz
-```
-
-It will compute the mean and standard deviation of power spectrum feature with 2000 random sampled audio clips listed in `data/librispeech/manifest.train` and save the results to `data/librispeech/mean_std.npz` for further usage.
-
-
-### Build Vocabulary
-
-A vocabulary of possible characters is required to convert the transcription into a list of token indices for training, and in decoding, to convert from a list of indices back to text again. Such a character-based vocabulary can be built with `tools/build_vocab.py`.
-
-```bash
-python tools/build_vocab.py \
---count_threshold 0 \
---vocab_path data/librispeech/eng_vocab.txt \
---manifest_paths data/librispeech/manifest.train
-```
-
-It will write a vocabuary file `data/librispeeech/eng_vocab.txt` with all transcription text in `data/librispeech/manifest.train`, without vocabulary truncation (`--count_threshold 0`).
-
-### More Help
-
-For more help on arguments:
-
-```bash
-python data/librispeech/librispeech.py --help
-python tools/compute_mean_std.py --help
-python tools/build_vocab.py --help
-```
-
-## Training a model
-
-`train.py` is the main caller of the training module. Examples of usage are shown below.
-
-- Start training from scratch with 8 GPUs:
-
- ```
- CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python train.py --trainer_count 8
- ```
-
-- Start training from scratch with 16 CPUs:
-
- ```
- python train.py --use_gpu False --trainer_count 16
- ```
-- Resume training from a checkpoint:
-
- ```
- CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
- python train.py \
- --init_model_path CHECKPOINT_PATH_TO_RESUME_FROM
- ```
-
-For more help on arguments:
-
-```bash
-python train.py --help
-```
-or refer to `example/librispeech/run_train.sh`.
-
-## Data Augmentation Pipeline
-
-Data augmentation has often been a highly effective technique to boost the deep learning performance. We augment our speech data by synthesizing new audios with small random perturbation (label-invariant transformation) added upon raw audios. You don't have to do the syntheses on your own, as it is already embedded into the data provider and is done on the fly, randomly for each epoch during training.
-
-Six optional augmentation components are provided to be selected, configured and inserted into the processing pipeline.
-
- - Volume Perturbation
- - Speed Perturbation
- - Shifting Perturbation
- - Online Bayesian normalization
- - Noise Perturbation (need background noise audio files)
- - Impulse Response (need impulse audio files)
-
-In order to inform the trainer of what augmentation components are needed and what their processing orders are, it is required to prepare in advance an *augmentation configuration file* in [JSON](http://www.json.org/) format. For example:
-
-```
-[{
- "type": "speed",
- "params": {"min_speed_rate": 0.95,
- "max_speed_rate": 1.05},
- "prob": 0.6
-},
-{
- "type": "shift",
- "params": {"min_shift_ms": -5,
- "max_shift_ms": 5},
- "prob": 0.8
-}]
-```
-
-When the `--augment_conf_file` argument of `trainer.py` is set to the path of the above example configuration file, every audio clip in every epoch will be processed: with 60% of chance, it will first be speed perturbed with a uniformly random sampled speed-rate between 0.95 and 1.05, and then with 80% of chance it will be shifted in time with a random sampled offset between -5 ms and 5 ms. Finally this newly synthesized audio clip will be feed into the feature extractor for further training.
-
-For other configuration examples, please refer to `conf/augmenatation.config.example`.
-
-Be careful when utilizing the data augmentation technique, as improper augmentation will do harm to the training, due to the enlarged train-test gap.
-
-## Inference and Evaluation
-
-### Prepare Language Model
-
-A language model is required to improve the decoder's performance. We have prepared two language models (with lossy compression) for users to download and try. One is for English and the other is for Mandarin. Users can simply run this to download the preprared language models:
-
-```bash
-cd models/lm
-sh download_lm_en.sh
-sh download_lm_ch.sh
-```
-
-If you wish to train your own better language model, please refer to [KenLM](https://github.com/kpu/kenlm) for tutorials. Here we provide some tips to show how we preparing our English and Mandarin language models. You can take it as a reference when you train your own.
-
-#### English LM
-
-The English corpus is from the [Common Crawl Repository](http://commoncrawl.org) and you can download it from [statmt](http://data.statmt.org/ngrams/deduped_en). We use part en.00 to train our English language model. There are some preprocessing steps before training:
-
- * Characters not in \[A-Za-z0-9\s'\] (\s represents whitespace characters) are removed and Arabic numbers are converted to English numbers like 1000 to one thousand.
- * Repeated whitespace characters are squeezed to one and the beginning whitespace characters are removed. Notice that all transcriptions are lowercase, so all characters are converted to lowercase.
- * Top 400,000 most frequent words are selected to build the vocabulary and the rest are replaced with 'UNKNOWNWORD'.
-
-Now the preprocessing is done and we get a clean corpus to train the language model. Our released language model are trained with agruments '-o 5 --prune 0 1 1 1 1'. '-o 5' means the max order of language model is 5. '--prune 0 1 1 1 1' represents count thresholds for each order and more specifically it will prune singletons for orders two and higher. To save disk storage we convert the arpa file to 'trie' binary file with arguments '-a 22 -q 8 -b 8'. '-a' represents the maximum number of leading bits of pointers in 'trie' to chop. '-q -b' are quantization parameters for probability and backoff.
-
-#### Mandarin LM
-
-Different from the English language model, Mandarin language model is character-based where each token is a Chinese character. We use internal corpus to train the released Mandarin language models. The corpus contain billions of tokens. The preprocessing has tiny difference from English language model and main steps include:
-
- * The beginning and trailing whitespace characters are removed.
- * English punctuations and Chinese punctuations are removed.
- * A whitespace character between two tokens is inserted.
-
-Please notice that the released language models only contain Chinese simplified characters. After preprocessing done we can begin to train the language model. The key training arguments for small LM is '-o 5 --prune 0 1 2 4 4' and '-o 5' for large LM. Please refer above section for the meaning of each argument. We also convert the arpa file to binary file using default settings.
-
-### Speech-to-text Inference
-
-An inference module caller `infer.py` is provided to infer, decode and visualize speech-to-text results for several given audio clips. It might help to have an intuitive and qualitative evaluation of the ASR model's performance.
-
-- Inference with GPU:
-
- ```bash
- CUDA_VISIBLE_DEVICES=0 python infer.py --trainer_count 1
- ```
-
-- Inference with CPUs:
-
- ```bash
- python infer.py --use_gpu False --trainer_count 12
- ```
-
-We provide two types of CTC decoders: *CTC greedy decoder* and *CTC beam search decoder*. The *CTC greedy decoder* is an implementation of the simple best-path decoding algorithm, selecting at each timestep the most likely token, thus being greedy and locally optimal. The [*CTC beam search decoder*](https://arxiv.org/abs/1408.2873) otherwise utilizes a heuristic breadth-first graph search for reaching a near global optimality; it also requires a pre-trained KenLM language model for better scoring and ranking. The decoder type can be set with argument `--decoding_method`.
-
-For more help on arguments:
-
-```
-python infer.py --help
-```
-or refer to `example/librispeech/run_infer.sh`.
-
-### Evaluate a Model
-
-To evaluate a model's performance quantitatively, please run:
-
-- Evaluation with GPUs:
-
- ```bash
- CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python test.py --trainer_count 8
- ```
-
-- Evaluation with CPUs:
-
- ```bash
- python test.py --use_gpu False --trainer_count 12
- ```
-
-The error rate (default: word error rate; can be set with `--error_rate_type`) will be printed.
-
-For more help on arguments:
-
-```bash
-python test.py --help
-```
-or refer to `example/librispeech/run_test.sh`.
-
-## Hyper-parameters Tuning
-
-The hyper-parameters $\alpha$ (language model weight) and $\beta$ (word insertion weight) for the [*CTC beam search decoder*](https://arxiv.org/abs/1408.2873) often have a significant impact on the decoder's performance. It would be better to re-tune them on the validation set when the acoustic model is renewed.
-
-`tools/tune.py` performs a 2-D grid search over the hyper-parameter $\alpha$ and $\beta$. You must provide the range of $\alpha$ and $\beta$, as well as the number of their attempts.
-
-- Tuning with GPU:
-
- ```bash
- CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
- python tools/tune.py \
- --trainer_count 8 \
- --alpha_from 1.0 \
- --alpha_to 3.2 \
- --num_alphas 45 \
- --beta_from 0.1 \
- --beta_to 0.45 \
- --num_betas 8
- ```
-
-- Tuning with CPU:
-
- ```bash
- python tools/tune.py --use_gpu False
- ```
- The grid search will print the WER (word error rate) or CER (character error rate) at each point in the hyper-parameters space, and draw the error surface optionally. A proper hyper-parameters range should include the global minima of the error surface for WER/CER, as illustrated in the following figure.
-
-
-
-
An example error surface for tuning on the dev-clean set of LibriSpeech
-
-
-Usually, as the figure shows, the variation of language model weight ($\alpha$) significantly affect the performance of CTC beam search decoder. And a better procedure is to first tune on serveral data batches (the number can be specified) to find out the proper range of hyper-parameters, then change to the whole validation set to carray out an accurate tuning.
-
-After tuning, you can reset $\alpha$ and $\beta$ in the inference and evaluation modules to see if they really help improve the ASR performance. For more help
-
-```bash
-python tune.py --help
-```
-or refer to `example/librispeech/run_tune.sh`.
-
-## Running in Docker Container
-
-Docker is an open source tool to build, ship, and run distributed applications in an isolated environment. A Docker image for this project has been provided in [hub.docker.com](https://hub.docker.com) with all the dependencies installed, including the pre-built PaddlePaddle, CTC decoders, and other necessary Python and third-party packages. This Docker image requires the support of NVIDIA GPU, so please make sure its availiability and the [nvidia-docker](https://github.com/NVIDIA/nvidia-docker) has been installed.
-
-Take several steps to launch the Docker image:
-
-- Download the Docker image
-
-```bash
-nvidia-docker pull paddlepaddle/models:deep-speech-2
-```
-
-- Clone this repository
-
-```
-git clone https://github.com/PaddlePaddle/models.git
-```
-
-- Run the Docker image
-
-```bash
-sudo nvidia-docker run -it -v $(pwd)/models:/models paddlepaddle/models:deep-speech-2 /bin/bash
-```
-Now go back and start from the [Getting Started](#getting-started) section, you can execute training, inference and hyper-parameters tuning similarly in the Docker container.
-
-## Distributed Cloud Training
-
-We also provide a cloud training module for users to do the distributed cluster training on [PaddleCloud](https://github.com/PaddlePaddle/cloud), to achieve a much faster training speed with multiple machines. To start with this, please first install PaddleCloud client and register a PaddleCloud account, as described in [PaddleCloud Usage](https://github.com/PaddlePaddle/cloud/blob/develop/doc/usage_cn.md#%E4%B8%8B%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AEpaddlecloud).
-
-Please take the following steps to submit a training job:
-
-- Go to directory:
-
- ```bash
- cd cloud
- ```
-- Upload data:
-
- Data must be uploaded to PaddleCloud filesystem to be accessed within a cloud job. `pcloud_upload_data.sh` helps do the data packing and uploading:
-
- ```bash
- sh pcloud_upload_data.sh
- ```
-
- Given input manifests, `pcloud_upload_data.sh` will:
-
- - Extract the audio files listed in the input manifests.
- - Pack them into a specified number of tar files.
- - Upload these tar files to PaddleCloud filesystem.
- - Create cloud manifests by replacing local filesystem paths with PaddleCloud filesystem paths. New manifests will be used to inform the cloud jobs of audio files' location and their meta information.
-
- It should be done only once for the very first time to do the cloud training. Later, the data is kept persisitent on the cloud filesystem and reusable for further job submissions.
-
- For argument details please refer to [Train DeepSpeech2 on PaddleCloud](https://github.com/PaddlePaddle/models/tree/develop/deep_speech_2/cloud).
-
- - Configure training arguments:
-
- Configure the cloud job parameters in `pcloud_submit.sh` (e.g. `NUM_NODES`, `NUM_GPUS`, `CLOUD_TRAIN_DIR`, `JOB_NAME` etc.) and then configure other hyper-parameters for training in `pcloud_train.sh` (just as what you do for local training).
-
- For argument details please refer to [Train DeepSpeech2 on PaddleCloud](https://github.com/PaddlePaddle/models/tree/develop/deep_speech_2/cloud).
-
- - Submit the job:
-
- By running:
-
- ```bash
- sh pcloud_submit.sh
- ```
- a training job has been submitted to PaddleCloud, with the job name printed to the console.
-
- - Get training logs
-
- Run this to list all the jobs you have submitted, as well as their running status:
-
- ```bash
- paddlecloud get jobs
- ```
-
- Run this, the corresponding job's logs will be printed.
- ```bash
- paddlecloud logs -n 10000 $REPLACED_WITH_YOUR_ACTUAL_JOB_NAME
- ```
-
-For more information about the usage of PaddleCloud, please refer to [PaddleCloud Usage](https://github.com/PaddlePaddle/cloud/blob/develop/doc/usage_cn.md#提交任务).
-
-For more information about the DeepSpeech2 training on PaddleCloud, please refer to
-[Train DeepSpeech2 on PaddleCloud](https://github.com/PaddlePaddle/models/tree/develop/deep_speech_2/cloud).
-
-## Training for Mandarin Language
-
-The key steps of training for Mandarin language are same to that of English language and we have also provided an example for Mandarin training with Aishell in ```examples/aishell```. As mentioned above, please execute ```sh run_data.sh```, ```sh run_train.sh```, ```sh run_test.sh``` and ```sh run_infer.sh``` to do data preparation, training, testing and inference correspondingly. We have also prepared a pre-trained model (downloaded by ./models/aishell/download_model.sh) for users to try with ```sh run_infer_golden.sh``` and ```sh run_test_golden.sh```. Notice that, different from English LM, the Mandarin LM is character-based and please run ```tools/tune.py``` to find an optimal setting.
-
-## Trying Live Demo with Your Own Voice
-
-Until now, an ASR model is trained and tested qualitatively (`infer.py`) and quantitatively (`test.py`) with existing audio files. But it is not yet tested with your own speech. `deploy/demo_server.py` and `deploy/demo_client.py` helps quickly build up a real-time demo ASR engine with the trained model, enabling you to test and play around with the demo, with your own voice.
-
-To start the demo's server, please run this in one console:
-
-```bash
-CUDA_VISIBLE_DEVICES=0 \
-python deploy/demo_server.py \
---trainer_count 1 \
---host_ip localhost \
---host_port 8086
-```
-
-For the machine (might not be the same machine) to run the demo's client, please do the following installation before moving on.
-
-For example, on MAC OS X:
-
-```bash
-brew install portaudio
-pip install pyaudio
-pip install pynput
-```
-
-Then to start the client, please run this in another console:
-
-```bash
-CUDA_VISIBLE_DEVICES=0 \
-python -u deploy/demo_client.py \
---host_ip 'localhost' \
---host_port 8086
-```
-
-Now, in the client console, press the `whitespace` key, hold, and start speaking. Until finishing your utterance, release the key to let the speech-to-text results shown in the console. To quit the client, just press `ESC` key.
-
-Notice that `deploy/demo_client.py` must be run on a machine with a microphone device, while `deploy/demo_server.py` could be run on one without any audio recording hardware, e.g. any remote server machine. Just be careful to set the `host_ip` and `host_port` argument with the actual accessible IP address and port, if the server and client are running with two separate machines. Nothing should be done if they are running on one single machine.
-
-Please also refer to `examples/mandarin/run_demo_server.sh`, which will first download a pre-trained Mandarin model (trained with 3000 hours of internal speech data) and then start the demo server with the model. With running `examples/mandarin/run_demo_client.sh`, you can speak Mandarin to test it. If you would like to try some other models, just update `--model_path` argument in the script.
-
-For more help on arguments:
-
-```bash
-python deploy/demo_server.py --help
-python deploy/demo_client.py --help
-```
-
-## Released Models
-
-#### Speech Model Released
-
-Language | Model Name | Training Data | Hours of Speech
-:-----------: | :------------: | :----------: | -------:
-English | [LibriSpeech Model](http://cloud.dlnel.org/filepub/?uuid=17404caf-cf19-492f-9707-1fad07c19aae) | [LibriSpeech Dataset](http://www.openslr.org/12/) | 960 h
-English | [BaiduEN8k Model](to-be-added) | Baidu Internal English Dataset | 8628 h
-Mandarin | [Aishell Model](http://cloud.dlnel.org/filepub/?uuid=6c83b9d8-3255-4adf-9726-0fe0be3d0274) | [Aishell Dataset](http://www.openslr.org/33/) | 151 h
-Mandarin | [BaiduCN1.2k Model](to-be-added) | Baidu Internal Mandarin Dataset | 1204 h
-
-#### Language Model Released
-
-Language Model | Training Data | Token-based | Size | Descriptions
-:-------------:| :------------:| :-----: | -----: | :-----------------
-[English LM](http://paddlepaddle.bj.bcebos.com/model_zoo/speech/common_crawl_00.prune01111.trie.klm) | [CommonCrawl(en.00)](http://web-language-models.s3-website-us-east-1.amazonaws.com/ngrams/en/deduped/en.00.deduped.xz) | Word-based | 8.3 GB | Pruned with 0 1 1 1 1;
About 1.85 billion n-grams;
'trie' binary with '-a 22 -q 8 -b 8'
-[Mandarin LM Small](http://cloud.dlnel.org/filepub/?uuid=d21861e4-4ed6-45bb-ad8e-ae417a43195e) | Baidu Internal Corpus | Char-based | 2.8 GB | Pruned with 0 1 2 4 4;
About 0.13 billion n-grams;
'probing' binary with default settings
-[Mandarin LM Large](http://cloud.dlnel.org/filepub/?uuid=245d02bb-cd01-4ebe-b079-b97be864ec37) | Baidu Internal Corpus | Char-based | 70.4 GB | No Pruning;
About 3.7 billion n-grams;
'probing' binary with default settings
-
-## Experiments and Benchmarks
-
-#### Benchmark Results for English Models (Word Error Rate)
-
-Test Set | LibriSpeech Model | BaiduEN8K Model
-:--------------------- | ---------------: | -------------------:
-LibriSpeech Test-Clean | 7.77 | 6.63
-LibriSpeech Test-Other | 23.25 | 16.59
-VoxForge American-Canadian | 12.52 | 7.46
-VoxForge Commonwealth | 21.08 | 16.23
-VoxForge European | 31.21 | 20.47
-VoxForge Indian | 56.79 | 28.15
-Baidu Internal Testset | 47.73 | 8.92
-
-#### Benchmark Results for Mandarin Model (Character Error Rate)
-
-Test Set | Aishell Model | BaiduCN1.2k Model
-:--------------------- | ---------------: | -------------------:
-Baidu Internal Testset | - | 15.49
-
-#### Acceleration with Multi-GPUs
-
-We compare the training time with 1, 2, 4, 8, 16 Tesla K40m GPUs (with a subset of LibriSpeech samples whose audio durations are between 6.0 and 7.0 seconds). And it shows that a **near-linear** acceleration with multiple GPUs has been achieved. In the following figure, the time (in seconds) cost for training is printed on the blue bars.
-
-
-
-| # of GPU | Acceleration Rate |
-| -------- | --------------: |
-| 1 | 1.00 X |
-| 2 | 1.97 X |
-| 4 | 3.74 X |
-| 8 | 6.21 X |
-|16 | 10.70 X |
-
-`tools/profile.sh` provides such a profiling tool.
-
-## Questions and Help
-
-You are welcome to submit questions and bug reports in [Github Issues](https://github.com/PaddlePaddle/models/issues). You are also welcome to contribute to this project.
diff --git a/deep_speech_2/cloud/README.md b/deep_speech_2/cloud/README.md
deleted file mode 100644
index a5be1c420880d4f32d472cdd23124cbf35033094..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/README.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Train DeepSpeech2 on PaddleCloud
-
->Note:
->Please make sure [PaddleCloud Client](https://github.com/PaddlePaddle/cloud/blob/develop/doc/usage_cn.md#%E4%B8%8B%E8%BD%BD%E5%B9%B6%E9%85%8D%E7%BD%AEpaddlecloud) has be installed and current directory is `deep_speech_2/cloud/`
-
-## Step 1: Upload Data
-
-Provided with several input manifests, `pcloud_upload_data.sh` will pack and upload all the containing audio files to PaddleCloud filesystem, and also generate some corresponding manifest files with updated cloud paths.
-
-Please modify the following arguments in `pcloud_upload_data.sh`:
-
-- `IN_MANIFESTS`: Paths (in local filesystem) of manifest files containing the audio files to be uploaded. Multiple paths can be concatenated with a whitespace delimeter.
-- `OUT_MANIFESTS`: Paths (in local filesystem) to write the updated output manifest files to. Multiple paths can be concatenated with a whitespace delimeter. The values of `audio_filepath` in the output manifests are updated with cloud filesystem paths.
-- `CLOUD_DATA_DIR`: Directory (in PaddleCloud filesystem) to upload the data to. Don't forget to replace `USERNAME` in the default directory and make sure that you have the permission to write it.
-- `NUM_SHARDS`: Number of data shards / parts (in tar files) to be generated when packing and uploading data. Smaller `num_shards` requires larger temoporal local disk space for packing data.
-
-By running:
-
-```
-sh pcloud_upload_data.sh
-```
-all the audio files will be uploaded to PaddleCloud filesystem, and you will get modified manifests files in `OUT_MANIFESTS`.
-
-You have to take this step only once, in the very first time you do the cloud training. Later on, the data is persisitent on the cloud filesystem and reusable for further job submissions.
-
-## Step 2: Configure Training
-
-Configure cloud training arguments in `pcloud_submit.sh`, with the following arguments:
-
-- `TRAIN_MANIFEST`: Manifest filepath (in local filesystem) for training. Notice that the`audio_filepath` should be in cloud filesystem, like those generated by `pcloud_upload_data.sh`.
-- `DEV_MANIFEST`: Manifest filepath (in local filesystem) for validation.
-- `CLOUD_MODEL_DIR`: Directory (in PaddleCloud filesystem) to save the model parameters (checkpoints). Don't forget to replace `USERNAME` in the default directory and make sure that you have the permission to write it.
-- `BATCH_SIZE`: Training batch size for a single node.
-- `NUM_GPU`: Number of GPUs allocated for a single node.
-- `NUM_NODE`: Number of nodes (machines) allocated for this job.
-- `IS_LOCAL`: Set to False to enable parameter server, if using multiple nodes.
-
-Configure other training hyper-parameters in `pcloud_train.sh` as you wish, just as what you can do in local training.
-
-By running:
-
-```
-sh pcloud_submit.sh
-```
-you submit a training job to PaddleCloud. And you will see the job name when the submission is done.
-
-
-## Step 3 Get Job Logs
-
-Run this to list all the jobs you have submitted, as well as their running status:
-
-```
-paddlecloud get jobs
-```
-
-Run this, the corresponding job's logs will be printed.
-```
-paddlecloud logs -n 10000 $REPLACED_WITH_YOUR_ACTUAL_JOB_NAME
-```
-
-## More Help
-
-For more information about the usage of PaddleCloud, please refer to [PaddleCloud Usage](https://github.com/PaddlePaddle/cloud/blob/develop/doc/usage_cn.md#提交任务).
diff --git a/deep_speech_2/cloud/_init_paths.py b/deep_speech_2/cloud/_init_paths.py
deleted file mode 100644
index 3305d7488ff1cfb03db7175a53f70c1a107fe52e..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/_init_paths.py
+++ /dev/null
@@ -1,17 +0,0 @@
-"""Set up paths for DS2"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import os.path
-import sys
-
-
-def add_path(path):
- if path not in sys.path:
- sys.path.insert(0, path)
-
-
-this_dir = os.path.dirname(__file__)
-proj_path = os.path.join(this_dir, '..')
-add_path(proj_path)
diff --git a/deep_speech_2/cloud/pcloud_submit.sh b/deep_speech_2/cloud/pcloud_submit.sh
deleted file mode 100644
index 99e458db96b819019628a26f05b3597ea951aeea..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/pcloud_submit.sh
+++ /dev/null
@@ -1,29 +0,0 @@
-#! /usr/bin/env bash
-
-TRAIN_MANIFEST="cloud/cloud_manifests/cloud.manifest.train"
-DEV_MANIFEST="cloud/cloud_manifests/cloud.manifest.dev"
-CLOUD_MODEL_DIR="./checkpoints"
-BATCH_SIZE=512
-NUM_GPU=8
-NUM_NODE=1
-IS_LOCAL="True"
-
-JOB_NAME=deepspeech-`date +%Y%m%d%H%M%S`
-DS2_PATH=${PWD%/*}
-cp -f pcloud_train.sh ${DS2_PATH}
-
-paddlecloud submit \
--image bootstrapper:5000/paddlepaddle/pcloud_ds2:latest \
--jobname ${JOB_NAME} \
--cpu ${NUM_GPU} \
--gpu ${NUM_GPU} \
--memory 64Gi \
--parallelism ${NUM_NODE} \
--pscpu 1 \
--pservers 1 \
--psmemory 64Gi \
--passes 1 \
--entry "sh pcloud_train.sh ${TRAIN_MANIFEST} ${DEV_MANIFEST} ${CLOUD_MODEL_DIR} ${NUM_GPU} ${BATCH_SIZE} ${IS_LOCAL}" \
-${DS2_PATH}
-
-rm ${DS2_PATH}/pcloud_train.sh
diff --git a/deep_speech_2/cloud/pcloud_train.sh b/deep_speech_2/cloud/pcloud_train.sh
deleted file mode 100644
index d0c47dece91c43d0cbfde1f6eb2dcc96fce36391..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/pcloud_train.sh
+++ /dev/null
@@ -1,46 +0,0 @@
-#! /usr/bin/env bash
-
-TRAIN_MANIFEST=$1
-DEV_MANIFEST=$2
-MODEL_PATH=$3
-NUM_GPU=$4
-BATCH_SIZE=$5
-IS_LOCAL=$6
-
-python ./cloud/split_data.py \
---in_manifest_path=${TRAIN_MANIFEST} \
---out_manifest_path='/local.manifest.train'
-
-python ./cloud/split_data.py \
---in_manifest_path=${DEV_MANIFEST} \
---out_manifest_path='/local.manifest.dev'
-
-mkdir ./logs
-
-python -u train.py \
---batch_size=${BATCH_SIZE} \
---trainer_count=${NUM_GPU} \
---num_passes=200 \
---num_proc_data=${NUM_GPU} \
---num_conv_layers=2 \
---num_rnn_layers=3 \
---rnn_layer_size=2048 \
---num_iter_print=100 \
---learning_rate=5e-4 \
---max_duration=27.0 \
---min_duration=0.0 \
---use_sortagrad=True \
---use_gru=False \
---use_gpu=True \
---is_local=${IS_LOCAL} \
---share_rnn_weights=True \
---train_manifest='/local.manifest.train' \
---dev_manifest='/local.manifest.dev' \
---mean_std_path='data/librispeech/mean_std.npz' \
---vocab_path='data/librispeech/vocab.txt' \
---output_model_dir='./checkpoints' \
---output_model_dir=${MODEL_PATH} \
---augment_conf_path='conf/augmentation.config' \
---specgram_type='linear' \
---shuffle_method='batch_shuffle_clipped' \
-2>&1 | tee ./logs/train.log
diff --git a/deep_speech_2/cloud/pcloud_upload_data.sh b/deep_speech_2/cloud/pcloud_upload_data.sh
deleted file mode 100644
index 71bb4af19b3b30f6efc31cb9b60f4f3b330b46b9..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/pcloud_upload_data.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#! /usr/bin/env bash
-
-mkdir cloud_manifests
-
-IN_MANIFESTS="../data/librispeech/manifest.train ../data/librispeech/manifest.dev-clean ../data/librispeech/manifest.test-clean"
-OUT_MANIFESTS="cloud_manifests/cloud.manifest.train cloud_manifests/cloud.manifest.dev cloud_manifests/cloud.manifest.test"
-CLOUD_DATA_DIR="/pfs/dlnel/home/USERNAME/deepspeech2/data/librispeech"
-NUM_SHARDS=50
-
-python upload_data.py \
---in_manifest_paths ${IN_MANIFESTS} \
---out_manifest_paths ${OUT_MANIFESTS} \
---cloud_data_dir ${CLOUD_DATA_DIR} \
---num_shards ${NUM_SHARDS}
-
-if [ $? -ne 0 ]
-then
- echo "Upload Data Failed!"
- exit 1
-fi
-
-echo "All Done."
diff --git a/deep_speech_2/cloud/split_data.py b/deep_speech_2/cloud/split_data.py
deleted file mode 100644
index 3496d52bfb5bf6c249c03dfb4df2937625bd55b5..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/split_data.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""This tool is used for splitting data into each node of
-paddlecloud. This script should be called in paddlecloud.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import os
-import json
-import argparse
-
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument(
- "--in_manifest_path",
- type=str,
- required=True,
- help="Input manifest path for all nodes.")
-parser.add_argument(
- "--out_manifest_path",
- type=str,
- required=True,
- help="Output manifest file path for current node.")
-args = parser.parse_args()
-
-
-def split_data(in_manifest_path, out_manifest_path):
- with open("/trainer_id", "r") as f:
- trainer_id = int(f.readline()[:-1])
- with open("/trainer_count", "r") as f:
- trainer_count = int(f.readline()[:-1])
-
- out_manifest = []
- for index, json_line in enumerate(open(in_manifest_path, 'r')):
- if (index % trainer_count) == trainer_id:
- out_manifest.append("%s\n" % json_line.strip())
- with open(out_manifest_path, 'w') as f:
- f.writelines(out_manifest)
-
-
-if __name__ == '__main__':
- split_data(args.in_manifest_path, args.out_manifest_path)
diff --git a/deep_speech_2/cloud/upload_data.py b/deep_speech_2/cloud/upload_data.py
deleted file mode 100644
index 9973f8c768410fd86a6ded6a74dac24f9f918173..0000000000000000000000000000000000000000
--- a/deep_speech_2/cloud/upload_data.py
+++ /dev/null
@@ -1,129 +0,0 @@
-"""This script is for uploading data for DeepSpeech2 training on paddlecloud.
-
-Steps:
-1. Read original manifests and extract local sound files.
-2. Tar all local sound files into multiple tar files and upload them.
-3. Modify original manifests with updated paths in cloud filesystem.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import json
-import os
-import tarfile
-import sys
-import argparse
-import shutil
-from subprocess import call
-import _init_paths
-from data_utils.utils import read_manifest
-
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument(
- "--in_manifest_paths",
- default=[
- "../datasets/manifest.train", "../datasets/manifest.dev",
- "../datasets/manifest.test"
- ],
- type=str,
- nargs='+',
- help="Local filepaths of input manifests to load, pack and upload."
- "(default: %(default)s)")
-parser.add_argument(
- "--out_manifest_paths",
- default=[
- "./cloud.manifest.train", "./cloud.manifest.dev",
- "./cloud.manifest.test"
- ],
- type=str,
- nargs='+',
- help="Local filepaths of modified manifests to write to. "
- "(default: %(default)s)")
-parser.add_argument(
- "--cloud_data_dir",
- required=True,
- type=str,
- help="Destination directory on paddlecloud to upload data to.")
-parser.add_argument(
- "--num_shards",
- default=10,
- type=int,
- help="Number of parts to split data to. (default: %(default)s)")
-parser.add_argument(
- "--local_tmp_dir",
- default="./tmp/",
- type=str,
- help="Local directory for storing temporary data. (default: %(default)s)")
-args = parser.parse_args()
-
-
-def upload_data(in_manifest_path_list, out_manifest_path_list, local_tmp_dir,
- upload_tar_dir, num_shards):
- """Extract and pack sound files listed in the manifest files into multple
- tar files and upload them to padldecloud. Besides, generate new manifest
- files with updated paths in paddlecloud.
- """
- # compute total audio number
- total_line = 0
- for manifest_path in in_manifest_path_list:
- with open(manifest_path, 'r') as f:
- total_line += len(f.readlines())
- line_per_tar = (total_line // num_shards) + 1
-
- # pack and upload shard by shard
- line_count, tar_file = 0, None
- for manifest_path, out_manifest_path in zip(in_manifest_path_list,
- out_manifest_path_list):
- manifest = read_manifest(manifest_path)
- out_manifest = []
- for json_data in manifest:
- sound_filepath = json_data['audio_filepath']
- sound_filename = os.path.basename(sound_filepath)
- if line_count % line_per_tar == 0:
- if tar_file != None:
- tar_file.close()
- pcloud_cp(tar_path, upload_tar_dir)
- os.remove(tar_path)
- tar_name = 'part-%s-of-%s.tar' % (
- str(line_count // line_per_tar).zfill(5),
- str(num_shards).zfill(5))
- tar_path = os.path.join(local_tmp_dir, tar_name)
- tar_file = tarfile.open(tar_path, 'w')
- tar_file.add(sound_filepath, arcname=sound_filename)
- line_count += 1
- json_data['audio_filepath'] = "tar:%s#%s" % (
- os.path.join(upload_tar_dir, tar_name), sound_filename)
- out_manifest.append("%s\n" % json.dumps(json_data))
- with open(out_manifest_path, 'w') as f:
- f.writelines(out_manifest)
- pcloud_cp(out_manifest_path, upload_tar_dir)
- tar_file.close()
- pcloud_cp(tar_path, upload_tar_dir)
- os.remove(tar_path)
-
-
-def pcloud_mkdir(dir):
- """Make directory in PaddleCloud filesystem.
- """
- if call(['paddlecloud', 'mkdir', dir]) != 0:
- raise IOError("PaddleCloud mkdir failed: %s." % dir)
-
-
-def pcloud_cp(src, dst):
- """Copy src from local filesytem to dst in PaddleCloud filesystem,
- or downlowd src from PaddleCloud filesystem to dst in local filesystem.
- """
- if call(['paddlecloud', 'cp', src, dst]) != 0:
- raise IOError("PaddleCloud cp failed: from [%s] to [%s]." % (src, dst))
-
-
-if __name__ == '__main__':
- if not os.path.exists(args.local_tmp_dir):
- os.makedirs(args.local_tmp_dir)
- pcloud_mkdir(args.cloud_data_dir)
-
- upload_data(args.in_manifest_paths, args.out_manifest_paths,
- args.local_tmp_dir, args.cloud_data_dir, args.num_shards)
-
- shutil.rmtree(args.local_tmp_dir)
diff --git a/deep_speech_2/conf/augmentation.config b/deep_speech_2/conf/augmentation.config
deleted file mode 100644
index 6c24da5497460d4bae9c9c4fecdbe96ab8da7532..0000000000000000000000000000000000000000
--- a/deep_speech_2/conf/augmentation.config
+++ /dev/null
@@ -1,8 +0,0 @@
-[
- {
- "type": "shift",
- "params": {"min_shift_ms": -5,
- "max_shift_ms": 5},
- "prob": 1.0
- }
-]
diff --git a/deep_speech_2/conf/augmentation.config.example b/deep_speech_2/conf/augmentation.config.example
deleted file mode 100644
index 21ed6ee10375a749f4c072389509db2020d9e9c9..0000000000000000000000000000000000000000
--- a/deep_speech_2/conf/augmentation.config.example
+++ /dev/null
@@ -1,39 +0,0 @@
-[
- {
- "type": "noise",
- "params": {"min_snr_dB": 40,
- "max_snr_dB": 50,
- "noise_manifest_path": "datasets/manifest.noise"},
- "prob": 0.6
- },
- {
- "type": "impulse",
- "params": {"impulse_manifest_path": "datasets/manifest.impulse"},
- "prob": 0.5
- },
- {
- "type": "speed",
- "params": {"min_speed_rate": 0.95,
- "max_speed_rate": 1.05},
- "prob": 0.5
- },
- {
- "type": "shift",
- "params": {"min_shift_ms": -5,
- "max_shift_ms": 5},
- "prob": 1.0
- },
- {
- "type": "volume",
- "params": {"min_gain_dBFS": -10,
- "max_gain_dBFS": 10},
- "prob": 0.0
- },
- {
- "type": "bayesian_normal",
- "params": {"target_db": -20,
- "prior_db": -20,
- "prior_samples": 100},
- "prob": 0.0
- }
-]
diff --git a/deep_speech_2/data/aishell/aishell.py b/deep_speech_2/data/aishell/aishell.py
deleted file mode 100644
index 17786b5d42d19fd1300c142b494d78f56e9f26dd..0000000000000000000000000000000000000000
--- a/deep_speech_2/data/aishell/aishell.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Prepare Aishell mandarin dataset
-
-Download, unpack and create manifest files.
-Manifest file is a json-format file with each line containing the
-meta data (i.e. audio filepath, transcript and audio duration)
-of each audio file in the data set.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import os
-import codecs
-import soundfile
-import json
-import argparse
-from data_utils.utility import download, unpack
-
-DATA_HOME = os.path.expanduser('~/.cache/paddle/dataset/speech')
-
-URL_ROOT = 'http://www.openslr.org/resources/33'
-DATA_URL = URL_ROOT + '/data_aishell.tgz'
-MD5_DATA = '2f494334227864a8a8fec932999db9d8'
-
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument(
- "--target_dir",
- default=DATA_HOME + "/Aishell",
- type=str,
- help="Directory to save the dataset. (default: %(default)s)")
-parser.add_argument(
- "--manifest_prefix",
- default="manifest",
- type=str,
- help="Filepath prefix for output manifests. (default: %(default)s)")
-args = parser.parse_args()
-
-
-def create_manifest(data_dir, manifest_path_prefix):
- print("Creating manifest %s ..." % manifest_path_prefix)
- json_lines = []
- transcript_path = os.path.join(data_dir, 'transcript',
- 'aishell_transcript_v0.8.txt')
- transcript_dict = {}
- for line in codecs.open(transcript_path, 'r', 'utf-8'):
- line = line.strip()
- if line == '': continue
- audio_id, text = line.split(' ', 1)
- # remove withespace
- text = ''.join(text.split())
- transcript_dict[audio_id] = text
-
- data_types = ['train', 'dev', 'test']
- for type in data_types:
- audio_dir = os.path.join(data_dir, 'wav', type)
- for subfolder, _, filelist in sorted(os.walk(audio_dir)):
- for fname in filelist:
- audio_path = os.path.join(subfolder, fname)
- audio_id = fname[:-4]
- # if no transcription for audio then skipped
- if audio_id not in transcript_dict:
- continue
- audio_data, samplerate = soundfile.read(audio_path)
- duration = float(len(audio_data) / samplerate)
- text = transcript_dict[audio_id]
- json_lines.append(
- json.dumps(
- {
- 'audio_filepath': audio_path,
- 'duration': duration,
- 'text': text
- },
- ensure_ascii=False))
- manifest_path = manifest_path_prefix + '.' + type
- with codecs.open(manifest_path, 'w', 'utf-8') as fout:
- for line in json_lines:
- fout.write(line + '\n')
-
-
-def prepare_dataset(url, md5sum, target_dir, manifest_path):
- """Download, unpack and create manifest file."""
- data_dir = os.path.join(target_dir, 'data_aishell')
- if not os.path.exists(data_dir):
- filepath = download(url, md5sum, target_dir)
- unpack(filepath, target_dir)
- # unpack all audio tar files
- audio_dir = os.path.join(data_dir, 'wav')
- for subfolder, _, filelist in sorted(os.walk(audio_dir)):
- for ftar in filelist:
- unpack(os.path.join(subfolder, ftar), subfolder, True)
- else:
- print("Skip downloading and unpacking. Data already exists in %s." %
- target_dir)
- create_manifest(data_dir, manifest_path)
-
-
-def main():
- if args.target_dir.startswith('~'):
- args.target_dir = os.path.expanduser(args.target_dir)
-
- prepare_dataset(
- url=DATA_URL,
- md5sum=MD5_DATA,
- target_dir=args.target_dir,
- manifest_path=args.manifest_prefix)
-
-
-if __name__ == '__main__':
- main()
diff --git a/deep_speech_2/data/librispeech/librispeech.py b/deep_speech_2/data/librispeech/librispeech.py
deleted file mode 100644
index 9a8e1c2871f74823b04c5839dd43f08f9a03d1df..0000000000000000000000000000000000000000
--- a/deep_speech_2/data/librispeech/librispeech.py
+++ /dev/null
@@ -1,148 +0,0 @@
-"""Prepare Librispeech ASR datasets.
-
-Download, unpack and create manifest files.
-Manifest file is a json-format file with each line containing the
-meta data (i.e. audio filepath, transcript and audio duration)
-of each audio file in the data set.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import distutils.util
-import os
-import sys
-import argparse
-import soundfile
-import json
-import codecs
-from data_utils.utility import download, unpack
-
-URL_ROOT = "http://www.openslr.org/resources/12"
-URL_TEST_CLEAN = URL_ROOT + "/test-clean.tar.gz"
-URL_TEST_OTHER = URL_ROOT + "/test-other.tar.gz"
-URL_DEV_CLEAN = URL_ROOT + "/dev-clean.tar.gz"
-URL_DEV_OTHER = URL_ROOT + "/dev-other.tar.gz"
-URL_TRAIN_CLEAN_100 = URL_ROOT + "/train-clean-100.tar.gz"
-URL_TRAIN_CLEAN_360 = URL_ROOT + "/train-clean-360.tar.gz"
-URL_TRAIN_OTHER_500 = URL_ROOT + "/train-other-500.tar.gz"
-
-MD5_TEST_CLEAN = "32fa31d27d2e1cad72775fee3f4849a9"
-MD5_TEST_OTHER = "fb5a50374b501bb3bac4815ee91d3135"
-MD5_DEV_CLEAN = "42e2234ba48799c1f50f24a7926300a1"
-MD5_DEV_OTHER = "c8d0bcc9cca99d4f8b62fcc847357931"
-MD5_TRAIN_CLEAN_100 = "2a93770f6d5c6c964bc36631d331a522"
-MD5_TRAIN_CLEAN_360 = "c0e676e450a7ff2f54aeade5171606fa"
-MD5_TRAIN_OTHER_500 = "d1a0fd59409feb2c614ce4d30c387708"
-
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument(
- "--target_dir",
- default='~/.cache/paddle/dataset/speech/libri',
- type=str,
- help="Directory to save the dataset. (default: %(default)s)")
-parser.add_argument(
- "--manifest_prefix",
- default="manifest",
- type=str,
- help="Filepath prefix for output manifests. (default: %(default)s)")
-parser.add_argument(
- "--full_download",
- default="True",
- type=distutils.util.strtobool,
- help="Download all datasets for Librispeech."
- " If False, only download a minimal requirement (test-clean, dev-clean"
- " train-clean-100). (default: %(default)s)")
-args = parser.parse_args()
-
-
-def create_manifest(data_dir, manifest_path):
- """Create a manifest json file summarizing the data set, with each line
- containing the meta data (i.e. audio filepath, transcription text, audio
- duration) of each audio file within the data set.
- """
- print("Creating manifest %s ..." % manifest_path)
- json_lines = []
- for subfolder, _, filelist in sorted(os.walk(data_dir)):
- text_filelist = [
- filename for filename in filelist if filename.endswith('trans.txt')
- ]
- if len(text_filelist) > 0:
- text_filepath = os.path.join(data_dir, subfolder, text_filelist[0])
- for line in open(text_filepath):
- segments = line.strip().split()
- text = ' '.join(segments[1:]).lower()
- audio_filepath = os.path.join(data_dir, subfolder,
- segments[0] + '.flac')
- audio_data, samplerate = soundfile.read(audio_filepath)
- duration = float(len(audio_data)) / samplerate
- json_lines.append(
- json.dumps({
- 'audio_filepath': audio_filepath,
- 'duration': duration,
- 'text': text
- }))
- with codecs.open(manifest_path, 'w', 'utf-8') as out_file:
- for line in json_lines:
- out_file.write(line + '\n')
-
-
-def prepare_dataset(url, md5sum, target_dir, manifest_path):
- """Download, unpack and create summmary manifest file.
- """
- if not os.path.exists(os.path.join(target_dir, "LibriSpeech")):
- # download
- filepath = download(url, md5sum, target_dir)
- # unpack
- unpack(filepath, target_dir)
- else:
- print("Skip downloading and unpacking. Data already exists in %s." %
- target_dir)
- # create manifest json file
- create_manifest(target_dir, manifest_path)
-
-
-def main():
- if args.target_dir.startswith('~'):
- args.target_dir = os.path.expanduser(args.target_dir)
-
- prepare_dataset(
- url=URL_TEST_CLEAN,
- md5sum=MD5_TEST_CLEAN,
- target_dir=os.path.join(args.target_dir, "test-clean"),
- manifest_path=args.manifest_prefix + ".test-clean")
- prepare_dataset(
- url=URL_DEV_CLEAN,
- md5sum=MD5_DEV_CLEAN,
- target_dir=os.path.join(args.target_dir, "dev-clean"),
- manifest_path=args.manifest_prefix + ".dev-clean")
- if args.full_download:
- prepare_dataset(
- url=URL_TRAIN_CLEAN_100,
- md5sum=MD5_TRAIN_CLEAN_100,
- target_dir=os.path.join(args.target_dir, "train-clean-100"),
- manifest_path=args.manifest_prefix + ".train-clean-100")
- prepare_dataset(
- url=URL_TEST_OTHER,
- md5sum=MD5_TEST_OTHER,
- target_dir=os.path.join(args.target_dir, "test-other"),
- manifest_path=args.manifest_prefix + ".test-other")
- prepare_dataset(
- url=URL_DEV_OTHER,
- md5sum=MD5_DEV_OTHER,
- target_dir=os.path.join(args.target_dir, "dev-other"),
- manifest_path=args.manifest_prefix + ".dev-other")
- prepare_dataset(
- url=URL_TRAIN_CLEAN_360,
- md5sum=MD5_TRAIN_CLEAN_360,
- target_dir=os.path.join(args.target_dir, "train-clean-360"),
- manifest_path=args.manifest_prefix + ".train-clean-360")
- prepare_dataset(
- url=URL_TRAIN_OTHER_500,
- md5sum=MD5_TRAIN_OTHER_500,
- target_dir=os.path.join(args.target_dir, "train-other-500"),
- manifest_path=args.manifest_prefix + ".train-other-500")
-
-
-if __name__ == '__main__':
- main()
diff --git a/deep_speech_2/data/noise/chime3_background.py b/deep_speech_2/data/noise/chime3_background.py
deleted file mode 100644
index f79ca7335bda7aec795bc43c32a51519f3363d85..0000000000000000000000000000000000000000
--- a/deep_speech_2/data/noise/chime3_background.py
+++ /dev/null
@@ -1,128 +0,0 @@
-"""Prepare CHiME3 background data.
-
-Download, unpack and create manifest files.
-Manifest file is a json-format file with each line containing the
-meta data (i.e. audio filepath, transcript and audio duration)
-of each audio file in the data set.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import distutils.util
-import os
-import wget
-import zipfile
-import argparse
-import soundfile
-import json
-from paddle.v2.dataset.common import md5file
-
-DATA_HOME = os.path.expanduser('~/.cache/paddle/dataset/speech')
-
-URL = "https://d4s.myairbridge.com/packagev2/AG0Y3DNBE5IWRRTV/?dlid=W19XG7T0NNHB027139H0EQ"
-MD5 = "c3ff512618d7a67d4f85566ea1bc39ec"
-
-parser = argparse.ArgumentParser(description=__doc__)
-parser.add_argument(
- "--target_dir",
- default=DATA_HOME + "/chime3_background",
- type=str,
- help="Directory to save the dataset. (default: %(default)s)")
-parser.add_argument(
- "--manifest_filepath",
- default="manifest.chime3.background",
- type=str,
- help="Filepath for output manifests. (default: %(default)s)")
-args = parser.parse_args()
-
-
-def download(url, md5sum, target_dir, filename=None):
- """Download file from url to target_dir, and check md5sum."""
- if filename == None:
- filename = url.split("/")[-1]
- if not os.path.exists(target_dir): os.makedirs(target_dir)
- filepath = os.path.join(target_dir, filename)
- if not (os.path.exists(filepath) and md5file(filepath) == md5sum):
- print("Downloading %s ..." % url)
- wget.download(url, target_dir)
- print("\nMD5 Chesksum %s ..." % filepath)
- if not md5file(filepath) == md5sum:
- raise RuntimeError("MD5 checksum failed.")
- else:
- print("File exists, skip downloading. (%s)" % filepath)
- return filepath
-
-
-def unpack(filepath, target_dir):
- """Unpack the file to the target_dir."""
- print("Unpacking %s ..." % filepath)
- if filepath.endswith('.zip'):
- zip = zipfile.ZipFile(filepath, 'r')
- zip.extractall(target_dir)
- zip.close()
- elif filepath.endswith('.tar') or filepath.endswith('.tar.gz'):
- tar = zipfile.open(filepath)
- tar.extractall(target_dir)
- tar.close()
- else:
- raise ValueError("File format is not supported for unpacking.")
-
-
-def create_manifest(data_dir, manifest_path):
- """Create a manifest json file summarizing the data set, with each line
- containing the meta data (i.e. audio filepath, transcription text, audio
- duration) of each audio file within the data set.
- """
- print("Creating manifest %s ..." % manifest_path)
- json_lines = []
- for subfolder, _, filelist in sorted(os.walk(data_dir)):
- for filename in filelist:
- if filename.endswith('.wav'):
- filepath = os.path.join(data_dir, subfolder, filename)
- audio_data, samplerate = soundfile.read(filepath)
- duration = float(len(audio_data)) / samplerate
- json_lines.append(
- json.dumps({
- 'audio_filepath': filepath,
- 'duration': duration,
- 'text': ''
- }))
- with open(manifest_path, 'w') as out_file:
- for line in json_lines:
- out_file.write(line + '\n')
-
-
-def prepare_chime3(url, md5sum, target_dir, manifest_path):
- """Download, unpack and create summmary manifest file."""
- if not os.path.exists(os.path.join(target_dir, "CHiME3")):
- # download
- filepath = download(url, md5sum, target_dir,
- "myairbridge-AG0Y3DNBE5IWRRTV.zip")
- # unpack
- unpack(filepath, target_dir)
- unpack(
- os.path.join(target_dir, 'CHiME3_background_bus.zip'), target_dir)
- unpack(
- os.path.join(target_dir, 'CHiME3_background_caf.zip'), target_dir)
- unpack(
- os.path.join(target_dir, 'CHiME3_background_ped.zip'), target_dir)
- unpack(
- os.path.join(target_dir, 'CHiME3_background_str.zip'), target_dir)
- else:
- print("Skip downloading and unpacking. Data already exists in %s." %
- target_dir)
- # create manifest json file
- create_manifest(target_dir, manifest_path)
-
-
-def main():
- prepare_chime3(
- url=URL,
- md5sum=MD5,
- target_dir=args.target_dir,
- manifest_path=args.manifest_filepath)
-
-
-if __name__ == '__main__':
- main()
diff --git a/deep_speech_2/data_utils/audio.py b/deep_speech_2/data_utils/audio.py
deleted file mode 100644
index 3fb782951699bc1abd3d5613621e89685ee387de..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/audio.py
+++ /dev/null
@@ -1,685 +0,0 @@
-"""Contains the audio segment class."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-import io
-import struct
-import re
-import soundfile
-import resampy
-from scipy import signal
-import random
-import copy
-
-
-class AudioSegment(object):
- """Monaural audio segment abstraction.
-
- :param samples: Audio samples [num_samples x num_channels].
- :type samples: ndarray.float32
- :param sample_rate: Audio sample rate.
- :type sample_rate: int
- :raises TypeError: If the sample data type is not float or int.
- """
-
- def __init__(self, samples, sample_rate):
- """Create audio segment from samples.
-
- Samples are convert float32 internally, with int scaled to [-1, 1].
- """
- self._samples = self._convert_samples_to_float32(samples)
- self._sample_rate = sample_rate
- if self._samples.ndim >= 2:
- self._samples = np.mean(self._samples, 1)
-
- def __eq__(self, other):
- """Return whether two objects are equal."""
- if type(other) is not type(self):
- return False
- if self._sample_rate != other._sample_rate:
- return False
- if self._samples.shape != other._samples.shape:
- return False
- if np.any(self.samples != other._samples):
- return False
- return True
-
- def __ne__(self, other):
- """Return whether two objects are unequal."""
- return not self.__eq__(other)
-
- def __str__(self):
- """Return human-readable representation of segment."""
- return ("%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, "
- "rms=%.2fdB" % (type(self), self.num_samples, self.sample_rate,
- self.duration, self.rms_db))
-
- @classmethod
- def from_file(cls, file):
- """Create audio segment from audio file.
-
- :param filepath: Filepath or file object to audio file.
- :type filepath: basestring|file
- :return: Audio segment instance.
- :rtype: AudioSegment
- """
- if isinstance(file, basestring) and re.findall(r".seqbin_\d+$", file):
- return cls.from_sequence_file(file)
- else:
- samples, sample_rate = soundfile.read(file, dtype='float32')
- return cls(samples, sample_rate)
-
- @classmethod
- def slice_from_file(cls, file, start=None, end=None):
- """Loads a small section of an audio without having to load
- the entire file into the memory which can be incredibly wasteful.
-
- :param file: Input audio filepath or file object.
- :type file: basestring|file
- :param start: Start time in seconds. If start is negative, it wraps
- around from the end. If not provided, this function
- reads from the very beginning.
- :type start: float
- :param end: End time in seconds. If end is negative, it wraps around
- from the end. If not provided, the default behvaior is
- to read to the end of the file.
- :type end: float
- :return: AudioSegment instance of the specified slice of the input
- audio file.
- :rtype: AudioSegment
- :raise ValueError: If start or end is incorrectly set, e.g. out of
- bounds in time.
- """
- sndfile = soundfile.SoundFile(file)
- sample_rate = sndfile.samplerate
- duration = float(len(sndfile)) / sample_rate
- start = 0. if start is None else start
- end = 0. if end is None else end
- if start < 0.0:
- start += duration
- if end < 0.0:
- end += duration
- if start < 0.0:
- raise ValueError("The slice start position (%f s) is out of "
- "bounds." % start)
- if end < 0.0:
- raise ValueError("The slice end position (%f s) is out of bounds." %
- end)
- if start > end:
- raise ValueError("The slice start position (%f s) is later than "
- "the slice end position (%f s)." % (start, end))
- if end > duration:
- raise ValueError("The slice end position (%f s) is out of bounds "
- "(> %f s)" % (end, duration))
- start_frame = int(start * sample_rate)
- end_frame = int(end * sample_rate)
- sndfile.seek(start_frame)
- data = sndfile.read(frames=end_frame - start_frame, dtype='float32')
- return cls(data, sample_rate)
-
- @classmethod
- def from_sequence_file(cls, filepath):
- """Create audio segment from sequence file. Sequence file is a binary
- file containing a collection of multiple audio files, with several
- header bytes in the head indicating the offsets of each audio byte data
- chunk.
-
- The format is:
-
- 4 bytes (int, version),
- 4 bytes (int, num of utterance),
- 4 bytes (int, bytes per header),
- [bytes_per_header*(num_utterance+1)] bytes (offsets for each audio),
- audio_bytes_data_of_1st_utterance,
- audio_bytes_data_of_2nd_utterance,
- ......
-
- Sequence file name must end with ".seqbin". And the filename of the 5th
- utterance's audio file in sequence file "xxx.seqbin" must be
- "xxx.seqbin_5", with "5" indicating the utterance index within this
- sequence file (starting from 1).
-
- :param filepath: Filepath of sequence file.
- :type filepath: basestring
- :return: Audio segment instance.
- :rtype: AudioSegment
- """
- # parse filepath
- matches = re.match(r"(.+\.seqbin)_(\d+)", filepath)
- if matches is None:
- raise IOError("File type of %s is not supported" % filepath)
- filename = matches.group(1)
- fileno = int(matches.group(2))
-
- # read headers
- f = open(filename, 'rb')
- version = f.read(4)
- num_utterances = struct.unpack("i", f.read(4))[0]
- bytes_per_header = struct.unpack("i", f.read(4))[0]
- header_bytes = f.read(bytes_per_header * (num_utterances + 1))
- header = [
- struct.unpack("i", header_bytes[bytes_per_header * i:
- bytes_per_header * (i + 1)])[0]
- for i in range(num_utterances + 1)
- ]
-
- # read audio bytes
- f.seek(header[fileno - 1])
- audio_bytes = f.read(header[fileno] - header[fileno - 1])
- f.close()
-
- # create audio segment
- try:
- return cls.from_bytes(audio_bytes)
- except Exception as e:
- samples = np.frombuffer(audio_bytes, dtype='int16')
- return cls(samples=samples, sample_rate=8000)
-
- @classmethod
- def from_bytes(cls, bytes):
- """Create audio segment from a byte string containing audio samples.
-
- :param bytes: Byte string containing audio samples.
- :type bytes: str
- :return: Audio segment instance.
- :rtype: AudioSegment
- """
- samples, sample_rate = soundfile.read(
- io.BytesIO(bytes), dtype='float32')
- return cls(samples, sample_rate)
-
- @classmethod
- def concatenate(cls, *segments):
- """Concatenate an arbitrary number of audio segments together.
-
- :param *segments: Input audio segments to be concatenated.
- :type *segments: tuple of AudioSegment
- :return: Audio segment instance as concatenating results.
- :rtype: AudioSegment
- :raises ValueError: If the number of segments is zero, or if the
- sample_rate of any segments does not match.
- :raises TypeError: If any segment is not AudioSegment instance.
- """
- # Perform basic sanity-checks.
- if len(segments) == 0:
- raise ValueError("No audio segments are given to concatenate.")
- sample_rate = segments[0]._sample_rate
- for seg in segments:
- if sample_rate != seg._sample_rate:
- raise ValueError("Can't concatenate segments with "
- "different sample rates")
- if type(seg) is not cls:
- raise TypeError("Only audio segments of the same type "
- "can be concatenated.")
- samples = np.concatenate([seg.samples for seg in segments])
- return cls(samples, sample_rate)
-
- @classmethod
- def make_silence(cls, duration, sample_rate):
- """Creates a silent audio segment of the given duration and sample rate.
-
- :param duration: Length of silence in seconds.
- :type duration: float
- :param sample_rate: Sample rate.
- :type sample_rate: float
- :return: Silent AudioSegment instance of the given duration.
- :rtype: AudioSegment
- """
- samples = np.zeros(int(duration * sample_rate))
- return cls(samples, sample_rate)
-
- def to_wav_file(self, filepath, dtype='float32'):
- """Save audio segment to disk as wav file.
-
- :param filepath: WAV filepath or file object to save the
- audio segment.
- :type filepath: basestring|file
- :param dtype: Subtype for audio file. Options: 'int16', 'int32',
- 'float32', 'float64'. Default is 'float32'.
- :type dtype: str
- :raises TypeError: If dtype is not supported.
- """
- samples = self._convert_samples_from_float32(self._samples, dtype)
- subtype_map = {
- 'int16': 'PCM_16',
- 'int32': 'PCM_32',
- 'float32': 'FLOAT',
- 'float64': 'DOUBLE'
- }
- soundfile.write(
- filepath,
- samples,
- self._sample_rate,
- format='WAV',
- subtype=subtype_map[dtype])
-
- def superimpose(self, other):
- """Add samples from another segment to those of this segment
- (sample-wise addition, not segment concatenation).
-
- Note that this is an in-place transformation.
-
- :param other: Segment containing samples to be added in.
- :type other: AudioSegments
- :raise TypeError: If type of two segments don't match.
- :raise ValueError: If the sample rates of the two segments are not
- equal, or if the lengths of segments don't match.
- """
- if isinstance(other, type(self)):
- raise TypeError("Cannot add segments of different types: %s "
- "and %s." % (type(self), type(other)))
- if self._sample_rate != other._sample_rate:
- raise ValueError("Sample rates must match to add segments.")
- if len(self._samples) != len(other._samples):
- raise ValueError("Segment lengths must match to add segments.")
- self._samples += other._samples
-
- def to_bytes(self, dtype='float32'):
- """Create a byte string containing the audio content.
-
- :param dtype: Data type for export samples. Options: 'int16', 'int32',
- 'float32', 'float64'. Default is 'float32'.
- :type dtype: str
- :return: Byte string containing audio content.
- :rtype: str
- """
- samples = self._convert_samples_from_float32(self._samples, dtype)
- return samples.tostring()
-
- def gain_db(self, gain):
- """Apply gain in decibels to samples.
-
- Note that this is an in-place transformation.
-
- :param gain: Gain in decibels to apply to samples.
- :type gain: float|1darray
- """
- self._samples *= 10.**(gain / 20.)
-
- def change_speed(self, speed_rate):
- """Change the audio speed by linear interpolation.
-
- Note that this is an in-place transformation.
-
- :param speed_rate: Rate of speed change:
- speed_rate > 1.0, speed up the audio;
- speed_rate = 1.0, unchanged;
- speed_rate < 1.0, slow down the audio;
- speed_rate <= 0.0, not allowed, raise ValueError.
- :type speed_rate: float
- :raises ValueError: If speed_rate <= 0.0.
- """
- if speed_rate <= 0:
- raise ValueError("speed_rate should be greater than zero.")
- old_length = self._samples.shape[0]
- new_length = int(old_length / speed_rate)
- old_indices = np.arange(old_length)
- new_indices = np.linspace(start=0, stop=old_length, num=new_length)
- self._samples = np.interp(new_indices, old_indices, self._samples)
-
- def normalize(self, target_db=-20, max_gain_db=300.0):
- """Normalize audio to be of the desired RMS value in decibels.
-
- Note that this is an in-place transformation.
-
- :param target_db: Target RMS value in decibels. This value should be
- less than 0.0 as 0.0 is full-scale audio.
- :type target_db: float
- :param max_gain_db: Max amount of gain in dB that can be applied for
- normalization. This is to prevent nans when
- attempting to normalize a signal consisting of
- all zeros.
- :type max_gain_db: float
- :raises ValueError: If the required gain to normalize the segment to
- the target_db value exceeds max_gain_db.
- """
- gain = target_db - self.rms_db
- if gain > max_gain_db:
- raise ValueError(
- "Unable to normalize segment to %f dB because the "
- "the probable gain have exceeds max_gain_db (%f dB)" %
- (target_db, max_gain_db))
- self.gain_db(min(max_gain_db, target_db - self.rms_db))
-
- def normalize_online_bayesian(self,
- target_db,
- prior_db,
- prior_samples,
- startup_delay=0.0):
- """Normalize audio using a production-compatible online/causal
- algorithm. This uses an exponential likelihood and gamma prior to
- make online estimates of the RMS even when there are very few samples.
-
- Note that this is an in-place transformation.
-
- :param target_db: Target RMS value in decibels.
- :type target_bd: float
- :param prior_db: Prior RMS estimate in decibels.
- :type prior_db: float
- :param prior_samples: Prior strength in number of samples.
- :type prior_samples: float
- :param startup_delay: Default 0.0s. If provided, this function will
- accrue statistics for the first startup_delay
- seconds before applying online normalization.
- :type startup_delay: float
- """
- # Estimate total RMS online.
- startup_sample_idx = min(self.num_samples - 1,
- int(self.sample_rate * startup_delay))
- prior_mean_squared = 10.**(prior_db / 10.)
- prior_sum_of_squares = prior_mean_squared * prior_samples
- cumsum_of_squares = np.cumsum(self.samples**2)
- sample_count = np.arange(self.num_samples) + 1
- if startup_sample_idx > 0:
- cumsum_of_squares[:startup_sample_idx] = \
- cumsum_of_squares[startup_sample_idx]
- sample_count[:startup_sample_idx] = \
- sample_count[startup_sample_idx]
- mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) /
- (sample_count + prior_samples))
- rms_estimate_db = 10 * np.log10(mean_squared_estimate)
- # Compute required time-varying gain.
- gain_db = target_db - rms_estimate_db
- self.gain_db(gain_db)
-
- def resample(self, target_sample_rate, filter='kaiser_best'):
- """Resample the audio to a target sample rate.
-
- Note that this is an in-place transformation.
-
- :param target_sample_rate: Target sample rate.
- :type target_sample_rate: int
- :param filter: The resampling filter to use one of {'kaiser_best',
- 'kaiser_fast'}.
- :type filter: str
- """
- self._samples = resampy.resample(
- self.samples, self.sample_rate, target_sample_rate, filter=filter)
- self._sample_rate = target_sample_rate
-
- def pad_silence(self, duration, sides='both'):
- """Pad this audio sample with a period of silence.
-
- Note that this is an in-place transformation.
-
- :param duration: Length of silence in seconds to pad.
- :type duration: float
- :param sides: Position for padding:
- 'beginning' - adds silence in the beginning;
- 'end' - adds silence in the end;
- 'both' - adds silence in both the beginning and the end.
- :type sides: str
- :raises ValueError: If sides is not supported.
- """
- if duration == 0.0:
- return self
- cls = type(self)
- silence = self.make_silence(duration, self._sample_rate)
- if sides == "beginning":
- padded = cls.concatenate(silence, self)
- elif sides == "end":
- padded = cls.concatenate(self, silence)
- elif sides == "both":
- padded = cls.concatenate(silence, self, silence)
- else:
- raise ValueError("Unknown value for the sides %s" % sides)
- self._samples = padded._samples
-
- def shift(self, shift_ms):
- """Shift the audio in time. If `shift_ms` is positive, shift with time
- advance; if negative, shift with time delay. Silence are padded to
- keep the duration unchanged.
-
- Note that this is an in-place transformation.
-
- :param shift_ms: Shift time in millseconds. If positive, shift with
- time advance; if negative; shift with time delay.
- :type shift_ms: float
- :raises ValueError: If shift_ms is longer than audio duration.
- """
- if abs(shift_ms) / 1000.0 > self.duration:
- raise ValueError("Absolute value of shift_ms should be smaller "
- "than audio duration.")
- shift_samples = int(shift_ms * self._sample_rate / 1000)
- if shift_samples > 0:
- # time advance
- self._samples[:-shift_samples] = self._samples[shift_samples:]
- self._samples[-shift_samples:] = 0
- elif shift_samples < 0:
- # time delay
- self._samples[-shift_samples:] = self._samples[:shift_samples]
- self._samples[:-shift_samples] = 0
-
- def subsegment(self, start_sec=None, end_sec=None):
- """Cut the AudioSegment between given boundaries.
-
- Note that this is an in-place transformation.
-
- :param start_sec: Beginning of subsegment in seconds.
- :type start_sec: float
- :param end_sec: End of subsegment in seconds.
- :type end_sec: float
- :raise ValueError: If start_sec or end_sec is incorrectly set, e.g. out
- of bounds in time.
- """
- start_sec = 0.0 if start_sec is None else start_sec
- end_sec = self.duration if end_sec is None else end_sec
- if start_sec < 0.0:
- start_sec = self.duration + start_sec
- if end_sec < 0.0:
- end_sec = self.duration + end_sec
- if start_sec < 0.0:
- raise ValueError("The slice start position (%f s) is out of "
- "bounds." % start_sec)
- if end_sec < 0.0:
- raise ValueError("The slice end position (%f s) is out of bounds." %
- end_sec)
- if start_sec > end_sec:
- raise ValueError("The slice start position (%f s) is later than "
- "the end position (%f s)." % (start_sec, end_sec))
- if end_sec > self.duration:
- raise ValueError("The slice end position (%f s) is out of bounds "
- "(> %f s)" % (end_sec, self.duration))
- start_sample = int(round(start_sec * self._sample_rate))
- end_sample = int(round(end_sec * self._sample_rate))
- self._samples = self._samples[start_sample:end_sample]
-
- def random_subsegment(self, subsegment_length, rng=None):
- """Cut the specified length of the audiosegment randomly.
-
- Note that this is an in-place transformation.
-
- :param subsegment_length: Subsegment length in seconds.
- :type subsegment_length: float
- :param rng: Random number generator state.
- :type rng: random.Random
- :raises ValueError: If the length of subsegment is greater than
- the origineal segemnt.
- """
- rng = random.Random() if rng is None else rng
- if subsegment_length > self.duration:
- raise ValueError("Length of subsegment must not be greater "
- "than original segment.")
- start_time = rng.uniform(0.0, self.duration - subsegment_length)
- self.subsegment(start_time, start_time + subsegment_length)
-
- def convolve(self, impulse_segment, allow_resample=False):
- """Convolve this audio segment with the given impulse segment.
-
- Note that this is an in-place transformation.
-
- :param impulse_segment: Impulse response segments.
- :type impulse_segment: AudioSegment
- :param allow_resample: Indicates whether resampling is allowed when
- the impulse_segment has a different sample
- rate from this signal.
- :type allow_resample: bool
- :raises ValueError: If the sample rate is not match between two
- audio segments when resample is not allowed.
- """
- if allow_resample and self.sample_rate != impulse_segment.sample_rate:
- impulse_segment.resample(self.sample_rate)
- if self.sample_rate != impulse_segment.sample_rate:
- raise ValueError("Impulse segment's sample rate (%d Hz) is not "
- "equal to base signal sample rate (%d Hz)." %
- (impulse_segment.sample_rate, self.sample_rate))
- samples = signal.fftconvolve(self.samples, impulse_segment.samples,
- "full")
- self._samples = samples
-
- def convolve_and_normalize(self, impulse_segment, allow_resample=False):
- """Convolve and normalize the resulting audio segment so that it
- has the same average power as the input signal.
-
- Note that this is an in-place transformation.
-
- :param impulse_segment: Impulse response segments.
- :type impulse_segment: AudioSegment
- :param allow_resample: Indicates whether resampling is allowed when
- the impulse_segment has a different sample
- rate from this signal.
- :type allow_resample: bool
- """
- target_db = self.rms_db
- self.convolve(impulse_segment, allow_resample=allow_resample)
- self.normalize(target_db)
-
- def add_noise(self,
- noise,
- snr_dB,
- allow_downsampling=False,
- max_gain_db=300.0,
- rng=None):
- """Add the given noise segment at a specific signal-to-noise ratio.
- If the noise segment is longer than this segment, a random subsegment
- of matching length is sampled from it and used instead.
-
- Note that this is an in-place transformation.
-
- :param noise: Noise signal to add.
- :type noise: AudioSegment
- :param snr_dB: Signal-to-Noise Ratio, in decibels.
- :type snr_dB: float
- :param allow_downsampling: Whether to allow the noise signal to be
- downsampled to match the base signal sample
- rate.
- :type allow_downsampling: bool
- :param max_gain_db: Maximum amount of gain to apply to noise signal
- before adding it in. This is to prevent attempting
- to apply infinite gain to a zero signal.
- :type max_gain_db: float
- :param rng: Random number generator state.
- :type rng: None|random.Random
- :raises ValueError: If the sample rate does not match between the two
- audio segments when downsampling is not allowed, or
- if the duration of noise segments is shorter than
- original audio segments.
- """
- rng = random.Random() if rng is None else rng
- if allow_downsampling and noise.sample_rate > self.sample_rate:
- noise = noise.resample(self.sample_rate)
- if noise.sample_rate != self.sample_rate:
- raise ValueError("Noise sample rate (%d Hz) is not equal to base "
- "signal sample rate (%d Hz)." % (noise.sample_rate,
- self.sample_rate))
- if noise.duration < self.duration:
- raise ValueError("Noise signal (%f sec) must be at least as long as"
- " base signal (%f sec)." %
- (noise.duration, self.duration))
- noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db)
- noise_new = copy.deepcopy(noise)
- noise_new.random_subsegment(self.duration, rng=rng)
- noise_new.gain_db(noise_gain_db)
- self.superimpose(noise_new)
-
- @property
- def samples(self):
- """Return audio samples.
-
- :return: Audio samples.
- :rtype: ndarray
- """
- return self._samples.copy()
-
- @property
- def sample_rate(self):
- """Return audio sample rate.
-
- :return: Audio sample rate.
- :rtype: int
- """
- return self._sample_rate
-
- @property
- def num_samples(self):
- """Return number of samples.
-
- :return: Number of samples.
- :rtype: int
- """
- return self._samples.shape[0]
-
- @property
- def duration(self):
- """Return audio duration.
-
- :return: Audio duration in seconds.
- :rtype: float
- """
- return self._samples.shape[0] / float(self._sample_rate)
-
- @property
- def rms_db(self):
- """Return root mean square energy of the audio in decibels.
-
- :return: Root mean square energy in decibels.
- :rtype: float
- """
- # square root => multiply by 10 instead of 20 for dBs
- mean_square = np.mean(self._samples**2)
- return 10 * np.log10(mean_square)
-
- def _convert_samples_to_float32(self, samples):
- """Convert sample type to float32.
-
- Audio sample type is usually integer or float-point.
- Integers will be scaled to [-1, 1] in float32.
- """
- float32_samples = samples.astype('float32')
- if samples.dtype in np.sctypes['int']:
- bits = np.iinfo(samples.dtype).bits
- float32_samples *= (1. / 2**(bits - 1))
- elif samples.dtype in np.sctypes['float']:
- pass
- else:
- raise TypeError("Unsupported sample type: %s." % samples.dtype)
- return float32_samples
-
- def _convert_samples_from_float32(self, samples, dtype):
- """Convert sample type from float32 to dtype.
-
- Audio sample type is usually integer or float-point. For integer
- type, float32 will be rescaled from [-1, 1] to the maximum range
- supported by the integer type.
-
- This is for writing a audio file.
- """
- dtype = np.dtype(dtype)
- output_samples = samples.copy()
- if dtype in np.sctypes['int']:
- bits = np.iinfo(dtype).bits
- output_samples *= (2**(bits - 1) / 1.)
- min_val = np.iinfo(dtype).min
- max_val = np.iinfo(dtype).max
- output_samples[output_samples > max_val] = max_val
- output_samples[output_samples < min_val] = min_val
- elif samples.dtype in np.sctypes['float']:
- min_val = np.finfo(dtype).min
- max_val = np.finfo(dtype).max
- output_samples[output_samples > max_val] = max_val
- output_samples[output_samples < min_val] = min_val
- else:
- raise TypeError("Unsupported sample type: %s." % samples.dtype)
- return output_samples.astype(dtype)
diff --git a/deep_speech_2/data_utils/augmentor/__init__.py b/deep_speech_2/data_utils/augmentor/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/deep_speech_2/data_utils/augmentor/augmentation.py b/deep_speech_2/data_utils/augmentor/augmentation.py
deleted file mode 100644
index 5c30b627ef9a23ff41d1f64f270934f149a793a2..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/augmentation.py
+++ /dev/null
@@ -1,124 +0,0 @@
-"""Contains the data augmentation pipeline."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import json
-import random
-from data_utils.augmentor.volume_perturb import VolumePerturbAugmentor
-from data_utils.augmentor.shift_perturb import ShiftPerturbAugmentor
-from data_utils.augmentor.speed_perturb import SpeedPerturbAugmentor
-from data_utils.augmentor.noise_perturb import NoisePerturbAugmentor
-from data_utils.augmentor.impulse_response import ImpulseResponseAugmentor
-from data_utils.augmentor.resample import ResampleAugmentor
-from data_utils.augmentor.online_bayesian_normalization import \
- OnlineBayesianNormalizationAugmentor
-
-
-class AugmentationPipeline(object):
- """Build a pre-processing pipeline with various augmentation models.Such a
- data augmentation pipeline is oftern leveraged to augment the training
- samples to make the model invariant to certain types of perturbations in the
- real world, improving model's generalization ability.
-
- The pipeline is built according the the augmentation configuration in json
- string, e.g.
-
- .. code-block::
-
- [ {
- "type": "noise",
- "params": {"min_snr_dB": 10,
- "max_snr_dB": 20,
- "noise_manifest_path": "datasets/manifest.noise"},
- "prob": 0.0
- },
- {
- "type": "speed",
- "params": {"min_speed_rate": 0.9,
- "max_speed_rate": 1.1},
- "prob": 1.0
- },
- {
- "type": "shift",
- "params": {"min_shift_ms": -5,
- "max_shift_ms": 5},
- "prob": 1.0
- },
- {
- "type": "volume",
- "params": {"min_gain_dBFS": -10,
- "max_gain_dBFS": 10},
- "prob": 0.0
- },
- {
- "type": "bayesian_normal",
- "params": {"target_db": -20,
- "prior_db": -20,
- "prior_samples": 100},
- "prob": 0.0
- }
- ]
-
- This augmentation configuration inserts two augmentation models
- into the pipeline, with one is VolumePerturbAugmentor and the other
- SpeedPerturbAugmentor. "prob" indicates the probability of the current
- augmentor to take effect. If "prob" is zero, the augmentor does not take
- effect.
-
- :param augmentation_config: Augmentation configuration in json string.
- :type augmentation_config: str
- :param random_seed: Random seed.
- :type random_seed: int
- :raises ValueError: If the augmentation json config is in incorrect format".
- """
-
- def __init__(self, augmentation_config, random_seed=0):
- self._rng = random.Random(random_seed)
- self._augmentors, self._rates = self._parse_pipeline_from(
- augmentation_config)
-
- def transform_audio(self, audio_segment):
- """Run the pre-processing pipeline for data augmentation.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to process.
- :type audio_segment: AudioSegmenet|SpeechSegment
- """
- for augmentor, rate in zip(self._augmentors, self._rates):
- if self._rng.uniform(0., 1.) < rate:
- augmentor.transform_audio(audio_segment)
-
- def _parse_pipeline_from(self, config_json):
- """Parse the config json to build a augmentation pipelien."""
- try:
- configs = json.loads(config_json)
- augmentors = [
- self._get_augmentor(config["type"], config["params"])
- for config in configs
- ]
- rates = [config["prob"] for config in configs]
- except Exception as e:
- raise ValueError("Failed to parse the augmentation config json: "
- "%s" % str(e))
- return augmentors, rates
-
- def _get_augmentor(self, augmentor_type, params):
- """Return an augmentation model by the type name, and pass in params."""
- if augmentor_type == "volume":
- return VolumePerturbAugmentor(self._rng, **params)
- elif augmentor_type == "shift":
- return ShiftPerturbAugmentor(self._rng, **params)
- elif augmentor_type == "speed":
- return SpeedPerturbAugmentor(self._rng, **params)
- elif augmentor_type == "resample":
- return ResampleAugmentor(self._rng, **params)
- elif augmentor_type == "bayesian_normal":
- return OnlineBayesianNormalizationAugmentor(self._rng, **params)
- elif augmentor_type == "noise":
- return NoisePerturbAugmentor(self._rng, **params)
- elif augmentor_type == "impulse":
- return ImpulseResponseAugmentor(self._rng, **params)
- else:
- raise ValueError("Unknown augmentor type [%s]." % augmentor_type)
diff --git a/deep_speech_2/data_utils/augmentor/base.py b/deep_speech_2/data_utils/augmentor/base.py
deleted file mode 100644
index a323165aaeefb8135e7189a47a388a565afd8c8a..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/base.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""Contains the abstract base class for augmentation models."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from abc import ABCMeta, abstractmethod
-
-
-class AugmentorBase(object):
- """Abstract base class for augmentation model (augmentor) class.
- All augmentor classes should inherit from this class, and implement the
- following abstract methods.
- """
-
- __metaclass__ = ABCMeta
-
- @abstractmethod
- def __init__(self):
- pass
-
- @abstractmethod
- def transform_audio(self, audio_segment):
- """Adds various effects to the input audio segment. Such effects
- will augment the training data to make the model invariant to certain
- types of perturbations in the real world, improving model's
- generalization ability.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegmenet|SpeechSegment
- """
- pass
diff --git a/deep_speech_2/data_utils/augmentor/impulse_response.py b/deep_speech_2/data_utils/augmentor/impulse_response.py
deleted file mode 100644
index 536b4d6a4a6666359b90e191a3d593250b44e863..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/impulse_response.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Contains the impulse response augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-from data_utils.utility import read_manifest
-from data_utils.audio import AudioSegment
-
-
-class ImpulseResponseAugmentor(AugmentorBase):
- """Augmentation model for adding impulse response effect.
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param impulse_manifest_path: Manifest path for impulse audio data.
- :type impulse_manifest_path: basestring
- """
-
- def __init__(self, rng, impulse_manifest_path):
- self._rng = rng
- self._impulse_manifest = read_manifest(impulse_manifest_path)
-
- def transform_audio(self, audio_segment):
- """Add impulse response effect.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegmenet|SpeechSegment
- """
- impulse_json = self._rng.sample(self._impulse_manifest, 1)[0]
- impulse_segment = AudioSegment.from_file(impulse_json['audio_filepath'])
- audio_segment.convolve(impulse_segment, allow_resample=True)
diff --git a/deep_speech_2/data_utils/augmentor/noise_perturb.py b/deep_speech_2/data_utils/augmentor/noise_perturb.py
deleted file mode 100644
index 96e0ff4deac48063faf76338014e418e3d8ad4ad..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/noise_perturb.py
+++ /dev/null
@@ -1,49 +0,0 @@
-"""Contains the noise perturb augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-from data_utils.utility import read_manifest
-from data_utils.audio import AudioSegment
-
-
-class NoisePerturbAugmentor(AugmentorBase):
- """Augmentation model for adding background noise.
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param min_snr_dB: Minimal signal noise ratio, in decibels.
- :type min_snr_dB: float
- :param max_snr_dB: Maximal signal noise ratio, in decibels.
- :type max_snr_dB: float
- :param noise_manifest_path: Manifest path for noise audio data.
- :type noise_manifest_path: basestring
- """
-
- def __init__(self, rng, min_snr_dB, max_snr_dB, noise_manifest_path):
- self._min_snr_dB = min_snr_dB
- self._max_snr_dB = max_snr_dB
- self._rng = rng
- self._noise_manifest = read_manifest(manifest_path=noise_manifest_path)
-
- def transform_audio(self, audio_segment):
- """Add background noise audio.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegmenet|SpeechSegment
- """
- noise_json = self._rng.sample(self._noise_manifest, 1)[0]
- if noise_json['duration'] < audio_segment.duration:
- raise RuntimeError("The duration of sampled noise audio is smaller "
- "than the audio segment to add effects to.")
- diff_duration = noise_json['duration'] - audio_segment.duration
- start = self._rng.uniform(0, diff_duration)
- end = start + audio_segment.duration
- noise_segment = AudioSegment.slice_from_file(
- noise_json['audio_filepath'], start=start, end=end)
- snr_dB = self._rng.uniform(self._min_snr_dB, self._max_snr_dB)
- audio_segment.add_noise(
- noise_segment, snr_dB, allow_downsampling=True, rng=self._rng)
diff --git a/deep_speech_2/data_utils/augmentor/online_bayesian_normalization.py b/deep_speech_2/data_utils/augmentor/online_bayesian_normalization.py
deleted file mode 100644
index e488ac7d67833631919f88b9e660a99b363b90d0..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/online_bayesian_normalization.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Contain the online bayesian normalization augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-
-
-class OnlineBayesianNormalizationAugmentor(AugmentorBase):
- """Augmentation model for adding online bayesian normalization.
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param target_db: Target RMS value in decibels.
- :type target_db: float
- :param prior_db: Prior RMS estimate in decibels.
- :type prior_db: float
- :param prior_samples: Prior strength in number of samples.
- :type prior_samples: int
- :param startup_delay: Default 0.0s. If provided, this function will
- accrue statistics for the first startup_delay
- seconds before applying online normalization.
- :type starup_delay: float.
- """
-
- def __init__(self,
- rng,
- target_db,
- prior_db,
- prior_samples,
- startup_delay=0.0):
- self._target_db = target_db
- self._prior_db = prior_db
- self._prior_samples = prior_samples
- self._rng = rng
- self._startup_delay = startup_delay
-
- def transform_audio(self, audio_segment):
- """Normalizes the input audio using the online Bayesian approach.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegment|SpeechSegment
- """
- audio_segment.normalize_online_bayesian(self._target_db, self._prior_db,
- self._prior_samples,
- self._startup_delay)
diff --git a/deep_speech_2/data_utils/augmentor/resample.py b/deep_speech_2/data_utils/augmentor/resample.py
deleted file mode 100644
index 8df17f3a869420bca1e4e6c0ae9b4035f7d50d8d..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/resample.py
+++ /dev/null
@@ -1,33 +0,0 @@
-"""Contain the resample augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-
-
-class ResampleAugmentor(AugmentorBase):
- """Augmentation model for resampling.
-
- See more info here:
- https://ccrma.stanford.edu/~jos/resample/index.html
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param new_sample_rate: New sample rate in Hz.
- :type new_sample_rate: int
- """
-
- def __init__(self, rng, new_sample_rate):
- self._new_sample_rate = new_sample_rate
- self._rng = rng
-
- def transform_audio(self, audio_segment):
- """Resamples the input audio to a target sample rate.
-
- Note that this is an in-place transformation.
-
- :param audio: Audio segment to add effects to.
- :type audio: AudioSegment|SpeechSegment
- """
- audio_segment.resample(self._new_sample_rate)
diff --git a/deep_speech_2/data_utils/augmentor/shift_perturb.py b/deep_speech_2/data_utils/augmentor/shift_perturb.py
deleted file mode 100644
index c4cbe3e172f6b291f3b778b748affda0341a3181..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/shift_perturb.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""Contains the volume perturb augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-
-
-class ShiftPerturbAugmentor(AugmentorBase):
- """Augmentation model for adding random shift perturbation.
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param min_shift_ms: Minimal shift in milliseconds.
- :type min_shift_ms: float
- :param max_shift_ms: Maximal shift in milliseconds.
- :type max_shift_ms: float
- """
-
- def __init__(self, rng, min_shift_ms, max_shift_ms):
- self._min_shift_ms = min_shift_ms
- self._max_shift_ms = max_shift_ms
- self._rng = rng
-
- def transform_audio(self, audio_segment):
- """Shift audio.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegmenet|SpeechSegment
- """
- shift_ms = self._rng.uniform(self._min_shift_ms, self._max_shift_ms)
- audio_segment.shift(shift_ms)
diff --git a/deep_speech_2/data_utils/augmentor/speed_perturb.py b/deep_speech_2/data_utils/augmentor/speed_perturb.py
deleted file mode 100644
index cc5738bd155a5871817039f5ccb3c4707ff87a6c..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/speed_perturb.py
+++ /dev/null
@@ -1,47 +0,0 @@
-"""Contain the speech perturbation augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-
-
-class SpeedPerturbAugmentor(AugmentorBase):
- """Augmentation model for adding speed perturbation.
-
- See reference paper here:
- http://www.danielpovey.com/files/2015_interspeech_augmentation.pdf
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param min_speed_rate: Lower bound of new speed rate to sample and should
- not be smaller than 0.9.
- :type min_speed_rate: float
- :param max_speed_rate: Upper bound of new speed rate to sample and should
- not be larger than 1.1.
- :type max_speed_rate: float
- """
-
- def __init__(self, rng, min_speed_rate, max_speed_rate):
- if min_speed_rate < 0.9:
- raise ValueError(
- "Sampling speed below 0.9 can cause unnatural effects")
- if max_speed_rate > 1.1:
- raise ValueError(
- "Sampling speed above 1.1 can cause unnatural effects")
- self._min_speed_rate = min_speed_rate
- self._max_speed_rate = max_speed_rate
- self._rng = rng
-
- def transform_audio(self, audio_segment):
- """Sample a new speed rate from the given range and
- changes the speed of the given audio clip.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegment|SpeechSegment
- """
- sampled_speed = self._rng.uniform(self._min_speed_rate,
- self._max_speed_rate)
- audio_segment.change_speed(sampled_speed)
diff --git a/deep_speech_2/data_utils/augmentor/volume_perturb.py b/deep_speech_2/data_utils/augmentor/volume_perturb.py
deleted file mode 100644
index 758676d558d8e4d77191504d0d7b75cefe020549..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/augmentor/volume_perturb.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""Contains the volume perturb augmentation model."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.augmentor.base import AugmentorBase
-
-
-class VolumePerturbAugmentor(AugmentorBase):
- """Augmentation model for adding random volume perturbation.
-
- This is used for multi-loudness training of PCEN. See
-
- https://arxiv.org/pdf/1607.05666v1.pdf
-
- for more details.
-
- :param rng: Random generator object.
- :type rng: random.Random
- :param min_gain_dBFS: Minimal gain in dBFS.
- :type min_gain_dBFS: float
- :param max_gain_dBFS: Maximal gain in dBFS.
- :type max_gain_dBFS: float
- """
-
- def __init__(self, rng, min_gain_dBFS, max_gain_dBFS):
- self._min_gain_dBFS = min_gain_dBFS
- self._max_gain_dBFS = max_gain_dBFS
- self._rng = rng
-
- def transform_audio(self, audio_segment):
- """Change audio loadness.
-
- Note that this is an in-place transformation.
-
- :param audio_segment: Audio segment to add effects to.
- :type audio_segment: AudioSegmenet|SpeechSegment
- """
- gain = self._rng.uniform(self._min_gain_dBFS, self._max_gain_dBFS)
- audio_segment.gain_db(gain)
diff --git a/deep_speech_2/data_utils/data.py b/deep_speech_2/data_utils/data.py
deleted file mode 100644
index 9dd2a91f639ec08fb2cebc0a91840943ccea6d84..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/data.py
+++ /dev/null
@@ -1,384 +0,0 @@
-"""Contains data generator for orgnaizing various audio data preprocessing
-pipeline and offering data reader interface of PaddlePaddle requirements.
-"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import random
-import tarfile
-import multiprocessing
-import numpy as np
-import paddle.v2 as paddle
-from threading import local
-import atexit
-from data_utils.utility import read_manifest
-from data_utils.utility import xmap_readers_mp
-from data_utils.augmentor.augmentation import AugmentationPipeline
-from data_utils.featurizer.speech_featurizer import SpeechFeaturizer
-from data_utils.speech import SpeechSegment
-from data_utils.normalizer import FeatureNormalizer
-
-
-class DataGenerator(object):
- """
- DataGenerator provides basic audio data preprocessing pipeline, and offers
- data reader interfaces of PaddlePaddle requirements.
-
- :param vocab_filepath: Vocabulary filepath for indexing tokenized
- transcripts.
- :type vocab_filepath: basestring
- :param mean_std_filepath: File containing the pre-computed mean and stddev.
- :type mean_std_filepath: None|basestring
- :param augmentation_config: Augmentation configuration in json string.
- Details see AugmentationPipeline.__doc__.
- :type augmentation_config: str
- :param max_duration: Audio with duration (in seconds) greater than
- this will be discarded.
- :type max_duration: float
- :param min_duration: Audio with duration (in seconds) smaller than
- this will be discarded.
- :type min_duration: float
- :param stride_ms: Striding size (in milliseconds) for generating frames.
- :type stride_ms: float
- :param window_ms: Window size (in milliseconds) for generating frames.
- :type window_ms: float
- :param max_freq: Used when specgram_type is 'linear', only FFT bins
- corresponding to frequencies between [0, max_freq] are
- returned.
- :types max_freq: None|float
- :param specgram_type: Specgram feature type. Options: 'linear'.
- :type specgram_type: str
- :param use_dB_normalization: Whether to normalize the audio to -20 dB
- before extracting the features.
- :type use_dB_normalization: bool
- :param num_threads: Number of CPU threads for processing data.
- :type num_threads: int
- :param random_seed: Random seed.
- :type random_seed: int
- :param keep_transcription_text: If set to True, transcription text will
- be passed forward directly without
- converting to index sequence.
- :type keep_transcription_text: bool
- :param num_conv_layers: The number of convolution layer, used to compute
- the sequence length.
- :type num_conv_layers: int
- """
-
- def __init__(self,
- vocab_filepath,
- mean_std_filepath,
- augmentation_config='{}',
- max_duration=float('inf'),
- min_duration=0.0,
- stride_ms=10.0,
- window_ms=20.0,
- max_freq=None,
- specgram_type='linear',
- use_dB_normalization=True,
- num_threads=multiprocessing.cpu_count() // 2,
- random_seed=0,
- keep_transcription_text=False,
- num_conv_layers=2):
- self._max_duration = max_duration
- self._min_duration = min_duration
- self._normalizer = FeatureNormalizer(mean_std_filepath)
- self._augmentation_pipeline = AugmentationPipeline(
- augmentation_config=augmentation_config, random_seed=random_seed)
- self._speech_featurizer = SpeechFeaturizer(
- vocab_filepath=vocab_filepath,
- specgram_type=specgram_type,
- stride_ms=stride_ms,
- window_ms=window_ms,
- max_freq=max_freq,
- use_dB_normalization=use_dB_normalization)
- self._num_threads = num_threads
- self._rng = random.Random(random_seed)
- self._keep_transcription_text = keep_transcription_text
- self._epoch = 0
- # for caching tar files info
- self._local_data = local()
- self._local_data.tar2info = {}
- self._local_data.tar2object = {}
- self._num_conv_layers = num_conv_layers
-
- def process_utterance(self, filename, transcript):
- """Load, augment, featurize and normalize for speech data.
-
- :param filename: Audio filepath
- :type filename: basestring | file
- :param transcript: Transcription text.
- :type transcript: basestring
- :return: Tuple of audio feature tensor and data of transcription part,
- where transcription part could be token ids or text.
- :rtype: tuple of (2darray, list)
- """
- if filename.startswith('tar:'):
- speech_segment = SpeechSegment.from_file(
- self._subfile_from_tar(filename), transcript)
- else:
- speech_segment = SpeechSegment.from_file(filename, transcript)
- self._augmentation_pipeline.transform_audio(speech_segment)
- specgram, transcript_part = self._speech_featurizer.featurize(
- speech_segment, self._keep_transcription_text)
- specgram = self._normalizer.apply(specgram)
- return specgram, transcript_part
-
- def batch_reader_creator(self,
- manifest_path,
- batch_size,
- min_batch_size=1,
- padding_to=-1,
- flatten=False,
- sortagrad=False,
- shuffle_method="batch_shuffle"):
- """
- Batch data reader creator for audio data. Return a callable generator
- function to produce batches of data.
-
- Audio features within one batch will be padded with zeros to have the
- same shape, or a user-defined shape.
-
- :param manifest_path: Filepath of manifest for audio files.
- :type manifest_path: basestring
- :param batch_size: Number of instances in a batch.
- :type batch_size: int
- :param min_batch_size: Any batch with batch size smaller than this will
- be discarded. (To be deprecated in the future.)
- :type min_batch_size: int
- :param padding_to: If set -1, the maximun shape in the batch
- will be used as the target shape for padding.
- Otherwise, `padding_to` will be the target shape.
- :type padding_to: int
- :param flatten: If set True, audio features will be flatten to 1darray.
- :type flatten: bool
- :param sortagrad: If set True, sort the instances by audio duration
- in the first epoch for speed up training.
- :type sortagrad: bool
- :param shuffle_method: Shuffle method. Options:
- '' or None: no shuffle.
- 'instance_shuffle': instance-wise shuffle.
- 'batch_shuffle': similarly-sized instances are
- put into batches, and then
- batch-wise shuffle the batches.
- For more details, please see
- ``_batch_shuffle.__doc__``.
- 'batch_shuffle_clipped': 'batch_shuffle' with
- head shift and tail
- clipping. For more
- details, please see
- ``_batch_shuffle``.
- If sortagrad is True, shuffle is disabled
- for the first epoch.
- :type shuffle_method: None|str
- :return: Batch reader function, producing batches of data when called.
- :rtype: callable
- """
-
- def batch_reader():
- # read manifest
- manifest = read_manifest(
- manifest_path=manifest_path,
- max_duration=self._max_duration,
- min_duration=self._min_duration)
- # sort (by duration) or batch-wise shuffle the manifest
- if self._epoch == 0 and sortagrad:
- manifest.sort(key=lambda x: x["duration"])
- else:
- if shuffle_method == "batch_shuffle":
- manifest = self._batch_shuffle(
- manifest, batch_size, clipped=False)
- elif shuffle_method == "batch_shuffle_clipped":
- manifest = self._batch_shuffle(
- manifest, batch_size, clipped=True)
- elif shuffle_method == "instance_shuffle":
- self._rng.shuffle(manifest)
- elif shuffle_method == None:
- pass
- else:
- raise ValueError("Unknown shuffle method %s." %
- shuffle_method)
- # prepare batches
- instance_reader = self._instance_reader_creator(manifest)
- batch = []
- for instance in instance_reader():
- batch.append(instance)
- if len(batch) == batch_size:
- yield self._padding_batch(batch, padding_to, flatten)
- batch = []
- if len(batch) >= min_batch_size:
- yield self._padding_batch(batch, padding_to, flatten)
- self._epoch += 1
-
- return batch_reader
-
- @property
- def feeding(self):
- """Returns data reader's feeding dict.
-
- :return: Data feeding dict.
- :rtype: dict
- """
- feeding_dict = {
- "audio_spectrogram": 0,
- "transcript_text": 1,
- "sequence_offset": 2,
- "sequence_length": 3
- }
- for i in xrange(self._num_conv_layers):
- feeding_dict["conv%d_index_range" % i] = len(feeding_dict)
- return feeding_dict
-
- @property
- def vocab_size(self):
- """Return the vocabulary size.
-
- :return: Vocabulary size.
- :rtype: int
- """
- return self._speech_featurizer.vocab_size
-
- @property
- def vocab_list(self):
- """Return the vocabulary in list.
-
- :return: Vocabulary in list.
- :rtype: list
- """
- return self._speech_featurizer.vocab_list
-
- def _parse_tar(self, file):
- """Parse a tar file to get a tarfile object
- and a map containing tarinfoes
- """
- result = {}
- f = tarfile.open(file)
- for tarinfo in f.getmembers():
- result[tarinfo.name] = tarinfo
- return f, result
-
- def _subfile_from_tar(self, file):
- """Get subfile object from tar.
-
- It will return a subfile object from tar file
- and cached tar file info for next reading request.
- """
- tarpath, filename = file.split(':', 1)[1].split('#', 1)
- if 'tar2info' not in self._local_data.__dict__:
- self._local_data.tar2info = {}
- if 'tar2object' not in self._local_data.__dict__:
- self._local_data.tar2object = {}
- if tarpath not in self._local_data.tar2info:
- object, infoes = self._parse_tar(tarpath)
- self._local_data.tar2info[tarpath] = infoes
- self._local_data.tar2object[tarpath] = object
- return self._local_data.tar2object[tarpath].extractfile(
- self._local_data.tar2info[tarpath][filename])
-
- def _instance_reader_creator(self, manifest):
- """
- Instance reader creator. Create a callable function to produce
- instances of data.
-
- Instance: a tuple of ndarray of audio spectrogram and a list of
- token indices for transcript.
- """
-
- def reader():
- for instance in manifest:
- yield instance
-
- reader, cleanup_callback = xmap_readers_mp(
- lambda instance: self.process_utterance(instance["audio_filepath"], instance["text"]),
- reader,
- self._num_threads,
- 4096,
- order=True)
-
- # register callback to main process
- atexit.register(cleanup_callback)
-
- return reader
-
- def _padding_batch(self, batch, padding_to=-1, flatten=False):
- """
- Padding audio features with zeros to make them have the same shape (or
- a user-defined shape) within one bach.
-
- If ``padding_to`` is -1, the maximun shape in the batch will be used
- as the target shape for padding. Otherwise, `padding_to` will be the
- target shape (only refers to the second axis).
-
- If `flatten` is True, features will be flatten to 1darray.
- """
- new_batch = []
- # get target shape
- max_length = max([audio.shape[1] for audio, text in batch])
- if padding_to != -1:
- if padding_to < max_length:
- raise ValueError("If padding_to is not -1, it should be larger "
- "than any instance's shape in the batch")
- max_length = padding_to
- # padding
- for audio, text in batch:
- padded_audio = np.zeros([audio.shape[0], max_length])
- padded_audio[:, :audio.shape[1]] = audio
- if flatten:
- padded_audio = padded_audio.flatten()
-
- # Stride size for conv0 is (3, 2)
- # Stride size for conv1 to convN is (1, 2)
- # Same as the network, hard-coded here
- padded_instance = [padded_audio, text]
- padded_conv0_h = (padded_audio.shape[0] - 1) // 2 + 1
- padded_conv0_w = (padded_audio.shape[1] - 1) // 3 + 1
- valid_w = (audio.shape[1] - 1) // 3 + 1
- padded_instance += [
- [0], # sequence offset, always 0
- [valid_w], # valid sequence length
- # Index ranges for channel, height and width
- # Please refer scale_sub_region layer to see details
- [1, 32, 1, padded_conv0_h, valid_w + 1, padded_conv0_w]
- ]
- pre_padded_h = padded_conv0_h
- for i in xrange(self._num_conv_layers - 1):
- padded_h = (pre_padded_h - 1) // 2 + 1
- pre_padded_h = padded_h
- padded_instance += [
- [1, 32, 1, padded_h, valid_w + 1, padded_conv0_w]
- ]
-
- new_batch.append(padded_instance)
- return new_batch
-
- def _batch_shuffle(self, manifest, batch_size, clipped=False):
- """Put similarly-sized instances into minibatches for better efficiency
- and make a batch-wise shuffle.
-
- 1. Sort the audio clips by duration.
- 2. Generate a random number `k`, k in [0, batch_size).
- 3. Randomly shift `k` instances in order to create different batches
- for different epochs. Create minibatches.
- 4. Shuffle the minibatches.
-
- :param manifest: Manifest contents. List of dict.
- :type manifest: list
- :param batch_size: Batch size. This size is also used for generate
- a random number for batch shuffle.
- :type batch_size: int
- :param clipped: Whether to clip the heading (small shift) and trailing
- (incomplete batch) instances.
- :type clipped: bool
- :return: Batch shuffled mainifest.
- :rtype: list
- """
- manifest.sort(key=lambda x: x["duration"])
- shift_len = self._rng.randint(0, batch_size - 1)
- batch_manifest = zip(*[iter(manifest[shift_len:])] * batch_size)
- self._rng.shuffle(batch_manifest)
- batch_manifest = [item for batch in batch_manifest for item in batch]
- if not clipped:
- res_len = len(manifest) - shift_len - len(batch_manifest)
- batch_manifest.extend(manifest[-res_len:])
- batch_manifest.extend(manifest[0:shift_len])
- return batch_manifest
diff --git a/deep_speech_2/data_utils/featurizer/__init__.py b/deep_speech_2/data_utils/featurizer/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/deep_speech_2/data_utils/featurizer/audio_featurizer.py b/deep_speech_2/data_utils/featurizer/audio_featurizer.py
deleted file mode 100644
index f594de7d9794354ed4a5afca25d70e85d658a828..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/featurizer/audio_featurizer.py
+++ /dev/null
@@ -1,187 +0,0 @@
-"""Contains the audio featurizer class."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-from data_utils.utility import read_manifest
-from data_utils.audio import AudioSegment
-from python_speech_features import mfcc
-from python_speech_features import delta
-
-
-class AudioFeaturizer(object):
- """Audio featurizer, for extracting features from audio contents of
- AudioSegment or SpeechSegment.
-
- Currently, it supports feature types of linear spectrogram and mfcc.
-
- :param specgram_type: Specgram feature type. Options: 'linear'.
- :type specgram_type: str
- :param stride_ms: Striding size (in milliseconds) for generating frames.
- :type stride_ms: float
- :param window_ms: Window size (in milliseconds) for generating frames.
- :type window_ms: float
- :param max_freq: When specgram_type is 'linear', only FFT bins
- corresponding to frequencies between [0, max_freq] are
- returned; when specgram_type is 'mfcc', max_feq is the
- highest band edge of mel filters.
- :types max_freq: None|float
- :param target_sample_rate: Audio are resampled (if upsampling or
- downsampling is allowed) to this before
- extracting spectrogram features.
- :type target_sample_rate: float
- :param use_dB_normalization: Whether to normalize the audio to a certain
- decibels before extracting the features.
- :type use_dB_normalization: bool
- :param target_dB: Target audio decibels for normalization.
- :type target_dB: float
- """
-
- def __init__(self,
- specgram_type='linear',
- stride_ms=10.0,
- window_ms=20.0,
- max_freq=None,
- target_sample_rate=16000,
- use_dB_normalization=True,
- target_dB=-20):
- self._specgram_type = specgram_type
- self._stride_ms = stride_ms
- self._window_ms = window_ms
- self._max_freq = max_freq
- self._target_sample_rate = target_sample_rate
- self._use_dB_normalization = use_dB_normalization
- self._target_dB = target_dB
-
- def featurize(self,
- audio_segment,
- allow_downsampling=True,
- allow_upsampling=True):
- """Extract audio features from AudioSegment or SpeechSegment.
-
- :param audio_segment: Audio/speech segment to extract features from.
- :type audio_segment: AudioSegment|SpeechSegment
- :param allow_downsampling: Whether to allow audio downsampling before
- featurizing.
- :type allow_downsampling: bool
- :param allow_upsampling: Whether to allow audio upsampling before
- featurizing.
- :type allow_upsampling: bool
- :return: Spectrogram audio feature in 2darray.
- :rtype: ndarray
- :raises ValueError: If audio sample rate is not supported.
- """
- # upsampling or downsampling
- if ((audio_segment.sample_rate > self._target_sample_rate and
- allow_downsampling) or
- (audio_segment.sample_rate < self._target_sample_rate and
- allow_upsampling)):
- audio_segment.resample(self._target_sample_rate)
- if audio_segment.sample_rate != self._target_sample_rate:
- raise ValueError("Audio sample rate is not supported. "
- "Turn allow_downsampling or allow up_sampling on.")
- # decibel normalization
- if self._use_dB_normalization:
- audio_segment.normalize(target_db=self._target_dB)
- # extract spectrogram
- return self._compute_specgram(audio_segment.samples,
- audio_segment.sample_rate)
-
- def _compute_specgram(self, samples, sample_rate):
- """Extract various audio features."""
- if self._specgram_type == 'linear':
- return self._compute_linear_specgram(
- samples, sample_rate, self._stride_ms, self._window_ms,
- self._max_freq)
- elif self._specgram_type == 'mfcc':
- return self._compute_mfcc(samples, sample_rate, self._stride_ms,
- self._window_ms, self._max_freq)
- else:
- raise ValueError("Unknown specgram_type %s. "
- "Supported values: linear." % self._specgram_type)
-
- def _compute_linear_specgram(self,
- samples,
- sample_rate,
- stride_ms=10.0,
- window_ms=20.0,
- max_freq=None,
- eps=1e-14):
- """Compute the linear spectrogram from FFT energy."""
- if max_freq is None:
- max_freq = sample_rate / 2
- if max_freq > sample_rate / 2:
- raise ValueError("max_freq must be greater than half of "
- "sample rate.")
- if stride_ms > window_ms:
- raise ValueError("Stride size must not be greater than "
- "window size.")
- stride_size = int(0.001 * sample_rate * stride_ms)
- window_size = int(0.001 * sample_rate * window_ms)
- specgram, freqs = self._specgram_real(
- samples,
- window_size=window_size,
- stride_size=stride_size,
- sample_rate=sample_rate)
- ind = np.where(freqs <= max_freq)[0][-1] + 1
- return np.log(specgram[:ind, :] + eps)
-
- def _specgram_real(self, samples, window_size, stride_size, sample_rate):
- """Compute the spectrogram for samples from a real signal."""
- # extract strided windows
- truncate_size = (len(samples) - window_size) % stride_size
- samples = samples[:len(samples) - truncate_size]
- nshape = (window_size, (len(samples) - window_size) // stride_size + 1)
- nstrides = (samples.strides[0], samples.strides[0] * stride_size)
- windows = np.lib.stride_tricks.as_strided(
- samples, shape=nshape, strides=nstrides)
- assert np.all(
- windows[:, 1] == samples[stride_size:(stride_size + window_size)])
- # window weighting, squared Fast Fourier Transform (fft), scaling
- weighting = np.hanning(window_size)[:, None]
- fft = np.fft.rfft(windows * weighting, axis=0)
- fft = np.absolute(fft)
- fft = fft**2
- scale = np.sum(weighting**2) * sample_rate
- fft[1:-1, :] *= (2.0 / scale)
- fft[(0, -1), :] /= scale
- # prepare fft frequency list
- freqs = float(sample_rate) / window_size * np.arange(fft.shape[0])
- return fft, freqs
-
- def _compute_mfcc(self,
- samples,
- sample_rate,
- stride_ms=10.0,
- window_ms=20.0,
- max_freq=None):
- """Compute mfcc from samples."""
- if max_freq is None:
- max_freq = sample_rate / 2
- if max_freq > sample_rate / 2:
- raise ValueError("max_freq must not be greater than half of "
- "sample rate.")
- if stride_ms > window_ms:
- raise ValueError("Stride size must not be greater than "
- "window size.")
- # compute the 13 cepstral coefficients, and the first one is replaced
- # by log(frame energy)
- mfcc_feat = mfcc(
- signal=samples,
- samplerate=sample_rate,
- winlen=0.001 * window_ms,
- winstep=0.001 * stride_ms,
- highfreq=max_freq)
- # Deltas
- d_mfcc_feat = delta(mfcc_feat, 2)
- # Deltas-Deltas
- dd_mfcc_feat = delta(d_mfcc_feat, 2)
- # transpose
- mfcc_feat = np.transpose(mfcc_feat)
- d_mfcc_feat = np.transpose(d_mfcc_feat)
- dd_mfcc_feat = np.transpose(dd_mfcc_feat)
- # concat above three features
- concat_mfcc_feat = np.concatenate(
- (mfcc_feat, d_mfcc_feat, dd_mfcc_feat))
- return concat_mfcc_feat
diff --git a/deep_speech_2/data_utils/featurizer/speech_featurizer.py b/deep_speech_2/data_utils/featurizer/speech_featurizer.py
deleted file mode 100644
index 4555dc31da89367b4775b712d3876168aae268f4..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/featurizer/speech_featurizer.py
+++ /dev/null
@@ -1,98 +0,0 @@
-"""Contains the speech featurizer class."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.featurizer.audio_featurizer import AudioFeaturizer
-from data_utils.featurizer.text_featurizer import TextFeaturizer
-
-
-class SpeechFeaturizer(object):
- """Speech featurizer, for extracting features from both audio and transcript
- contents of SpeechSegment.
-
- Currently, for audio parts, it supports feature types of linear
- spectrogram and mfcc; for transcript parts, it only supports char-level
- tokenizing and conversion into a list of token indices. Note that the
- token indexing order follows the given vocabulary file.
-
- :param vocab_filepath: Filepath to load vocabulary for token indices
- conversion.
- :type specgram_type: basestring
- :param specgram_type: Specgram feature type. Options: 'linear', 'mfcc'.
- :type specgram_type: str
- :param stride_ms: Striding size (in milliseconds) for generating frames.
- :type stride_ms: float
- :param window_ms: Window size (in milliseconds) for generating frames.
- :type window_ms: float
- :param max_freq: When specgram_type is 'linear', only FFT bins
- corresponding to frequencies between [0, max_freq] are
- returned; when specgram_type is 'mfcc', max_freq is the
- highest band edge of mel filters.
- :types max_freq: None|float
- :param target_sample_rate: Speech are resampled (if upsampling or
- downsampling is allowed) to this before
- extracting spectrogram features.
- :type target_sample_rate: float
- :param use_dB_normalization: Whether to normalize the audio to a certain
- decibels before extracting the features.
- :type use_dB_normalization: bool
- :param target_dB: Target audio decibels for normalization.
- :type target_dB: float
- """
-
- def __init__(self,
- vocab_filepath,
- specgram_type='linear',
- stride_ms=10.0,
- window_ms=20.0,
- max_freq=None,
- target_sample_rate=16000,
- use_dB_normalization=True,
- target_dB=-20):
- self._audio_featurizer = AudioFeaturizer(
- specgram_type=specgram_type,
- stride_ms=stride_ms,
- window_ms=window_ms,
- max_freq=max_freq,
- target_sample_rate=target_sample_rate,
- use_dB_normalization=use_dB_normalization,
- target_dB=target_dB)
- self._text_featurizer = TextFeaturizer(vocab_filepath)
-
- def featurize(self, speech_segment, keep_transcription_text):
- """Extract features for speech segment.
-
- 1. For audio parts, extract the audio features.
- 2. For transcript parts, keep the original text or convert text string
- to a list of token indices in char-level.
-
- :param audio_segment: Speech segment to extract features from.
- :type audio_segment: SpeechSegment
- :return: A tuple of 1) spectrogram audio feature in 2darray, 2) list of
- char-level token indices.
- :rtype: tuple
- """
- audio_feature = self._audio_featurizer.featurize(speech_segment)
- if keep_transcription_text:
- return audio_feature, speech_segment.transcript
- text_ids = self._text_featurizer.featurize(speech_segment.transcript)
- return audio_feature, text_ids
-
- @property
- def vocab_size(self):
- """Return the vocabulary size.
-
- :return: Vocabulary size.
- :rtype: int
- """
- return self._text_featurizer.vocab_size
-
- @property
- def vocab_list(self):
- """Return the vocabulary in list.
-
- :return: Vocabulary in list.
- :rtype: list
- """
- return self._text_featurizer.vocab_list
diff --git a/deep_speech_2/data_utils/featurizer/text_featurizer.py b/deep_speech_2/data_utils/featurizer/text_featurizer.py
deleted file mode 100644
index 89202163ca8d8b69f59b858db5451882d7e089b3..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/featurizer/text_featurizer.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""Contains the text featurizer class."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import os
-import codecs
-
-
-class TextFeaturizer(object):
- """Text featurizer, for processing or extracting features from text.
-
- Currently, it only supports char-level tokenizing and conversion into
- a list of token indices. Note that the token indexing order follows the
- given vocabulary file.
-
- :param vocab_filepath: Filepath to load vocabulary for token indices
- conversion.
- :type specgram_type: basestring
- """
-
- def __init__(self, vocab_filepath):
- self._vocab_dict, self._vocab_list = self._load_vocabulary_from_file(
- vocab_filepath)
-
- def featurize(self, text):
- """Convert text string to a list of token indices in char-level.Note
- that the token indexing order follows the given vocabulary file.
-
- :param text: Text to process.
- :type text: basestring
- :return: List of char-level token indices.
- :rtype: list
- """
- tokens = self._char_tokenize(text)
- return [self._vocab_dict[token] for token in tokens]
-
- @property
- def vocab_size(self):
- """Return the vocabulary size.
-
- :return: Vocabulary size.
- :rtype: int
- """
- return len(self._vocab_list)
-
- @property
- def vocab_list(self):
- """Return the vocabulary in list.
-
- :return: Vocabulary in list.
- :rtype: list
- """
- return self._vocab_list
-
- def _char_tokenize(self, text):
- """Character tokenizer."""
- return list(text.strip())
-
- def _load_vocabulary_from_file(self, vocab_filepath):
- """Load vocabulary from file."""
- vocab_lines = []
- with codecs.open(vocab_filepath, 'r', 'utf-8') as file:
- vocab_lines.extend(file.readlines())
- vocab_list = [line[:-1] for line in vocab_lines]
- vocab_dict = dict(
- [(token, id) for (id, token) in enumerate(vocab_list)])
- return vocab_dict, vocab_list
diff --git a/deep_speech_2/data_utils/normalizer.py b/deep_speech_2/data_utils/normalizer.py
deleted file mode 100644
index 7c2e05c9d85fa55c0a91386ebf9ba570b2ec0e3b..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/normalizer.py
+++ /dev/null
@@ -1,87 +0,0 @@
-"""Contains feature normalizers."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import numpy as np
-import random
-from data_utils.utility import read_manifest
-from data_utils.audio import AudioSegment
-
-
-class FeatureNormalizer(object):
- """Feature normalizer. Normalize features to be of zero mean and unit
- stddev.
-
- if mean_std_filepath is provided (not None), the normalizer will directly
- initilize from the file. Otherwise, both manifest_path and featurize_func
- should be given for on-the-fly mean and stddev computing.
-
- :param mean_std_filepath: File containing the pre-computed mean and stddev.
- :type mean_std_filepath: None|basestring
- :param manifest_path: Manifest of instances for computing mean and stddev.
- :type meanifest_path: None|basestring
- :param featurize_func: Function to extract features. It should be callable
- with ``featurize_func(audio_segment)``.
- :type featurize_func: None|callable
- :param num_samples: Number of random samples for computing mean and stddev.
- :type num_samples: int
- :param random_seed: Random seed for sampling instances.
- :type random_seed: int
- :raises ValueError: If both mean_std_filepath and manifest_path
- (or both mean_std_filepath and featurize_func) are None.
- """
-
- def __init__(self,
- mean_std_filepath,
- manifest_path=None,
- featurize_func=None,
- num_samples=500,
- random_seed=0):
- if not mean_std_filepath:
- if not (manifest_path and featurize_func):
- raise ValueError("If mean_std_filepath is None, meanifest_path "
- "and featurize_func should not be None.")
- self._rng = random.Random(random_seed)
- self._compute_mean_std(manifest_path, featurize_func, num_samples)
- else:
- self._read_mean_std_from_file(mean_std_filepath)
-
- def apply(self, features, eps=1e-14):
- """Normalize features to be of zero mean and unit stddev.
-
- :param features: Input features to be normalized.
- :type features: ndarray
- :param eps: added to stddev to provide numerical stablibity.
- :type eps: float
- :return: Normalized features.
- :rtype: ndarray
- """
- return (features - self._mean) / (self._std + eps)
-
- def write_to_file(self, filepath):
- """Write the mean and stddev to the file.
-
- :param filepath: File to write mean and stddev.
- :type filepath: basestring
- """
- np.savez(filepath, mean=self._mean, std=self._std)
-
- def _read_mean_std_from_file(self, filepath):
- """Load mean and std from file."""
- npzfile = np.load(filepath)
- self._mean = npzfile["mean"]
- self._std = npzfile["std"]
-
- def _compute_mean_std(self, manifest_path, featurize_func, num_samples):
- """Compute mean and std from randomly sampled instances."""
- manifest = read_manifest(manifest_path)
- sampled_manifest = self._rng.sample(manifest, num_samples)
- features = []
- for instance in sampled_manifest:
- features.append(
- featurize_func(
- AudioSegment.from_file(instance["audio_filepath"])))
- features = np.hstack(features)
- self._mean = np.mean(features, axis=1).reshape([-1, 1])
- self._std = np.std(features, axis=1).reshape([-1, 1])
diff --git a/deep_speech_2/data_utils/speech.py b/deep_speech_2/data_utils/speech.py
deleted file mode 100644
index 0cea887309d7c443a5dcdb3577ad897e6b36e209..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/speech.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""Contains the speech segment class."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from data_utils.audio import AudioSegment
-
-
-class SpeechSegment(AudioSegment):
- """Speech segment abstraction, a subclass of AudioSegment,
- with an additional transcript.
-
- :param samples: Audio samples [num_samples x num_channels].
- :type samples: ndarray.float32
- :param sample_rate: Audio sample rate.
- :type sample_rate: int
- :param transcript: Transcript text for the speech.
- :type transript: basestring
- :raises TypeError: If the sample data type is not float or int.
- """
-
- def __init__(self, samples, sample_rate, transcript):
- AudioSegment.__init__(self, samples, sample_rate)
- self._transcript = transcript
-
- def __eq__(self, other):
- """Return whether two objects are equal.
- """
- if not AudioSegment.__eq__(self, other):
- return False
- if self._transcript != other._transcript:
- return False
- return True
-
- def __ne__(self, other):
- """Return whether two objects are unequal."""
- return not self.__eq__(other)
-
- @classmethod
- def from_file(cls, filepath, transcript):
- """Create speech segment from audio file and corresponding transcript.
-
- :param filepath: Filepath or file object to audio file.
- :type filepath: basestring|file
- :param transcript: Transcript text for the speech.
- :type transript: basestring
- :return: Speech segment instance.
- :rtype: SpeechSegment
- """
- audio = AudioSegment.from_file(filepath)
- return cls(audio.samples, audio.sample_rate, transcript)
-
- @classmethod
- def from_bytes(cls, bytes, transcript):
- """Create speech segment from a byte string and corresponding
- transcript.
-
- :param bytes: Byte string containing audio samples.
- :type bytes: str
- :param transcript: Transcript text for the speech.
- :type transript: basestring
- :return: Speech segment instance.
- :rtype: Speech Segment
- """
- audio = AudioSegment.from_bytes(bytes)
- return cls(audio.samples, audio.sample_rate, transcript)
-
- @classmethod
- def concatenate(cls, *segments):
- """Concatenate an arbitrary number of speech segments together, both
- audio and transcript will be concatenated.
-
- :param *segments: Input speech segments to be concatenated.
- :type *segments: tuple of SpeechSegment
- :return: Speech segment instance.
- :rtype: SpeechSegment
- :raises ValueError: If the number of segments is zero, or if the
- sample_rate of any two segments does not match.
- :raises TypeError: If any segment is not SpeechSegment instance.
- """
- if len(segments) == 0:
- raise ValueError("No speech segments are given to concatenate.")
- sample_rate = segments[0]._sample_rate
- transcripts = ""
- for seg in segments:
- if sample_rate != seg._sample_rate:
- raise ValueError("Can't concatenate segments with "
- "different sample rates")
- if type(seg) is not cls:
- raise TypeError("Only speech segments of the same type "
- "instance can be concatenated.")
- transcripts += seg._transcript
- samples = np.concatenate([seg.samples for seg in segments])
- return cls(samples, sample_rate, transcripts)
-
- @classmethod
- def slice_from_file(cls, filepath, transcript, start=None, end=None):
- """Loads a small section of an speech without having to load
- the entire file into the memory which can be incredibly wasteful.
-
- :param filepath: Filepath or file object to audio file.
- :type filepath: basestring|file
- :param start: Start time in seconds. If start is negative, it wraps
- around from the end. If not provided, this function
- reads from the very beginning.
- :type start: float
- :param end: End time in seconds. If end is negative, it wraps around
- from the end. If not provided, the default behvaior is
- to read to the end of the file.
- :type end: float
- :param transcript: Transcript text for the speech. if not provided,
- the defaults is an empty string.
- :type transript: basestring
- :return: SpeechSegment instance of the specified slice of the input
- speech file.
- :rtype: SpeechSegment
- """
- audio = AudioSegment.slice_from_file(filepath, start, end)
- return cls(audio.samples, audio.sample_rate, transcript)
-
- @classmethod
- def make_silence(cls, duration, sample_rate):
- """Creates a silent speech segment of the given duration and
- sample rate, transcript will be an empty string.
-
- :param duration: Length of silence in seconds.
- :type duration: float
- :param sample_rate: Sample rate.
- :type sample_rate: float
- :return: Silence of the given duration.
- :rtype: SpeechSegment
- """
- audio = AudioSegment.make_silence(duration, sample_rate)
- return cls(audio.samples, audio.sample_rate, "")
-
- @property
- def transcript(self):
- """Return the transcript text.
-
- :return: Transcript text for the speech.
- :rtype: basestring
- """
- return self._transcript
diff --git a/deep_speech_2/data_utils/utility.py b/deep_speech_2/data_utils/utility.py
deleted file mode 100644
index bb5cad45bb2383e2125ec22181c9aedea8508eb0..0000000000000000000000000000000000000000
--- a/deep_speech_2/data_utils/utility.py
+++ /dev/null
@@ -1,181 +0,0 @@
-"""Contains data helper functions."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import json
-import codecs
-import os
-import tarfile
-import time
-from Queue import Queue
-from threading import Thread
-from multiprocessing import Process, Manager
-from paddle.v2.dataset.common import md5file
-
-
-def read_manifest(manifest_path, max_duration=float('inf'), min_duration=0.0):
- """Load and parse manifest file.
-
- Instances with durations outside [min_duration, max_duration] will be
- filtered out.
-
- :param manifest_path: Manifest file to load and parse.
- :type manifest_path: basestring
- :param max_duration: Maximal duration in seconds for instance filter.
- :type max_duration: float
- :param min_duration: Minimal duration in seconds for instance filter.
- :type min_duration: float
- :return: Manifest parsing results. List of dict.
- :rtype: list
- :raises IOError: If failed to parse the manifest.
- """
- manifest = []
- for json_line in codecs.open(manifest_path, 'r', 'utf-8'):
- try:
- json_data = json.loads(json_line)
- except Exception as e:
- raise IOError("Error reading manifest: %s" % str(e))
- if (json_data["duration"] <= max_duration and
- json_data["duration"] >= min_duration):
- manifest.append(json_data)
- return manifest
-
-
-def download(url, md5sum, target_dir):
- """Download file from url to target_dir, and check md5sum."""
- if not os.path.exists(target_dir): os.makedirs(target_dir)
- filepath = os.path.join(target_dir, url.split("/")[-1])
- if not (os.path.exists(filepath) and md5file(filepath) == md5sum):
- print("Downloading %s ..." % url)
- os.system("wget -c " + url + " -P " + target_dir)
- print("\nMD5 Chesksum %s ..." % filepath)
- if not md5file(filepath) == md5sum:
- raise RuntimeError("MD5 checksum failed.")
- else:
- print("File exists, skip downloading. (%s)" % filepath)
- return filepath
-
-
-def unpack(filepath, target_dir, rm_tar=False):
- """Unpack the file to the target_dir."""
- print("Unpacking %s ..." % filepath)
- tar = tarfile.open(filepath)
- tar.extractall(target_dir)
- tar.close()
- if rm_tar == True:
- os.remove(filepath)
-
-
-class XmapEndSignal():
- pass
-
-
-def xmap_readers_mp(mapper, reader, process_num, buffer_size, order=False):
- """A multiprocessing pipeline wrapper for the data reader.
-
- :param mapper: Function to map sample.
- :type mapper: callable
- :param reader: Given data reader.
- :type reader: callable
- :param process_num: Number of processes in the pipeline
- :type process_num: int
- :param buffer_size: Maximal buffer size.
- :type buffer_size: int
- :param order: Reserve the order of samples from the given reader.
- :type order: bool
- :return: The wrappered reader
- :rtype: callable
- """
- end_flag = XmapEndSignal()
-
- # define a worker to read samples from reader to in_queue
- def read_worker(reader, in_queue):
- for sample in reader():
- in_queue.put(sample)
- in_queue.put(end_flag)
-
- # define a worker to read samples from reader to in_queue with order flag
- def order_read_worker(reader, in_queue):
- for order_id, sample in enumerate(reader()):
- in_queue.put((order_id, sample))
- in_queue.put(end_flag)
-
- # define a worker to handle samples from in_queue by mapper and put results
- # to out_queue
- def handle_worker(in_queue, out_queue, mapper):
- sample = in_queue.get()
- while not isinstance(sample, XmapEndSignal):
- out_queue.put(mapper(sample))
- sample = in_queue.get()
- in_queue.put(end_flag)
- out_queue.put(end_flag)
-
- # define a worker to handle samples from in_queue by mapper and put results
- # to out_queue with order
- def order_handle_worker(in_queue, out_queue, mapper, out_order):
- ins = in_queue.get()
- while not isinstance(ins, XmapEndSignal):
- order_id, sample = ins
- result = mapper(sample)
- while order_id != out_order[0]:
- time.sleep(0.001)
- out_queue.put(result)
- out_order[0] += 1
- ins = in_queue.get()
- in_queue.put(end_flag)
- out_queue.put(end_flag)
-
- # define a thread worker to flush samples from Manager.Queue to Queue
- # for acceleration
- def flush_worker(in_queue, out_queue):
- finish = 0
- while finish < process_num:
- sample = in_queue.get()
- if isinstance(sample, XmapEndSignal):
- finish += 1
- else:
- out_queue.put(sample)
- out_queue.put(end_flag)
-
- def cleanup():
- # kill all sub process and threads
- os._exit(0)
-
- def xreader():
- # prepare shared memory
- manager = Manager()
- in_queue = manager.Queue(buffer_size)
- out_queue = manager.Queue(buffer_size)
- out_order = manager.list([0])
-
- # start a read worker in a process
- target = order_read_worker if order else read_worker
- p = Process(target=target, args=(reader, in_queue))
- p.daemon = True
- p.start()
-
- # start handle_workers with multiple processes
- target = order_handle_worker if order else handle_worker
- args = (in_queue, out_queue, mapper, out_order) if order else (
- in_queue, out_queue, mapper)
- workers = [
- Process(target=target, args=args) for _ in xrange(process_num)
- ]
- for w in workers:
- w.daemon = True
- w.start()
-
- # start a thread to read data from slow Manager.Queue
- flush_queue = Queue(buffer_size)
- t = Thread(target=flush_worker, args=(out_queue, flush_queue))
- t.daemon = True
- t.start()
-
- # get results
- sample = flush_queue.get()
- while not isinstance(sample, XmapEndSignal):
- yield sample
- sample = flush_queue.get()
-
- return xreader, cleanup
diff --git a/deep_speech_2/decoders/__init__.py b/deep_speech_2/decoders/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/deep_speech_2/decoders/decoders_deprecated.py b/deep_speech_2/decoders/decoders_deprecated.py
deleted file mode 100644
index 17b28b0d02a22a2e59856156ccd663324e886aed..0000000000000000000000000000000000000000
--- a/deep_speech_2/decoders/decoders_deprecated.py
+++ /dev/null
@@ -1,238 +0,0 @@
-"""Contains various CTC decoders."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-from itertools import groupby
-import numpy as np
-from math import log
-import multiprocessing
-
-
-def ctc_greedy_decoder(probs_seq, vocabulary):
- """CTC greedy (best path) decoder.
-
- Path consisting of the most probable tokens are further post-processed to
- remove consecutive repetitions and all blanks.
-
- :param probs_seq: 2-D list of probabilities over the vocabulary for each
- character. Each element is a list of float probabilities
- for one character.
- :type probs_seq: list
- :param vocabulary: Vocabulary list.
- :type vocabulary: list
- :return: Decoding result string.
- :rtype: baseline
- """
- # dimension verification
- for probs in probs_seq:
- if not len(probs) == len(vocabulary) + 1:
- raise ValueError("probs_seq dimension mismatchedd with vocabulary")
- # argmax to get the best index for each time step
- max_index_list = list(np.array(probs_seq).argmax(axis=1))
- # remove consecutive duplicate indexes
- index_list = [index_group[0] for index_group in groupby(max_index_list)]
- # remove blank indexes
- blank_index = len(vocabulary)
- index_list = [index for index in index_list if index != blank_index]
- # convert index list to string
- return ''.join([vocabulary[index] for index in index_list])
-
-
-def ctc_beam_search_decoder(probs_seq,
- beam_size,
- vocabulary,
- cutoff_prob=1.0,
- cutoff_top_n=40,
- ext_scoring_func=None,
- nproc=False):
- """CTC Beam search decoder.
-
- It utilizes beam search to approximately select top best decoding
- labels and returning results in the descending order.
- The implementation is based on Prefix Beam Search
- (https://arxiv.org/abs/1408.2873), and the unclear part is
- redesigned. Two important modifications: 1) in the iterative computation
- of probabilities, the assignment operation is changed to accumulation for
- one prefix may comes from different paths; 2) the if condition "if l^+ not
- in A_prev then" after probabilities' computation is deprecated for it is
- hard to understand and seems unnecessary.
-
- :param probs_seq: 2-D list of probability distributions over each time
- step, with each element being a list of normalized
- probabilities over vocabulary and blank.
- :type probs_seq: 2-D list
- :param beam_size: Width for beam search.
- :type beam_size: int
- :param vocabulary: Vocabulary list.
- :type vocabulary: list
- :param cutoff_prob: Cutoff probability in pruning,
- default 1.0, no pruning.
- :type cutoff_prob: float
- :param ext_scoring_func: External scoring function for
- partially decoded sentence, e.g. word count
- or language model.
- :type external_scoring_func: callable
- :param nproc: Whether the decoder used in multiprocesses.
- :type nproc: bool
- :return: List of tuples of log probability and sentence as decoding
- results, in descending order of the probability.
- :rtype: list
- """
- # dimension check
- for prob_list in probs_seq:
- if not len(prob_list) == len(vocabulary) + 1:
- raise ValueError("The shape of prob_seq does not match with the "
- "shape of the vocabulary.")
-
- # blank_id assign
- blank_id = len(vocabulary)
-
- # If the decoder called in the multiprocesses, then use the global scorer
- # instantiated in ctc_beam_search_decoder_batch().
- if nproc is True:
- global ext_nproc_scorer
- ext_scoring_func = ext_nproc_scorer
-
- ## initialize
- # prefix_set_prev: the set containing selected prefixes
- # probs_b_prev: prefixes' probability ending with blank in previous step
- # probs_nb_prev: prefixes' probability ending with non-blank in previous step
- prefix_set_prev = {'\t': 1.0}
- probs_b_prev, probs_nb_prev = {'\t': 1.0}, {'\t': 0.0}
-
- ## extend prefix in loop
- for time_step in xrange(len(probs_seq)):
- # prefix_set_next: the set containing candidate prefixes
- # probs_b_cur: prefixes' probability ending with blank in current step
- # probs_nb_cur: prefixes' probability ending with non-blank in current step
- prefix_set_next, probs_b_cur, probs_nb_cur = {}, {}, {}
-
- prob_idx = list(enumerate(probs_seq[time_step]))
- cutoff_len = len(prob_idx)
- #If pruning is enabled
- if cutoff_prob < 1.0 or cutoff_top_n < cutoff_len:
- prob_idx = sorted(prob_idx, key=lambda asd: asd[1], reverse=True)
- cutoff_len, cum_prob = 0, 0.0
- for i in xrange(len(prob_idx)):
- cum_prob += prob_idx[i][1]
- cutoff_len += 1
- if cum_prob >= cutoff_prob:
- break
- cutoff_len = min(cutoff_len, cutoff_top_n)
- prob_idx = prob_idx[0:cutoff_len]
-
- for l in prefix_set_prev:
- if not prefix_set_next.has_key(l):
- probs_b_cur[l], probs_nb_cur[l] = 0.0, 0.0
-
- # extend prefix by travering prob_idx
- for index in xrange(cutoff_len):
- c, prob_c = prob_idx[index][0], prob_idx[index][1]
-
- if c == blank_id:
- probs_b_cur[l] += prob_c * (
- probs_b_prev[l] + probs_nb_prev[l])
- else:
- last_char = l[-1]
- new_char = vocabulary[c]
- l_plus = l + new_char
- if not prefix_set_next.has_key(l_plus):
- probs_b_cur[l_plus], probs_nb_cur[l_plus] = 0.0, 0.0
-
- if new_char == last_char:
- probs_nb_cur[l_plus] += prob_c * probs_b_prev[l]
- probs_nb_cur[l] += prob_c * probs_nb_prev[l]
- elif new_char == ' ':
- if (ext_scoring_func is None) or (len(l) == 1):
- score = 1.0
- else:
- prefix = l[1:]
- score = ext_scoring_func(prefix)
- probs_nb_cur[l_plus] += score * prob_c * (
- probs_b_prev[l] + probs_nb_prev[l])
- else:
- probs_nb_cur[l_plus] += prob_c * (
- probs_b_prev[l] + probs_nb_prev[l])
- # add l_plus into prefix_set_next
- prefix_set_next[l_plus] = probs_nb_cur[
- l_plus] + probs_b_cur[l_plus]
- # add l into prefix_set_next
- prefix_set_next[l] = probs_b_cur[l] + probs_nb_cur[l]
- # update probs
- probs_b_prev, probs_nb_prev = probs_b_cur, probs_nb_cur
-
- ## store top beam_size prefixes
- prefix_set_prev = sorted(
- prefix_set_next.iteritems(), key=lambda asd: asd[1], reverse=True)
- if beam_size < len(prefix_set_prev):
- prefix_set_prev = prefix_set_prev[:beam_size]
- prefix_set_prev = dict(prefix_set_prev)
-
- beam_result = []
- for seq, prob in prefix_set_prev.items():
- if prob > 0.0 and len(seq) > 1:
- result = seq[1:]
- # score last word by external scorer
- if (ext_scoring_func is not None) and (result[-1] != ' '):
- prob = prob * ext_scoring_func(result)
- log_prob = log(prob)
- beam_result.append((log_prob, result))
- else:
- beam_result.append((float('-inf'), ''))
-
- ## output top beam_size decoding results
- beam_result = sorted(beam_result, key=lambda asd: asd[0], reverse=True)
- return beam_result
-
-
-def ctc_beam_search_decoder_batch(probs_split,
- beam_size,
- vocabulary,
- num_processes,
- cutoff_prob=1.0,
- cutoff_top_n=40,
- ext_scoring_func=None):
- """CTC beam search decoder using multiple processes.
-
- :param probs_seq: 3-D list with each element as an instance of 2-D list
- of probabilities used by ctc_beam_search_decoder().
- :type probs_seq: 3-D list
- :param beam_size: Width for beam search.
- :type beam_size: int
- :param vocabulary: Vocabulary list.
- :type vocabulary: list
- :param num_processes: Number of parallel processes.
- :type num_processes: int
- :param cutoff_prob: Cutoff probability in pruning,
- default 1.0, no pruning.
- :type cutoff_prob: float
- :param num_processes: Number of parallel processes.
- :type num_processes: int
- :param ext_scoring_func: External scoring function for
- partially decoded sentence, e.g. word count
- or language model.
- :type external_scoring_function: callable
- :return: List of tuples of log probability and sentence as decoding
- results, in descending order of the probability.
- :rtype: list
- """
- if not num_processes > 0:
- raise ValueError("Number of processes must be positive!")
-
- # use global variable to pass the externnal scorer to beam search decoder
- global ext_nproc_scorer
- ext_nproc_scorer = ext_scoring_func
- nproc = True
-
- pool = multiprocessing.Pool(processes=num_processes)
- results = []
- for i, probs_list in enumerate(probs_split):
- args = (probs_list, beam_size, vocabulary, cutoff_prob, cutoff_top_n,
- None, nproc)
- results.append(pool.apply_async(ctc_beam_search_decoder, args))
-
- pool.close()
- pool.join()
- beam_search_results = [result.get() for result in results]
- return beam_search_results
diff --git a/deep_speech_2/decoders/scorer_deprecated.py b/deep_speech_2/decoders/scorer_deprecated.py
deleted file mode 100644
index c6a661030d4363727e259da9c7949e59705d55c8..0000000000000000000000000000000000000000
--- a/deep_speech_2/decoders/scorer_deprecated.py
+++ /dev/null
@@ -1,68 +0,0 @@
-"""External Scorer for Beam Search Decoder."""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import os
-import kenlm
-import numpy as np
-
-
-class Scorer(object):
- """External scorer to evaluate a prefix or whole sentence in
- beam search decoding, including the score from n-gram language
- model and word count.
-
- :param alpha: Parameter associated with language model. Don't use
- language model when alpha = 0.
- :type alpha: float
- :param beta: Parameter associated with word count. Don't use word
- count when beta = 0.
- :type beta: float
- :model_path: Path to load language model.
- :type model_path: basestring
- """
-
- def __init__(self, alpha, beta, model_path):
- self._alpha = alpha
- self._beta = beta
- if not os.path.isfile(model_path):
- raise IOError("Invaid language model path: %s" % model_path)
- self._language_model = kenlm.LanguageModel(model_path)
-
- # n-gram language model scoring
- def _language_model_score(self, sentence):
- #log10 prob of last word
- log_cond_prob = list(
- self._language_model.full_scores(sentence, eos=False))[-1][0]
- return np.power(10, log_cond_prob)
-
- # word insertion term
- def _word_count(self, sentence):
- words = sentence.strip().split(' ')
- return len(words)
-
- # reset alpha and beta
- def reset_params(self, alpha, beta):
- self._alpha = alpha
- self._beta = beta
-
- # execute evaluation
- def __call__(self, sentence, log=False):
- """Evaluation function, gathering all the different scores
- and return the final one.
-
- :param sentence: The input sentence for evalutation
- :type sentence: basestring
- :param log: Whether return the score in log representation.
- :type log: bool
- :return: Evaluation score, in the decimal or log.
- :rtype: float
- """
- lm = self._language_model_score(sentence)
- word_cnt = self._word_count(sentence)
- if log == False:
- score = np.power(lm, self._alpha) * np.power(word_cnt, self._beta)
- else:
- score = self._alpha * np.log(lm) + self._beta * np.log(word_cnt)
- return score
diff --git a/deep_speech_2/decoders/swig/__init__.py b/deep_speech_2/decoders/swig/__init__.py
deleted file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000
diff --git a/deep_speech_2/decoders/swig/_init_paths.py b/deep_speech_2/decoders/swig/_init_paths.py
deleted file mode 100644
index ddabb535be682d95c3c8b73003ea30eed06ca0b0..0000000000000000000000000000000000000000
--- a/deep_speech_2/decoders/swig/_init_paths.py
+++ /dev/null
@@ -1,19 +0,0 @@
-"""Set up paths for DS2"""
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import os.path
-import sys
-
-
-def add_path(path):
- if path not in sys.path:
- sys.path.insert(0, path)
-
-
-this_dir = os.path.dirname(__file__)
-
-# Add project path to PYTHONPATH
-proj_path = os.path.join(this_dir, '..')
-add_path(proj_path)
diff --git a/deep_speech_2/decoders/swig/ctc_beam_search_decoder.cpp b/deep_speech_2/decoders/swig/ctc_beam_search_decoder.cpp
deleted file mode 100644
index 4a63af26af5e2da135f75386581fbe61f56c7fc7..0000000000000000000000000000000000000000
--- a/deep_speech_2/decoders/swig/ctc_beam_search_decoder.cpp
+++ /dev/null
@@ -1,222 +0,0 @@
-#include "ctc_beam_search_decoder.h"
-
-#include
-#include
-#include
-#include
-#include