Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 95 additions & 51 deletions tutorials/tools/CTC_Segmentation_Tutorial.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,6 @@
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "JDk9zxC6pdod"
},
"outputs": [],
"source": [
"import os\n",
"# either provide a path to local NeMo repository with NeMo already installed or git clone\n",
Expand All @@ -40,28 +35,56 @@
" ! git clone -b $BRANCH https://github.com/NVIDIA/NeMo\n",
" ! cd NeMo\n",
" ! python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]"
]
],
"metadata": {
"id": "6DGWYSp62hs1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# install reqs for this notebook\n",
"!python -m pip install --no-cache-dir -r \"{NEMO_DIR_PATH}/tools/ctc_segmentation/requirements.txt\""
],
"metadata": {
"id": "CH7yR7cSwPKr"
"id": "73jaO-HZ4b_5"
},
"outputs": [],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"import json\n",
"import os\n",
"import wget\n",
"\n",
"from IPython.display import Audio\n",
"import numpy as np\n",
"import scipy.io.wavfile as wav\n",
"import scipy\n",
"import soundfile as sf\n",
"\n",
"! pip install pandas\n",
"! pip install plotly\n",
"from plotly import graph_objects as go"
]
"\n",
"from plotly import graph_objects as go\n"
],
"metadata": {
"id": "WFvmiWv02jr2"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"!apt-get install sox libsox-fmt-mp3"
],
"metadata": {
"id": "JbdAPFb99Mff"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
Expand All @@ -70,28 +93,13 @@
},
"source": [
"# 1. Introduction\n",
"End-to-end Automatic Speech Recognition (ASR) systems surpassed traditional systems in performance but require large amounts of labeled data for training. \n",
"End-to-end Automatic Speech Recognition (ASR) systems surpassed traditional systems in performance but require large amounts of labeled data for training.\n",
"\n",
"This tutorial will show how to use a pre-trained with Connectionist Temporal Classification (CTC) ASR model, such as [QuartzNet Model](https://arxiv.org/abs/1910.10261) or [Citrinet](https://arxiv.org/abs/2104.01721) to split long audio files and the corresponding transcripts into shorter fragments that are suitable for an ASR model training. \n",
"This tutorial will show how to use a pre-trained with Connectionist Temporal Classification (CTC) ASR model, such as [QuartzNet Model](https://arxiv.org/abs/1910.10261) or [Citrinet](https://arxiv.org/abs/2104.01721) to split long audio files and the corresponding transcripts into shorter fragments that are suitable for an ASR model training.\n",
"\n",
"We're going to use [ctc-segmentation](https://github.com/lumaku/ctc-segmentation) Python package based on the algorithm described in [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "8FAZKakrIyGI"
},
"outputs": [],
"source": [
"requirements = f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/tools/ctc_segmentation/requirements.txt'\n",
"wget.download(requirements)\n",
"! pip install -r requirements.txt\n",
"! apt-get install -y ffmpeg\n",
"! apt-get install -y libsox-fmt-mp3 "
]
},
{
"cell_type": "markdown",
"metadata": {
Expand All @@ -113,7 +121,7 @@
" NEMO_DIR_PATH = \"/content/NeMo\"\n",
"elif not os.path.exists(NEMO_DIR_PATH):\n",
" NEMO_DIR_PATH = \"NeMo\"\n",
" \n",
"\n",
"TOOLS_DIR = f'{NEMO_DIR_PATH}/tools/ctc_segmentation/scripts'\n",
"print(TOOLS_DIR)\n",
"! ls -l $TOOLS_DIR"
Expand Down Expand Up @@ -250,7 +258,7 @@
"* the text will be roughly split into sentences and stored under '$OUTPUT_DIR/processed/*.txt' where each sentence is going to start with a new line (we're going to find alignments for these sentences in the next steps)\n",
"* to change the lengths of the final sentences/fragments, specify additional punctuation marks to split the text into fragments, use `--additional_split_symbols` argument. Use `|` as a separator between symbols, for example: `--additional_split_symbols=;|:`\n",
"* `max_length` argument - max number of words in a segment for alignment (used only if there are no punctuation marks present in the original text. Long non-speech segments are better for segments split and are more likely to co-occur with punctuation marks. Random text split could deteriorate the quality of the alignment.\n",
"* out-of-vocabulary words will be removed based on pre-trained ASR model vocabulary, and the text will be changed to lowercase \n",
"* out-of-vocabulary words will be removed based on pre-trained ASR model vocabulary, and the text will be changed to lowercase\n",
"* sentences for alignment with the original punctuation and capitalization will be stored under `$OUTPUT_DIR/processed/*_with_punct.txt`\n",
"* numbers will be converted from written to their spoken form with `num2words` package. For English, it's recommended to use NeMo normalization tool use `--use_nemo_normalization` argument (not supported if running this segmentation tutorial in Colab, see the text normalization tutorial: [`https://github.com/NVIDIA/NeMo-text-processing/blob/main/tutorials/Text_(Inverse)_Normalization.ipynb`](https://colab.research.google.com/github/NVIDIA/NeMo-text-processing/blob/main/tutorials/Text_(Inverse)_Normalization.ipynb) for more details). Even `num2words` normalization is usually enough for proper segmentation. However, it does not take audio into account. NeMo supports audio-based normalization for English, German and Russian languages that can be applied to the segmented data as a post-processing step. Audio-based normalization produces multiple normalization options. For example, `901` could be normalized as `nine zero one` or `nine hundred and one`. The audio-based normalization chooses the best match among the possible normalization options and the transcript based on the character error rate. See [https://github.com/NVIDIA/NeMo-text-processing/blob/main/nemo_text_processing/text_normalization/normalize_with_audio.py](https://github.com/NVIDIA/NeMo-text-processing/blob/main/nemo_text_processing/text_normalization/normalize_with_audio.py) for more details.\n",
"\n",
Expand All @@ -274,12 +282,13 @@
},
"outputs": [],
"source": [
"MODEL = \"stt_es_citrinet_512\" \n",
"import sys\n",
"MODEL = \"stt_es_citrinet_512\"\n",
"OUTPUT_DIR = WORK_DIR + \"/es_output\"\n",
"\n",
"! rm -rf $OUTPUT_DIR\n",
"\n",
"! python $TOOLS_DIR/prepare_data.py \\\n",
"!{sys.executable} $TOOLS_DIR/prepare_data.py \\\n",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why this change? Can we keep python?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, this was done because I've tested it in colab, and seems that something is messing up with just python. Same in other places.

"--in_text=$DATA_DIR/es/text \\\n",
"--output_dir=$OUTPUT_DIR/processed/ \\\n",
"--language='en' \\\n",
Expand Down Expand Up @@ -343,7 +352,7 @@
"In this step, we're going to use the [`ctc-segmentation`](https://github.com/lumaku/ctc-segmentation) to find the start and end time stamps for the segments we created during the previous step.\n",
"\n",
"\n",
"As described in the [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf), the algorithm is relying on a CTC-based ASR model to extract utterance segments with exact time-wise alignments. "
"As described in the [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf), the algorithm is relying on a CTC-based ASR model to extract utterance segments with exact time-wise alignments."
]
},
{
Expand All @@ -354,13 +363,14 @@
},
"outputs": [],
"source": [
"import sys\n",
"WINDOW = 8000\n",
"\n",
"! python $TOOLS_DIR/run_ctc_segmentation.py \\\n",
"!{sys.executable} $TOOLS_DIR/run_ctc_segmentation.py \\\n",
"--output_dir=$OUTPUT_DIR \\\n",
"--data=$OUTPUT_DIR/processed \\\n",
"--model=$MODEL \\\n",
"--window_len=$WINDOW "
"--window_len=$WINDOW"
]
},
{
Expand All @@ -369,7 +379,7 @@
"id": "wY27__e3HmhH"
},
"source": [
"`WINDOW` parameter might need to be adjusted depending on the length of the utterance one wants to align, the default value should work in most cases. By default, if the alignment is not found for the initial `WINDOW` size, the window size will be doubled a few times to re-try backtracing. \n",
"`WINDOW` parameter might need to be adjusted depending on the length of the utterance one wants to align, the default value should work in most cases. By default, if the alignment is not found for the initial `WINDOW` size, the window size will be doubled a few times to re-try backtracing.\n",
"\n",
"Let's take a look at the generated alignments."
]
Expand Down Expand Up @@ -414,7 +424,7 @@
"Finally, we're going to split the original audio file into segments based on the found alignments. We're going to save only segments with alignment score above the threshold value (default threshold=-2:\n",
"* high scored clips (segments with the segmentation score above the threshold value)\n",
"* low scored clips (segments with the segmentation score below the threshold)\n",
"* deleted segments (segments that were excluded during the alignment. For example, in our sample audio file, the prologue and epilogue that don't have the corresponding transcript were excluded. Oftentimes, deleted files also contain such things as clapping, music, or hard breathing. \n",
"* deleted segments (segments that were excluded during the alignment. For example, in our sample audio file, the prologue and epilogue that don't have the corresponding transcript were excluded. Oftentimes, deleted files also contain such things as clapping, music, or hard breathing.\n",
"\n",
"The alignment score values depend on the pre-trained model quality and the dataset.\n",
"\n",
Expand All @@ -429,10 +439,11 @@
},
"outputs": [],
"source": [
"import sys\n",
"OFFSET = 0\n",
"THRESHOLD = -2\n",
"\n",
"! python $TOOLS_DIR/cut_audio.py \\\n",
"!{sys.executable} $TOOLS_DIR/cut_audio.py \\\n",
"--output_dir=$OUTPUT_DIR \\\n",
"--alignment=$OUTPUT_DIR/segments/ \\\n",
"--threshold=$THRESHOLD \\\n",
Expand All @@ -458,9 +469,10 @@
},
"outputs": [],
"source": [
"import sys\n",
"wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/asr/transcribe_speech.py')\n",
"\n",
"! python transcribe_speech.py \\\n",
"!{sys.executable} transcribe_speech.py \\\n",
"pretrained_name=$MODEL \\\n",
"dataset_manifest=$OUTPUT_DIR/manifests/manifest.json \\\n",
"output_filename=$OUTPUT_DIR/manifests/manifest_transcribed.json"
Expand All @@ -474,6 +486,8 @@
},
"outputs": [],
"source": [
"import soundfile as sf\n",
"\n",
"def plot_signal(signal, sample_rate):\n",
" \"\"\" Plot the signal in time domain \"\"\"\n",
" fig_signal = go.Figure(\n",
Expand All @@ -490,13 +504,16 @@
" }\n",
" )\n",
" fig_signal.show()\n",
" \n",
"\n",
"def display_samples(manifest):\n",
" \"\"\" Display audio and reference text.\"\"\"\n",
" with open(manifest, 'r') as f:\n",
" for line in f:\n",
" sample = json.loads(line)\n",
" sample_rate, signal = wav.read(sample['audio_filepath'])\n",
"\n",
"\n",
" signal, sample_rate = sf.read(sample['audio_filepath'])\n",
"\n",
" plot_signal(signal, sample_rate)\n",
" display(Audio(sample['audio_filepath']))\n",
" display('Reference text: ' + sample['text_no_preprocessing'])\n",
Expand Down Expand Up @@ -541,7 +558,7 @@
"source": [
"# 4. Processing of multiple files (English samples)\n",
"\n",
"Up until now, we were processing only one file at a time, but to create a large dataset processing of multiple files simultaneously could help speed up things considerably. \n",
"Up until now, we were processing only one file at a time, but to create a large dataset processing of multiple files simultaneously could help speed up things considerably.\n",
"\n",
"Our English data folder contains 2 audio files and corresponding text files:"
]
Expand Down Expand Up @@ -596,6 +613,17 @@
"`run_segmentation.sh` could use multiple `WINDOW` sizes for segmentation, and then adds segments that were similarly aligned with various window sizes to `verified_segments` folder. This could be useful to reduce the amount of manual work while checking the alignment quality."
]
},
{
"cell_type": "code",
"source": [
"!pip install sox"
],
"metadata": {
"id": "TijPmstX9x4W"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"execution_count": null,
Expand All @@ -604,7 +632,10 @@
},
"outputs": [],
"source": [
"MODEL = \"QuartzNet15x5Base-En\" # \"stt_en_citrinet_512_gamma_0_25\" \n",
"if 'google.colab' in str(get_ipython()):\n",
" !sudo ln -s /usr/local/bin/python /usr/local/bin/ctc_segmentation #for comatability with run_segmentation.sh\n",
"\n",
"MODEL = \"QuartzNet15x5Base-En\" # \"stt_en_citrinet_512_gamma_0_25\"\n",
"OUTPUT_DIR_2 = WORK_DIR + \"/en_output\"\n",
"\n",
"! rm -rf $OUTPUT_DIR_2\n",
Expand All @@ -618,6 +649,13 @@
"--USE_NEMO_NORMALIZATION=False"
]
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"id": "9qgq9m6Fyp-1"
}
},
{
"cell_type": "markdown",
"metadata": {
Expand Down Expand Up @@ -684,16 +722,22 @@
"# References\n",
"Kürzinger, Ludwig, et al. [\"CTC-Segmentation of Large Corpora for German End-to-End Speech Recognition.\"](https://arxiv.org/abs/2007.09127) International Conference on Speech and Computer. Springer, Cham, 2020."
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "i_dk6NJA3Vre"
},
"execution_count": null,
"outputs": []
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
"name": "CTC_Segmentation_Tutorial_update.ipynb",
"private_outputs": true,
"provenance": [],
"toc_visible": true
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
Expand All @@ -715,4 +759,4 @@
},
"nbformat": 4,
"nbformat_minor": 0
}
}
Loading