chore: import upstream snapshot with attribution
Create PR to main with cherry-pick from release / cherry-pick (push) Failing after 0s
CICD NeMo / pre-flight (push) Failing after 0s
CICD NeMo / configure (push) Has been skipped
Build, validate, and release Neural Modules / pre-flight (push) Failing after 1s
CICD NeMo / code-linting (push) Has been skipped
Build, validate, and release Neural Modules / release (push) Has been skipped
Build, validate, and release Neural Modules / release-summary (push) Has been cancelled
CICD NeMo / cicd-test-container-build (push) Has been cancelled
CICD NeMo / cicd-import-tests (push) Has been cancelled
CICD NeMo / L0_Setup_Test_Data_And_Models (push) Has been cancelled
CICD NeMo / cicd-main-unit-tests (push) Has been cancelled
CICD NeMo / cicd-main-speech (push) Has been cancelled
CICD NeMo / Nemo_CICD_Test (push) Has been cancelled
CICD NeMo / Coverage (e2e) (push) Has been cancelled
CICD NeMo / Coverage (unit-test) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
CICD NeMo / cicd-wait-in-queue (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:28:58 +08:00
commit ba4be087d5
2316 changed files with 2668701 additions and 0 deletions
@@ -0,0 +1,762 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "d4KCUoxSpdoZ"
},
"outputs": [],
"source": [
"BRANCH = 'main'\n",
"\n",
"\"\"\"\n",
"You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
"\n",
"Instructions for setting up Colab are as follows:\n",
"1. Open a new Python 3 notebook.\n",
"2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
"3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
"4. Run this cell to set up dependencies.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"source": [
"import os\n",
"# either provide a path to local NeMo repository with NeMo already installed or git clone\n",
"\n",
"# option #1: local path to NeMo repo with NeMo already installed\n",
"NEMO_DIR_PATH = \"NeMo\"\n",
"\n",
"# option #2: download NeMo repo\n",
"if 'google.colab' in str(get_ipython()) or not os.path.exists(NEMO_DIR_PATH):\n",
" ! git clone -b $BRANCH https://github.com/NVIDIA-NeMo/Speech\n",
" ! cd NeMo\n",
" ! python -m pip install \"nemo_toolkit[all] @ git+https://github.com/NVIDIA-NeMo/Speech.git@$BRANCH\""
],
"metadata": {
"id": "6DGWYSp62hs1"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"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": "73jaO-HZ4b_5"
},
"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\n",
"import soundfile as sf\n",
"\n",
"\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",
"metadata": {
"id": "xXRARM8XtK_g"
},
"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",
"\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": "markdown",
"metadata": {
"id": "S1DZk-inQGTI"
},
"source": [
"`TOOLS_DIR` contains scripts that we are going to need during the next steps, all necessary scripts could be found [here](https://github.com/NVIDIA/NeMo/tree/main/tools/ctc_segmentation/scripts)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1C9DdMfvRFM-"
},
"outputs": [],
"source": [
"if 'google.colab' in str(get_ipython()):\n",
" NEMO_DIR_PATH = \"/content/NeMo\"\n",
"elif not os.path.exists(NEMO_DIR_PATH):\n",
" NEMO_DIR_PATH = \"NeMo\"\n",
"\n",
"TOOLS_DIR = f'{NEMO_DIR_PATH}/tools/ctc_segmentation/scripts'\n",
"print(TOOLS_DIR)\n",
"! ls -l $TOOLS_DIR"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XUEncnqTIzF6"
},
"source": [
"# 2. Data Download\n",
"First, let's download audio and text data (data source: [https://librivox.org/](https://librivox.org/) and [http://www.gutenberg.org](http://www.gutenberg.org)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bkeKX2I_tIgV"
},
"outputs": [],
"source": [
"## create data directory and download an audio file\n",
"WORK_DIR = 'WORK_DIR'\n",
"DATA_DIR = WORK_DIR + '/DATA'\n",
"os.makedirs(DATA_DIR, exist_ok=True)\n",
"\n",
"print('downloading audio samples...')\n",
"wget.download(\"https://multilangaudiosamples.s3.us-east-2.amazonaws.com/audio_samples.zip\", DATA_DIR)\n",
"! unzip -o $DATA_DIR/audio_samples.zip -d $DATA_DIR\n",
"! rm $DATA_DIR/audio_samples.zip\n",
"\n",
"DATA_DIR = os.path.join(DATA_DIR, \"audio_samples\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2JAv7ePmpdok"
},
"source": [
"We downloaded audio and text samples in `English` and `Spanish`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Y6VYVk9mpdol"
},
"outputs": [],
"source": [
"! ls $DATA_DIR"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-_XE9MkKuAA7"
},
"source": [
"Data folder for each language contains both audio and text files. Note, the text file and the audio file share the same base name. For example, an audio file `example.wav` should have a corresponding text file called `example.txt`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IGhijb-Bpdol"
},
"outputs": [],
"source": [
"! ls $DATA_DIR/es/audio/ $DATA_DIR/es/text/"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FWqlbSryw_WL"
},
"source": [
"# 3. Segmentation of a single file (Spanish sample)\n",
"\n",
"Let's listen to our Spanish audio sample:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ulkPrqwipdom"
},
"outputs": [],
"source": [
"base_name_es = \"el19demarzoyel2demayo_03_perezgaldos\"\n",
"Audio(f\"{DATA_DIR}/es/audio/{base_name_es}.wav\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RzlLsmMXpdom"
},
"source": [
"Let's take a look at the ground truth text:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "9Qfp10Xnpdom"
},
"outputs": [],
"source": [
"text = f\"{DATA_DIR}/es/text/{base_name_es}.txt\"\n",
"! cat $text"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RMT5lkPYzZHK"
},
"source": [
"As one probably noticed, the audio file contains a prologue and an epilogue that are missing in the corresponding text. The segmentation algorithm could handle extra audio fragments at the end and the beginning of the audio, but prolonged untranscribed audio segments in the middle of the file could deteriorate segmentation results. That is why, it is recommended to normalize text, so that transcripts contain spoken equivalents of abbreviations and numbers.\n",
"\n",
"## 3.1. Prepare Text and Audio\n",
"\n",
"We're going to use `prepare_data.py` script to prepare both text and audio data for segmentation.\n",
"\n",
"### Text preprocessing:\n",
"* 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",
"* 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",
"### Audio preprocessing:\n",
"* non '.wav' audio files will be converted to `.wav` format\n",
"* audio files will be resampled to 16kHz (sampling rate used during training NeMo ASR models)\n",
"* stereo tracks will be converted to mono\n",
"* In some cases, if an audio contains a very long untranscribed prologue, increasing `--cut_prefix` value might help improve segmentation quality.\n",
"\n",
"\n",
"The `prepare_data.py` will preprocess all `.txt` files found in the `--in_text=$DATA_DIR` and all audio files located at `--audio_dir=$DATA_DIR`.\n",
"\n",
"We are going to use [Spanish Citrinet-512 model](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_es_citrinet_512)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "u4zjeVVv-UXR"
},
"outputs": [],
"source": [
"import sys\n",
"MODEL = \"stt_es_citrinet_512\"\n",
"OUTPUT_DIR = WORK_DIR + \"/es_output\"\n",
"\n",
"! rm -rf $OUTPUT_DIR\n",
"\n",
"!{sys.executable} $TOOLS_DIR/prepare_data.py \\\n",
"--in_text=$DATA_DIR/es/text \\\n",
"--output_dir=$OUTPUT_DIR/processed/ \\\n",
"--language='en' \\\n",
"--model=$MODEL \\\n",
"--audio_dir=$DATA_DIR/es/audio"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kmDTCuTLH7pm"
},
"source": [
"The following four files should be generated and stored at the `$OUTPUT_DIR/processed` folder:\n",
"\n",
"* el19demarzoyel2demayo_03_perezgaldos.txt (lower cased and normalized text with punctuation removed, each line represents an utterance for alignment)\n",
"* el19demarzoyel2demayo_03_perezgaldos.wav (.wav mono file, 16kHz)\n",
"* el19demarzoyel2demayo_03_perezgaldos_with_punct.txt (raw utterances for alignment with punctuation and case preserved)\n",
"* el19demarzoyel2demayo_03_perezgaldos_with_punct_normalized.txt (normalized utterances for alignment utterance for alignment with punctuation and case preserved)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6R7OKAsYH9p0"
},
"outputs": [],
"source": [
"! ls $OUTPUT_DIR/processed"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bIvKBwRcH_9W"
},
"source": [
"The `.txt` file without punctuation contains preprocessed text phrases that we're going to align within the audio file. Here, we split the text into sentences. Each line should contain a text snippet for alignment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "74GLpMgoICmk"
},
"outputs": [],
"source": [
"! head $OUTPUT_DIR/processed/el19demarzoyel2demayo_03_perezgaldos.txt"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QrvZAjeoR9U1"
},
"source": [
"## 3.2. Run CTC-Segmentation\n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xyKtaqAd-Tvk"
},
"outputs": [],
"source": [
"import sys\n",
"WINDOW = 8000\n",
"\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"
]
},
{
"cell_type": "markdown",
"metadata": {
"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",
"\n",
"Let's take a look at the generated alignments."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ktBAsfJRVCwI"
},
"outputs": [],
"source": [
"alignment_file = f\"{WINDOW}_{base_name_es}_segments.txt\"\n",
"! head -n 3 $OUTPUT_DIR/segments/$alignment_file"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xCwEFefHZz1C"
},
"source": [
"The expected output for our audio sample looks like this:\n",
"\n",
"```\n",
"<PATH_TO>/processed/el19demarzoyel2demayo_03_perezgaldos.wav\n",
"11.518331881862931 25.916246734191596 -1.2629864680237006 | entraron en la habitación donde estábamos y al punto que d mauro vio a su sobrina dirigiose a ella con los brazos abiertos y al estrecharla en ellos exclamó endulzando la voz ¡inés de mi alma inocente hija de mi prima juana | Entraron en la habitación donde estábamos, y al punto que D. Mauro vio a su sobrina dirigiose a ella con los brazos abiertos, y al estrecharla en ellos, exclamó endulzando la voz: -¡Inés de mi alma, inocente hija de mi prima Juana! | Entraron en la habitación donde estábamos, y al punto que D. Mauro vio a su sobrina dirigiose a ella con los brazos abiertos, y al estrecharla en ellos, exclamó endulzando la voz: - Inés de mi alma, inocente hija de mi prima Juana!\n",
"25.756269902499053 28.155922377887165 -0.0003830735786323203 | al fin al fin te veo | Al fin, al fin te veo. | Al fin, al fin te veo.\n",
"...\n",
"```\n",
"\n",
"**Details of the file content**:\n",
"- the first line of the file contains the path to the original audio file\n",
"- all subsequent lines contain:\n",
" * the first number is the start of the segment (in seconds)\n",
" * the second one is the end of the segment (in seconds)\n",
" * the third value - alignment confidence score (in log space)\n",
" * text fragments corresponding to the timestamps\n",
" * original text without pre-processing\n",
" * normalized text\n",
"\n",
"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",
"\n",
"The alignment score values depend on the pre-trained model quality and the dataset.\n",
"\n",
"Also note, that the `OFFSET` parameter is something one might want to experiment with since timestamps have a delay (offset) depending on the model.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "6YM64RPlitPL"
},
"outputs": [],
"source": [
"import sys\n",
"OFFSET = 0\n",
"THRESHOLD = -2\n",
"\n",
"!{sys.executable} $TOOLS_DIR/cut_audio.py \\\n",
"--output_dir=$OUTPUT_DIR \\\n",
"--alignment=$OUTPUT_DIR/segments/ \\\n",
"--threshold=$THRESHOLD \\\n",
"--offset=$OFFSET"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QoyS0T8AZxcx"
},
"source": [
"## 3.3. Transcribe segmented audio\n",
"\n",
"The transcripts will be saved in a new manifest file in `pred_text` field."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1UaSIflBZwaV"
},
"outputs": [],
"source": [
"import sys\n",
"wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/asr/transcribe_speech.py')\n",
"\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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "F-nPT8z_IVD-"
},
"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",
" go.Scatter(x=np.arange(signal.shape[0])/sample_rate,\n",
" y=signal, line={'color': 'green'},\n",
" name='Waveform',\n",
" hovertemplate='Time: %{x:.2f} s<br>Amplitude: %{y:.2f}<br><extra></extra>'),\n",
" layout={\n",
" 'height': 200,\n",
" 'xaxis': {'title': 'Time, s'},\n",
" 'yaxis': {'title': 'Amplitude'},\n",
" 'title': 'Audio Signal',\n",
" 'margin': dict(l=0, r=0, t=40, b=0, pad=0),\n",
" }\n",
" )\n",
" fig_signal.show()\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",
"\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",
" if 'pred_text' in sample:\n",
" display('ASR transcript: ' + sample['pred_text'])\n",
" print(f\"Score: {sample['score']}\")\n",
" print('\\n' + '-' * 110)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "S69UFA30ZvxV"
},
"source": [
"Let's examine the high scored segments we obtained.\n",
"\n",
"The `Reference text` in the next cell represents the original text without pre-processing, while `ASR transcript` is an ASR model prediction with greedy decoding. Also notice, that `ASR transcript` in some cases contains errors that could decrease the alignment score, but usually it doesnt hurt the quality of the aligned segments.\n",
"\n",
"Displaying audio in Jupyter Notebook could be slow, it's recommended to use [Speech Data Explorer](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/tools/speech_data_explorer.html) to analyze speech data."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Q45uBtsHIaAD"
},
"outputs": [],
"source": [
"# let's examine only a few first samples\n",
"! head -n 2 $OUTPUT_DIR/manifests/manifest_transcribed.json > $OUTPUT_DIR/manifests/samples.json\n",
"\n",
"display_samples(f\"{OUTPUT_DIR}/manifests/samples.json\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yivXpD25T4Ir"
},
"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",
"\n",
"Our English data folder contains 2 audio files and corresponding text files:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KRc9yMjPXPgj"
},
"outputs": [],
"source": [
"! ls $DATA_DIR/en/audio $DATA_DIR/en/text"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3ftilXu-5tzT"
},
"source": [
"We are going to use `run_segmentation.sh` to perform all the above steps starting from the text and audio preprocessing to segmentation and manifest creation in a single step:"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2I4w34Hepdor"
},
"source": [
"`run_segmentation.sh` script takes `DATA_DIR` argument and assumes that it contains folders `text` and `audio`.\n",
"An example of the `DATA_DIR` folder structure:\n",
"\n",
"\n",
"--DATA_DIR\n",
"\n",
" |----audio\n",
" |---1.mp3\n",
" |---2.mp3\n",
" \n",
" |-----text\n",
" |---1.txt\n",
" |---2.txt"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nYXNvBDsHMEu"
},
"source": [
"`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,
"metadata": {
"id": "hRFAl0gO92bp"
},
"outputs": [],
"source": [
"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 = \"stt_en_citrinet_512\" # QuartzNet15x5Base-En was removed from NeMo (PR #15507); use a registered CTC model\n",
"OUTPUT_DIR_2 = WORK_DIR + \"/en_output\"\n",
"\n",
"! rm -rf $OUTPUT_DIR_2\n",
"\n",
"! bash $TOOLS_DIR/../run_segmentation.sh \\\n",
"--MODEL_NAME_OR_PATH=$MODEL \\\n",
"--DATA_DIR=$DATA_DIR/en \\\n",
"--OUTPUT_DIR=$OUTPUT_DIR_2 \\\n",
"--SCRIPTS_DIR=$TOOLS_DIR \\\n",
"--MIN_SCORE=$THRESHOLD \\\n",
"--USE_NEMO_NORMALIZATION=False"
]
},
{
"cell_type": "markdown",
"source": [],
"metadata": {
"id": "9qgq9m6Fyp-1"
}
},
{
"cell_type": "markdown",
"metadata": {
"id": "zzJTwKq2Kl9U"
},
"source": [
"Manifest file with segments with alignment score above the threshold values are saved in `en/output/manifests/manifest.json`.\n",
"\n",
"Next, we are going to run `run_filter.sh`. The script does the following:\n",
"* adds ASR transcripts to the manifest\n",
"* calculates and saves metrics such as Word Error Rate (WER), Character Error Rate (CER), CER at the tails of the audio file, word difference between reference and transcript, mean absolute values at the tails of the audio.\n",
"* filters out samples that do not satisfy threshold values and saves selected segments in `manifest_transcribed_metrics_filtered.json`.\n",
"\n",
"Note, it's better to analyze the manifest with metrics in Speech Data Explorer to decide on what thresholds should be used for final sample selection."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xsm89hYlpdor"
},
"outputs": [],
"source": [
"! bash $TOOLS_DIR/../run_filter.sh \\\n",
"--SCRIPTS_DIR=$TOOLS_DIR \\\n",
"--MODEL_NAME_OR_PATH=stt_en_conformer_ctc_large \\\n",
"--MANIFEST=$OUTPUT_DIR_2/manifests/manifest.json \\\n",
"--INPUT_AUDIO_DIR=$DATA_DIR/en/audio/"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nacE_iQ2_85L"
},
"outputs": [],
"source": [
"# let's examine only a few first samples\n",
"! head -n 2 $OUTPUT_DIR_2/manifests/manifest_transcribed_metrics_filtered.json > $OUTPUT_DIR_2/manifests/samples.json\n",
"\n",
"display_samples(f\"{OUTPUT_DIR_2}/manifests/samples.json\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lcvT3P2lQ_GS"
},
"source": [
"# Next Steps\n",
"\n",
"- Check out [NeMo Speech Data Explorer tool](https://github.com/NVIDIA/NeMo/tree/main/tools/speech_data_explorer#speech-data-explorer) to interactively evaluate the aligned segments.\n",
"- Try Audio-based normalization tool."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "GYylwvTX2VSF"
},
"source": [
"# 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": {
"private_outputs": true,
"provenance": []
},
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,396 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\"\"\"\n",
"You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
"\n",
"Instructions for setting up Colab are as follows:\n",
"1. Open a new Python 3 notebook.\n",
"2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
"3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
"4. Run this cell to set up dependencies.\n",
"5. Restart the runtime (Runtime -> Restart Runtime) for any upgraded packages to take effect\n",
"\"\"\"\n",
"\n",
"NEMO_DIR_PATH = \"NeMo\"\n",
"BRANCH = 'main'\n",
"\n",
"! git clone https://github.com/NVIDIA-NeMo/Speech\n",
"%cd NeMo\n",
"! python -m pip install \"nemo_toolkit[all] @ git+https://github.com/NVIDIA-NeMo/Speech.git@$BRANCH\"\n",
"%cd .."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Install dependencies\n",
"!apt-get install sox libsndfile1 ffmpeg\n",
"!pip install wget\n",
"!pip install text-unidecode\n",
"!pip install \"matplotlib>=3.3.2\"\n",
"!pip install seaborn"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Multispeaker Simulator\n",
"\n",
"This tutorial shows how to use the speech data simulator to generate synthetic multispeaker audio sessions that can be used to train or evaluate models for multispeaker ASR or speaker diarization. This tool aims to address the lack of labelled multispeaker training data and to help models deal with overlapping speech."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 1: Download Required Datasets\n",
"\n",
"The LibriSpeech dataset and corresponding word alignments are required for generating synthetic multispeaker audio sessions. For simplicity, only the dev-clean dataset is used for generating synthetic sessions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"\n",
"# download scripts if not already there \n",
"if not os.path.exists('NeMo/scripts'):\n",
" print(\"Downloading necessary scripts\")\n",
" !mkdir -p NeMo/scripts/dataset_processing\n",
" !mkdir -p NeMo/scripts/speaker_tasks\n",
" !wget -P NeMo/scripts/dataset_processing/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/scripts/dataset_processing/get_librispeech_data.py\n",
" !wget -P NeMo/scripts/speaker_tasks/ https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/scripts/speaker_tasks/create_alignment_manifest.py"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!mkdir -p LibriSpeech\n",
"!python {NEMO_DIR_PATH}/scripts/dataset_processing/get_librispeech_data.py \\\n",
" --data_root LibriSpeech \\\n",
" --data_sets dev_clean"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The LibriSpeech forced word alignments are from [this repository](https://github.com/CorentinJ/librispeech-alignments). You can access to the whole LibriSpeech splits at this google drive [link](https://drive.google.com/file/d/1WYfgr31T-PPwMcxuAq09XZfHQO5Mw8fE/view?usp=sharing). We will download the dev-clean part for demo purpose."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wget -nc https://dldata-public.s3.us-east-2.amazonaws.com/LibriSpeech_Alignments.tar.gz\n",
"!tar -xzf LibriSpeech_Alignments.tar.gz\n",
"!rm -f LibriSpeech_Alignments.tar.gz"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 2: Produce Manifest File with Forced Alignments\n",
"\n",
"The LibriSpeech manifest file and LibriSpeech forced alignments will now be merged into one manifest file for ease of use when generating synthetic data. \n",
"\n",
"Here, the input LibriSpeech alignments are first converted to CTM files, and the CTM files are then combined with the base manifest in order to produce the manifest file with word alignments. When using another dataset, the --use_ctm argument can be used to generate the manifest file using alignments in CTM files."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!python {NEMO_DIR_PATH}/scripts/speaker_tasks/create_alignment_manifest.py \\\n",
" --input_manifest_filepath LibriSpeech/dev_clean.json \\\n",
" --base_alignment_path LibriSpeech_Alignments \\\n",
" --output_manifest_filepath ./dev-clean-align.json \\\n",
" --ctm_output_directory ./ctm_out \\\n",
" --libri_dataset_split dev-clean"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 3: Download Background Noise Data\n",
"\n",
"The background noise is constructed from [here](https://www.openslr.org/resources/28/rirs_noises.zip) (although it can be constructed from other background noise datasets instead)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!wget -nc https://www.openslr.org/resources/28/rirs_noises.zip\n",
"!unzip -o rirs_noises.zip\n",
"!rm -f rirs_noises.zip"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Data Simulator Overview\n",
"\n",
"The simulator creates a speech session using utterances from a desired number of speakers. The simulator first selects the LibriSpeech speaker IDs that will be used for the current session, and sets speaker dominance values for each speaker to determine how often each speaker will talk in the session. The session is then constructed by iterating through the following steps:\n",
"\n",
"* The next speaker is selected (which could be the same speaker again with some probability, and which accounts for the speaker dominance values).\n",
"* The sentence length is determined using a probability distribution, and an utterance of the desired length is then constructed by concatenating together (or truncating) LibriSpeech sentences corresponding to the desired speaker. Individual word alignments are used to truncate the last LibriSpeech sentence such that the entire utterance has the desired length.\n",
"* Next, either the current utterance is overlapped with a previous utterance or silence is introduced before inserting the current utterance. \n",
"\n",
"The simulator includes a multi-microphone far-field mode that incorporates synthetic room impulse response generation in order to simulate multi-microphone multispeaker sessions. When using RIR generation, the RIR is computed once per batch of sessions, and then each constructed utterance is convolved with the RIR in order to get the sound recorded by each microphone before adding the utterance to the audio session. In this tutorial, only near field sessions will be generated.\n",
"\n",
"The simulator also has a speaker enforcement mode which ensures that the correct number of speakers appear in each session, since it is possible that fewer than the desired number may be present since speaker turns are probabilistic. In speaker enforcement mode, the length of the session or speaker probabilities may be adjusted to ensure all speakers are included before the session finishes."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Parameters"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from omegaconf import OmegaConf\n",
"ROOT = os.getcwd()\n",
"conf_dir = os.path.join(ROOT,'conf')\n",
"!mkdir -p $conf_dir\n",
"CONFIG_PATH = os.path.join(conf_dir, 'data_simulator.yaml')\n",
"if not os.path.exists(CONFIG_PATH):\n",
" !wget -P $conf_dir https://raw.githubusercontent.com/NVIDIA/NeMo/$BRANCH/tools/speech_data_simulator/conf/data_simulator.yaml\n",
"\n",
"config = OmegaConf.load(CONFIG_PATH)\n",
"print(OmegaConf.to_yaml(config))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 4: Create Background Noise Manifest"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!find RIRS_NOISES/real_rirs_isotropic_noises/*.wav > bg_noise.list \n",
"\n",
"# this function can also be run using the pathfiles_to_diarize_manifest.py script\n",
"from nemo.collections.asr.parts.utils.manifest_utils import create_manifest\n",
"create_manifest('bg_noise.list', 'bg_noise.json')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 5: Generate Simulated Audio Session\n",
"\n",
"A single 4-speaker session of 30 seconds is generated as an example. "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from nemo.collections.asr.data.data_simulation import MultiSpeakerSimulator\n",
"\n",
"ROOT = os.getcwd()\n",
"data_dir = os.path.join(ROOT,'simulated_data')\n",
"config.data_simulator.random_seed=42\n",
"config.data_simulator.manifest_filepath=\"./dev-clean-align.json\"\n",
"config.data_simulator.outputs.output_dir=data_dir\n",
"config.data_simulator.session_config.num_sessions=1\n",
"config.data_simulator.session_config.session_length=30\n",
"config.data_simulator.background_noise.add_bg=True\n",
"config.data_simulator.background_noise.background_manifest=\"./bg_noise.json\"\n",
"config.data_simulator.session_params.mean_silence=0.2\n",
"config.data_simulator.session_params.mean_silence_var=0.02\n",
"config.data_simulator.session_params.mean_overlap=0.15\n",
"\n",
"lg = MultiSpeakerSimulator(cfg=config)\n",
"lg.generate_sessions()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 6: Listen to and Visualize Session\n",
"\n",
"Listen to the audio and visualize the corresponding speaker timestamps (recorded in a RTTM file for each session)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import os\n",
"import IPython\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import librosa\n",
"from nemo.collections.asr.parts.utils.speaker_utils import rttm_to_labels, labels_to_supervisions\n",
"\n",
"ROOT = os.getcwd()\n",
"data_dir = os.path.join(ROOT,'simulated_data')\n",
"audio = os.path.join(data_dir,'multispeaker_session_0.wav')\n",
"rttm = os.path.join(data_dir,'multispeaker_session_0.rttm')\n",
"\n",
"sr = 16000\n",
"signal, sr = librosa.load(audio,sr=sr) \n",
"\n",
"fig,ax = plt.subplots(1,1)\n",
"fig.set_figwidth(20)\n",
"fig.set_figheight(2)\n",
"plt.plot(np.arange(len(signal)),signal,'gray')\n",
"fig.suptitle('Synthetic Audio Session', fontsize=16)\n",
"plt.xlabel('Time (s)', fontsize=18)\n",
"ax.margins(x=0)\n",
"plt.ylabel('Signal Strength', fontsize=16);\n",
"a,_ = plt.xticks();plt.xticks(a,a/sr);\n",
"\n",
"IPython.display.Audio(audio)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The visualization is useful for seeing both the distribution of utterance lengths, the differing speaker dominance values, and the amount of overlap in the session."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#display speaker labels for reference\n",
"labels = rttm_to_labels(rttm)\n",
"reference = labels_to_supervisions(labels)\n",
"reference"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"# Step 7: Get Simulated Data Statistics "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import wget\n",
"if not os.path.exists(\"multispeaker_data_analysis.py\"):\n",
" !wget https://raw.githubusercontent.com/NVIDIA/NeMo/main/scripts/speaker_tasks/multispeaker_data_analysis.py\n",
"\n",
"from multispeaker_data_analysis import run_multispeaker_data_analysis\n",
"\n",
"session_dur = 30\n",
"silence_mean = 0.2\n",
"silence_var = 0.1\n",
"overlap_mean = 0.15\n",
"run_multispeaker_data_analysis(data_dir, session_dur=session_dur, silence_var=silence_var, overlap_mean=overlap_mean, precise=True);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Files Produced\n",
"\n",
"The following files are produced by the simulator:\n",
"\n",
"* wav files (one per audio session) - the output audio sessions\n",
"* rttm files (one per audio session) - the speaker timestamps for the corresponding audio session (used for diarization training)\n",
"* json files (one per audio session) - the output manifest file for the corresponding audio session (containing text transcriptions, utterance durations, full paths to audio files, words, and word alignments)\n",
"* ctm files (one per audio session) - contains word-by-word alignments, speaker ID, and word\n",
"* txt files (one per audio session) - contains the full text transcription for a given session\n",
"* list files (one per file type per batch of sessions) - a list of generated files of the given type (wav, rttm, json, ctm, or txt), used primarily for manifest creation\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!ls simulated_data"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "nemo093025",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
},
"pycharm": {
"stem_cell": {
"cell_type": "raw",
"metadata": {
"collapsed": false
},
"source": []
}
}
},
"nbformat": 4,
"nbformat_minor": 4
}
@@ -0,0 +1,560 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 88
},
"id": "d4KCUoxSpdoZ",
"outputId": "51c8a307-54e4-4056-a677-2baee15081b8"
},
"outputs": [],
"source": [
"BRANCH = 'main'\n",
"\n",
"\"\"\"\n",
"You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
"\n",
"Instructions for setting up Colab are as follows:\n",
"1. Open a new Python 3 notebook.\n",
"2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
"3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
"4. Run this cell to set up dependencies.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JDk9zxC6pdod",
"outputId": "3ba8e4ef-65b6-4731-ad27-d34d15adc3d1"
},
"outputs": [],
"source": [
"import os\n",
"# either provide a path to local NeMo repository with NeMo already installed or git clone\n",
"\n",
"# option #1: local path to NeMo repo with NeMo already installed\n",
"NEMO_DIR_PATH = \"NeMo\"\n",
"\n",
"# option #2: download NeMo repo\n",
"if 'google.colab' in str(get_ipython()) or not os.path.exists(NEMO_DIR_PATH):\n",
" !git clone -b $BRANCH https://github.com/NVIDIA-NeMo/Speech\n",
" %cd NeMo\n",
" !python -m pip install \"nemo_toolkit[all] @ git+https://github.com/NVIDIA-NeMo/Speech.git@$BRANCH\"\n",
" %cd -"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "7ZO_421L7bOH"
},
"source": [
"This tutorial contains external links. Each user is responsible for checking the content and the applicable licenses and determining if suitable for the intended use."
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "A4NE9GhNn8f-"
},
"source": [
"In this tutorial, we will use [NeMo Forced Aligner](https://github.com/NVIDIA/NeMo/tree/main/tools/nemo_forced_aligner) to generate token and word alignments for a video of Neil Armstrong's first steps on the moon. We will use the ASS-format subtitle files generated by NFA to add subtitles with token-by-token and word-by-word highlighting to the video.\n",
"\n",
"\n",
"We will use the video at this [link](https://www.nasa.gov/wp-content/uploads/static/history/alsj/a11/a11.v1092338.mov), which is in the public domain and was obtained from the NASA website [here](https://history.nasa.gov/alsj/a11/video11.html#Step). The transcript for the video is obtained from the transcript of the mission [here](https://history.nasa.gov/alsj/a11/a11transcript_tec.pdf). As referenced on this [page](https://history.nasa.gov/alsj/a11/a11trans.html), this is a raw transcript with no copyright asserted.\n",
"\n",
"The alignment process is shown below. To better understand the 'Viterbi decoding' process, you can refer to our tutorial [here](https://nvidia.github.io/NeMo/blogs/2023/2023-08-forced-alignment/).\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PGr_hMTCcm3J"
},
"source": [
"![NFA forced alignment pipeline](https://github.com/NVIDIA/NeMo/releases/download/v1.20.0/nfa_forced_alignment_pipeline.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gQOQ-EK1aIBN"
},
"source": [
"\n",
"\n",
"We will do the following:\n",
"\n",
"1. Download the source video.\n",
"2. Prepare a manifest to input to NFA.\n",
"3. Generate alignments using NFA.\n",
"4. Generate a video with subtitles with token-by-token or word-by-word highlighting."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CH7yR7cSwPKr"
},
"outputs": [],
"source": [
"import json\n",
"import os\n",
"\n",
"from IPython.display import HTML\n",
"from base64 import b64encode"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "40XnfPNop_7V"
},
"source": [
"# 1. Video download\n",
"We will download the video from the provided link and convert it to a higher-resolution format - the video footage will not get any clearer, but it will allow the subtitles to look sharper when we burn them in at the end of the tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "sl34bUsUp_EV",
"outputId": "a1170a38-7fa0-439f-8ca8-2b79d9d0406d"
},
"outputs": [],
"source": [
"# first make a directory WORK_DIR that we will save all our new files in\n",
"WORK_DIR=\"WORK_DIR\"\n",
"!mkdir $WORK_DIR\n",
"!wget https://www.nasa.gov/wp-content/uploads/static/history/alsj/a11/a11.v1092338.mov --directory-prefix=$WORK_DIR"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "GuFjl8-mrJub",
"outputId": "a216ef90-3d6e-49e5-8c23-88f60b2fc11f"
},
"outputs": [],
"source": [
"# scale up the number of pixels in video so that the subtitles will look sharp when we burn them in later\n",
"!/usr/bin/ffmpeg -loglevel warning -y -i $WORK_DIR/a11.v1092338.mov -vf \"scale=-1:480\" $WORK_DIR/one_small_step.mp4\n",
"# also save the audio as a separate file, so that we can use this as input to NFA\n",
"!/usr/bin/ffmpeg -loglevel warning -y -i $WORK_DIR/a11.v1092338.mov $WORK_DIR/one_small_step.wav"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "laCH__s6KYSF"
},
"source": [
"A note on FFMPEG commands:\n",
"\n",
"*In this tutorial, instead of just calling the `ffmpeg` command, we will specifically call `/usr/bin/ffmpeg`. If we just call `ffmpeg`, there is a chance the conda version of `ffmpeg` will be called (depending on how you installed the dependencies for this tutorial). We have observed that the conda version of `ffmpeg` may generate incorrectly formatted MP4 files with the commands used, and may not be able to generate the subtitle videos which we will create at the end of this tutorial.*\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 322
},
"id": "5In-mlX7pPqq",
"outputId": "47651480-9e64-48e8-d3bb-08bae51e6f50"
},
"outputs": [],
"source": [
"# display video so we know what we will be working with\n",
"mp4 = open(f'{WORK_DIR}/one_small_step.mp4','rb').read()\n",
"data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n",
"HTML(\"\"\"\n",
"<video width=400 controls>\n",
" <source src=\"%s\" type=\"video/mp4\">\n",
"</video>\n",
"\"\"\" % data_url)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dNSOrcDyscvV"
},
"source": [
"The audio and video quality of the video isn't great - it was taken on the Moon in 1969 after all. Using NFA, we will still be able to obtain good token & word alignments despite the poor audio quality."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "VGsMdjOsdBn6"
},
"source": [
"# 2. Prepare a manifest to input to NFA.\n",
"NFA requires a manifest as input, in the form shown in the diagram below. As we are only aligning a single audio file, our manifest will only contain one line.\n",
"\n",
"**Note**: the text field is optional, but if you omit it, you need to specify `align_using_pred_text=true` in the config you feed into NFA.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "i84J0AyiW6X7"
},
"source": [
"![NFA usage pipeline](https://github.com/NVIDIA/NeMo/releases/download/v1.20.0/nfa_run.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lmxvl-tcsyz6"
},
"source": [
"We prepare the text obtained from [here](https://history.nasa.gov/alsj/a11/a11transcript_tec.pdf).\n",
"\n",
"We will specify in the NFA config `additional_segment_grouping_separator=['.', '?', '!', '...']` to separate the text into logically defined segments that are finished expressions. This will make sure NFA produces timestamps for each segment separated by `additional_segment_grouping_separator`. It also means that, by default, the ASS subtitle files will display those segments together.\n",
"\n",
"**Extra info**: Alternatively, you can specify in the NFA config that `ass_file_config.resegment_text_to_fill_space=true`, which will cause automatic grouping of words in the ASS files. You can also specify `ass_file_config.max_lines_per_segment` to set the maximum number of lines of text that will appear at a time."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IS-ef4o5s_tv"
},
"outputs": [],
"source": [
"text = \"\"\"\n",
"I'm at the foot of the ladder. The LM footpads are only depressed in the \n",
"surface about 1 or 2 inches, although the surface appears to be very, very \n",
"fine grained, as you get close to it. It's almost like a powder. \n",
"Down there, it's very fine. I'm going to step off the LM now. That's one \n",
"small step for man, one giant leap for mankind.\n",
"\"\"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OHq0trf2h24g"
},
"outputs": [],
"source": [
"manifest_filepath = f\"{WORK_DIR}/manifest.json\"\n",
"manifest_data = {\n",
" \"audio_filepath\": f\"{WORK_DIR}/one_small_step.wav\",\n",
" \"text\": text\n",
"}\n",
"with open(manifest_filepath, 'w') as f:\n",
" line = json.dumps(manifest_data)\n",
" f.write(line + \"\\n\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "RvTrg8C3wHYw",
"outputId": "b257a766-4dfc-4f69-f75e-4b3bbf84ef60"
},
"outputs": [],
"source": [
"!cat $manifest_filepath"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QKnTJG5Ig4lP"
},
"source": [
"# 3. Run NFA"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"id": "izC7x71-T0Il"
},
"source": [
"We run NFA by calling the `align.py` function and passing in config parameters. In our case these want to set:\n",
"\n",
"**Compulsory parameters**\n",
"\n",
"* `pretrained_name` (either this or a `model_path` is required) - this is the name of the ASR model that we will use to do alignment. You can use any of NeMo's CTC models for alignment.\n",
"* `manifest_filepath` - the path to the manifest specifying the audio that you want to align and its reference text.\n",
"* `output_dir` - the path to the directory where your output files will be saved.\n",
"\n",
"**Optional parameters**\n",
"* `additional_segment_grouping_separator` - a list of strings that will be used to separate the text into segments. In our case we use default values of `['.', '?', '!', '...']`.\n",
"* `ass_file_config.vertical_alignment` - by default this is set to `\"center\"`, meaning the subtitles will appear in the center of the screen. We want them to appear at the bottom of our video, so we set this parameter to `\"bottom\"`.\n",
"* `ass_file_config.text_already_spoken_rgb`, `ass_file_config.text_being_spoken_rgb`, `ass_file_config.text_not_yet_spoken_rgb` - these parameters define the RGB values of the colors of the text. The default colors do not show up very clearly against our video, so we set them to some different values, which will generate the colors teal, yellow, and a very pale blue."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "QDcyfW_RWrqB",
"outputId": "9b76c513-30bd-44d6-ef70-7daba8f604f0"
},
"outputs": [],
"source": [
"!python $NEMO_DIR_PATH/tools/nemo_forced_aligner/align.py \\\n",
" pretrained_name=\"stt_en_fastconformer_hybrid_large_pc\" \\\n",
" manifest_filepath=$manifest_filepath \\\n",
" output_dir=$WORK_DIR/nfa_output/ \\\n",
" additional_segment_grouping_separator='[\".\",\"?\",\"!\",\"...\"]' \\\n",
" ass_file_config.vertical_alignment=\"bottom\" \\\n",
" ass_file_config.text_already_spoken_rgb=[66,245,212] \\\n",
" ass_file_config.text_being_spoken_rgb=[242,222,44] \\\n",
" ass_file_config.text_not_yet_spoken_rgb=[223,242,239]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dHU-YmALUvVf"
},
"source": [
"The alignment process should have finished successfully, let's look at some of the output files."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "VSyM9zp4wQSJ",
"outputId": "3d77e04d-cc56-425a-92bc-d70a34545f00"
},
"outputs": [],
"source": [
"!head $WORK_DIR/nfa_output/ctm/*/*.ctm\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-LESm1cudqZ0"
},
"source": [
"The token timestamps are produced directly from the Viterbi alignment process, and the word and segment timestamps are obtained from the token timestamps using a simple grouping process shown below:"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OXUL-KyUdVpL"
},
"source": [
"![How NFA generates word and segment alignments from token alignments](https://github.com/NVIDIA/NeMo/releases/download/v1.20.0/nfa_word_segment_alignments.png)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3ZZuKU5YwXBh"
},
"source": [
"# 4. Make subtitled video"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tlYr1ymnU4Du"
},
"source": [
"To make the subtitled video, we will use the ASS-format files that NFA produces."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "RauJ91RgzCvp",
"outputId": "b0b34085-847a-4af0-d937-b67de12304e5"
},
"outputs": [],
"source": [
"!head -n20 $WORK_DIR/nfa_output/ass/words/*.ass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OaYjR7mDdVKF",
"outputId": "2fedc7ae-b931-409f-a338-5a36e6c457c4"
},
"outputs": [],
"source": [
"!head -n20 $WORK_DIR/nfa_output/ass/tokens/*.ass"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ipIlViegVDgQ"
},
"source": [
"We burn the subtitles into the video using the below commands. We generate 2 videos, one with token-by-token highlighting, and one with word-by-word highlighting."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Av7L4Qzojykv",
"outputId": "dd1dc2af-3631-4776-e79d-157b61afa98e"
},
"outputs": [],
"source": [
"!/usr/bin/ffmpeg -loglevel warning -y -i \"$WORK_DIR/one_small_step.mp4\" \\\n",
" -vf \"ass=$WORK_DIR/nfa_output/ass/tokens/one_small_step.ass\" \\\n",
" $WORK_DIR/one_small_step_tokens_aligned.mp4\n",
"\n",
"!/usr/bin/ffmpeg -loglevel warning -y -i \"$WORK_DIR/one_small_step.mp4\" \\\n",
" -vf \"ass=$WORK_DIR/nfa_output/ass/words/one_small_step.ass\" \\\n",
" $WORK_DIR/one_small_step_words_aligned.mp4"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gfhQxkbPVPSj"
},
"source": [
"Let's look at the resulting videos below.\n",
"\n",
"You can see that the token timestamps (in the first video) are very accurate, even despite the poor audio quality of the video.\n",
"\n",
"The word timestamps (in the second video) are also very good. The only noticeable mistakes are when the word has punctuation at the end (or beginning). This is because punctuation that is not separated from a word by a space is considered to be part of that word. If the alignment for the punctuation is in a region of non-speech, then the word alignment will also contain that region of non-speech."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 322
},
"id": "ik6FcCgIMYsa",
"outputId": "4781a087-a8a2-44a7-9e0f-ea57e05cde59"
},
"outputs": [],
"source": [
"mp4 = open(f'{WORK_DIR}/one_small_step_tokens_aligned.mp4','rb').read()\n",
"data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n",
"HTML(\"\"\"\n",
"<video width=400 controls>\n",
" <source src=\"%s\" type=\"video/mp4\">\n",
"</video>\n",
"\"\"\" % data_url)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 322
},
"id": "mgFUhdlsdXLs",
"outputId": "94f8ae2f-8752-4671-aeca-a19f03db7fd6"
},
"outputs": [],
"source": [
"mp4 = open(f'{WORK_DIR}/one_small_step_words_aligned.mp4','rb').read()\n",
"data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n",
"HTML(\"\"\"\n",
"<video width=400 controls>\n",
" <source src=\"%s\" type=\"video/mp4\">\n",
"</video>\n",
"\"\"\" % data_url)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gr70zxMoeLqR"
},
"outputs": [],
"source": []
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"provenance": []
},
"gpuClass": "standard",
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,249 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "exact-strand",
"metadata": {},
"source": [
"## Install NVidia NeMo environment"
]
},
{
"cell_type": "markdown",
"id": "compound-found",
"metadata": {},
"source": [
"You can locally install NeMo environment by following [installation guide](https://github.com/heartexlabs/NeMo#installation), or quickstart it from the prebuilt Docker container:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "pacific-pepper",
"metadata": {},
"outputs": [],
"source": [
"!docker run --gpus all -it --rm --shm-size=8g \\\n",
"-p 8888:8888 -p 6006:6006 -p 8080:8080 --ulimit memlock=-1 --ulimit \\\n",
"stack=67108864 --device=/dev/snd nvcr.io/nvidia/nemo:1.0.1"
]
},
{
"cell_type": "markdown",
"id": "strong-therapist",
"metadata": {},
"source": [
"Note that the default Label Studio port 8080 is exposed from Docker."
]
},
{
"cell_type": "markdown",
"id": "everyday-depth",
"metadata": {},
"source": [
"## Install Label Studio"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "spoken-venice",
"metadata": {},
"outputs": [],
"source": [
"!pip install label-studio"
]
},
{
"cell_type": "markdown",
"id": "integral-introduction",
"metadata": {},
"source": [
"## Create ML backend with NeMo model"
]
},
{
"cell_type": "markdown",
"id": "dimensional-playing",
"metadata": {},
"source": [
"Let's create a simple script `asr.py` that wraps NeMo inference call and converts its output to annotation format expected by Label Studio"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "tribal-minority",
"metadata": {},
"outputs": [],
"source": [
"import nemo\n",
"import nemo.collections.asr as nemo_asr\n",
"from label_studio_ml.model import LabelStudioMLBase\n",
"\n",
"\n",
"class NemoASR(LabelStudioMLBase):\n",
"\n",
" def __init__(self, model_name='QuartzNet15x5Base-En', **kwargs):\n",
" super(NemoASR, self).__init__(**kwargs)\n",
"\n",
" # Find TextArea control tag and bind ASR model to it\n",
" self.from_name, self.to_name, self.value = self._bind_to_textarea()\n",
"\n",
" # This line will download pre-trained QuartzNet15x5 model from NVIDIA's NGC cloud and instantiate it for you\n",
" self.model = nemo_asr.models.EncDecCTCModel.from_pretrained(model_name=model_name)\n",
"\n",
" def predict(self, tasks, **kwargs):\n",
" \"\"\"Returns NeMo ASR predictions given audio files in Label Studio's tasks\"\"\"\n",
" audio_path = self.get_local_path(tasks[0]['data'][self.value])\n",
" transcription = self.model.transcribe(paths2audio_files=[audio_path])[0]\n",
" return [{\n",
" 'result': [{\n",
" 'from_name': self.from_name,\n",
" 'to_name': self.to_name,\n",
" 'type': 'textarea',\n",
" 'value': {\n",
" 'text': [transcription]\n",
" }\n",
" }],\n",
" 'score': 1.0\n",
" }]\n",
"\n",
" def _bind_to_textarea(self):\n",
" \"\"\"Helper to bind inference output to annotation format expected by Label Studio\"\"\"\n",
" from_name, to_name, value = None, None, None\n",
" for tag_name, tag_info in self.parsed_label_config.items():\n",
" if tag_info['type'] == 'TextArea':\n",
" from_name = tag_name\n",
" if len(tag_info['inputs']) > 1:\n",
" logger.warning(\n",
" 'ASR model works with single Audio or AudioPlus input, '\n",
" 'but {0} found: {1}. We\\'ll use only the first one'.format(\n",
" len(tag_info['inputs']), ', '.join(tag_info['to_name'])))\n",
" if tag_info['inputs'][0]['type'] not in ('Audio', 'AudioPlus'):\n",
" raise ValueError('{0} tag expected to be of type Audio or AudioPlus, but type {1} found'.format(\n",
" tag_info['to_name'][0], tag_info['inputs'][0]['type']))\n",
" to_name = tag_info['to_name'][0]\n",
" value = tag_info['inputs'][0]['value']\n",
" if from_name is None:\n",
" raise ValueError('ASR model expects <TextArea> tag to be presented in a label config.')\n",
" return from_name, to_name, value"
]
},
{
"cell_type": "markdown",
"id": "induced-pacific",
"metadata": {},
"source": [
"## Run ML backend"
]
},
{
"cell_type": "markdown",
"id": "fuzzy-malta",
"metadata": {},
"source": [
"The following initializes ML backend by creating a directory `./nemo-ml-backend` and copying everything needed to run, including `asr.py` script."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "outstanding-russell",
"metadata": {},
"outputs": [],
"source": [
"!label-studio-ml init nemo-ml-backend --from asr.py"
]
},
{
"cell_type": "markdown",
"id": "hybrid-thread",
"metadata": {},
"source": [
"Then launch ML backend serving on default `http://localhost:9090`"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "black-hazard",
"metadata": {},
"outputs": [],
"source": [
"!label-studio-ml start nemo-ml-backend"
]
},
{
"cell_type": "markdown",
"id": "private-recommendation",
"metadata": {},
"source": [
"## Connect ML backend to Label Studio"
]
},
{
"cell_type": "markdown",
"id": "aerial-circulation",
"metadata": {},
"source": [
"Launch Label Studio web application running on `http://localhost:8080`"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "skilled-giant",
"metadata": {},
"outputs": [],
"source": [
"!label-studio start annotation-with-nemo --init"
]
},
{
"cell_type": "markdown",
"id": "afraid-revision",
"metadata": {},
"source": [
"In Label Studio, upload audio files either by drag-and-drop, or by importing a text file with one URL referencing an audio file per line. Then, go to the **Settings** page and select the **Speech Transcription** template. Click **Save**."
]
},
{
"cell_type": "markdown",
"id": "suffering-respect",
"metadata": {},
"source": [
"On the **Model** page, add the ML backend URL `http://localhost:9090`. If it connects successfully, you see \"Connected\" status in green."
]
},
{
"cell_type": "markdown",
"id": "alike-realtor",
"metadata": {},
"source": [
"Then you can start to annotate your audio files by correcting the text areas prepopulated by NeMo ASR's output. After you finish labeling, you can export results in the `ASR_MANIFEST` format ready to use for [training a NeMo ASR model](https://colab.research.google.com/github/NVIDIA/NeMo/blob/stable/tutorials/asr/ASR_with_NeMo.ipynb)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}