class_docstr: Align text to audio using CTC segmentation.
  
  Usage:
      Initialize with given ASR model and parameters.
      If needed, parameters for CTC segmentation can be set with ``set_config(·)``.
      Then call the instance as function to align text within an audio file.
  
  Example:
      >>> # example file included in the ESPnet repository
      >>> import soundfile
      >>> speech, fs = soundfile.read("test_utils/ctc_align_test.wav")
      >>> # load an ASR model
      >>> from espnet_model_zoo.downloader import ModelDownloader
      >>> d = ModelDownloader()
      >>> wsjmodel = d.download_and_unpack( "kamo-naoyuki/wsj" )
      >>> # Apply CTC segmentation
      >>> aligner = CTCSegmentation( **wsjmodel )
      >>> text=["utt1 THE SALE OF THE HOTELS", "utt2 ON PROPERTY MANAGEMENT"]
      >>> aligner.set_config( gratis_blank=True )
      >>> segments = aligner( speech, text, fs=fs )
      >>> print( segments )
      utt1 utt 0.27 1.72 -0.1663 THE SALE OF THE HOTELS
      utt2 utt 4.54 6.10 -4.9646 ON PROPERTY MANAGEMENT
  
  On multiprocessing:
      To parallelize the computation with multiprocessing, these three steps
      can be separated:
      (1) ``get_lpz``: obtain the lpz,
      (2) ``prepare_segmentation_task``: prepare the task, and
      (3) ``get_segments``: perform CTC segmentation.
      Note that the function `get_segments` is a staticmethod and therefore
      independent of an already initialized CTCSegmentation object.
  
  References:
      CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition
      2020, Kürzinger, Winkelbauer, Li, Watzel, Rigoll
      https://arxiv.org/abs/2007.09127
  
  More parameters are described in https://github.com/lumaku/ctc-segmentation
docstr: Initialize the CTCSegmentation module.
  
  Args:
      asr_train_config: ASR model config file (yaml).
      asr_model_file: ASR model file (pth).
      fs: Sample rate of audio file.
      ngpu: Number of GPUs. Set 0 for processing on CPU, set to 1 for
          processing on GPU. Multi-GPU aligning is currently not
          implemented. Default: 0.
      batch_size: Currently, only batch size == 1 is implemented.
      dtype: Data type used for inference. Set dtype according to
          the ASR model.
      kaldi_style_text: A kaldi-style text file includes the name of the
          utterance at the start of the line. If True, the utterance name
          is expected as first word at each line. If False, utterance
          names are automatically generated. Set this option according to
          your input data. Default: True.
      text_converter: How CTC segmentation handles text.
          "tokenize": Use ESPnet 2 preprocessing to tokenize the text.
          "classic": The text is preprocessed as in ESPnet 1 which takes
          token length into account. If the ASR model has longer tokens,
          this option may yield better results. Default: "tokenize".
      time_stamps: Choose the method how the time stamps are
          calculated. While "fixed" and "auto" use both the sample rate,
          the ratio of samples to one frame is either automatically
          determined for each inference or fixed at a certain ratio that
          is initially determined by the module, but can be changed via
          the parameter ``samples_to_frames_ratio``. Recommended for
          longer audio files: "auto".
      **ctc_segmentation_args: Parameters for CTC segmentation.
docstr_tok: ["Initialize","the","CTCSegmentation","module",".","Args",":","asr_train_config",":","ASR","model","config","file","(","yaml",")",".","asr_model_file",":","ASR","model","file","(","pth",")",".","fs",":","Sample","rate","of","audio","file",".","ngpu",":","Number","of","GPUs",".","Set","0","for","processing","on","CPU",",","set","to","1","for","processing","on","GPU",".","Multi-GPU","aligning","is","currently","not","implemented",".","Default",":","0.","batch_size",":","Currently",",","only","batch","size","==","1","is","implemented",".","dtype",":","Data","type","used","for","inference",".","Set","dtype","according","to","the","ASR","model",".","kaldi_style_text",":","A","kaldi-style","text","file","includes","the","name","of","the","utterance","at","the","start","of","the","line",".","If","True",",","the","utterance","name","is","expected","as","first","word","at","each","line",".","If","False",",","utterance","names","are","automatically","generated",".","Set","this","option","according","to","your","input","data",".","Default",":","True",".","text_converter",":","How","CTC","segmentation","handles","text",".","``","tokenize","''",":","Use","ESPnet","2","preprocessing","to","tokenize","the","text",".","``","classic","''",":","The","text","is","preprocessed","as","in","ESPnet","1","which","takes","token","length","into","account",".","If","the","ASR","model","has","longer","tokens",",","this","option","may","yield","better","results",".","Default",":","``","tokenize","''",".","time_stamps",":","Choose","the","method","how","the","time","stamps","are","calculated",".","While","``","fixed","''","and","``","auto","''","use","both","the","sample","rate",",","the","ratio","of","samples","to","one","frame","is","either","automatically","determined","for","each","inference","or","fixed","at","a","certain","ratio","that","is","initially","determined","by","the","module",",","but","can","be","changed","via","the","parameter","``","samples_to_frames_ratio","``",".","Recommended","for","longer","audio","files",":","``","auto","''",".","*","*","ctc_segmentation_args",":","Parameters","for","CTC","segmentation","."]
code: def __init__(
      self,
      asr_train_config: Union[Path, str],
      asr_model_file: Union[Path, str] = None,
      fs: int = 16000,
      ngpu: int = 0,
      batch_size: int = 1,
      dtype: str = "float32",
      kaldi_style_text: bool = True,
      text_converter: str = "tokenize",
      time_stamps: str = "auto",
      **ctc_segmentation_args,
  ):
      """Initialize the CTCSegmentation module.
  
      Args:
          asr_train_config: ASR model config file (yaml).
          asr_model_file: ASR model file (pth).
          fs: Sample rate of audio file.
          ngpu: Number of GPUs. Set 0 for processing on CPU, set to 1 for
              processing on GPU. Multi-GPU aligning is currently not
              implemented. Default: 0.
          batch_size: Currently, only batch size == 1 is implemented.
          dtype: Data type used for inference. Set dtype according to
              the ASR model.
          kaldi_style_text: A kaldi-style text file includes the name of the
              utterance at the start of the line. If True, the utterance name
              is expected as first word at each line. If False, utterance
              names are automatically generated. Set this option according to
              your input data. Default: True.
          text_converter: How CTC segmentation handles text.
              "tokenize": Use ESPnet 2 preprocessing to tokenize the text.
              "classic": The text is preprocessed as in ESPnet 1 which takes
              token length into account. If the ASR model has longer tokens,
              this option may yield better results. Default: "tokenize".
          time_stamps: Choose the method how the time stamps are
              calculated. While "fixed" and "auto" use both the sample rate,
              the ratio of samples to one frame is either automatically
              determined for each inference or fixed at a certain ratio that
              is initially determined by the module, but can be changed via
              the parameter ``samples_to_frames_ratio``. Recommended for
              longer audio files: "auto".
          **ctc_segmentation_args: Parameters for CTC segmentation.
      """
      assert check_argument_types()
  
      # Basic settings
      if batch_size > 1:
          raise NotImplementedError("Batch decoding is not implemented")
      device = "cpu"
      if ngpu == 1:
          device = "cuda"
      elif ngpu > 1:
          logging.error("Multi-GPU not yet implemented.")
          raise NotImplementedError(
              "Only single GPU decoding is supported"
          )
  
      # Prepare ASR model
      asr_model, asr_train_args = ASRTask.build_model_from_file(
          asr_train_config, asr_model_file, device
      )
      asr_model.to(dtype=getattr(torch, dtype)).eval()
      self.preprocess_fn = ASRTask.build_preprocess_fn(
          asr_train_args, False
      )
  
      # Warn for nets with high memory consumption on long audio files
      if hasattr(asr_model, "encoder"):
          encoder_module = asr_model.encoder.__class__.__module__
      else:
          encoder_module = "Unknown"
      logging.info(f"Encoder module: {encoder_module}")
      logging.info(
          f"CTC module:     {asr_model.ctc.__class__.__module__}"
      )
      if "rnn" not in encoder_module.lower():
          logging.warning(
              "No RNN model detected; memory consumption may be high."
          )
  
      self.asr_model = asr_model
      self.asr_train_args = asr_train_args
      self.device = device
      self.dtype = dtype
      self.ctc = asr_model.ctc
  
      self.kaldi_style_text = kaldi_style_text
      self.token_list = asr_model.token_list
      # Apply configuration
      self.set_config(
          fs=fs,
          time_stamps=time_stamps,
          kaldi_style_text=kaldi_style_text,
          text_converter=text_converter,
          **ctc_segmentation_args,
      )
      # last token "<sos/eos>", not needed
      self.config.char_list = asr_model.token_list[:-1]
  
imports: import argparse
  import logging
  import sys
  from pathlib import Path
  from typing import List, Optional, TextIO, Union
  import numpy
  import soundfile
  import torch
  from ctc_segmentation import CtcSegmentationParameters, ctc_segmentation, determine_utterance_segments, prepare_text, prepare_token_list
  from typeguard import check_argument_types, check_return_type
  from espnet2.tasks.asr import ASRTask
  from espnet2.torch_utils.device_funcs import to_device
  from espnet2.utils import config_argparse
  from espnet2.utils.types import str2bool, str_or_none
  from espnet.utils.cli_utils import get_commandline_args
label_desc: Use image node_id 1 to create a new CTCSegmentation object  with example: obj = CTCSegmentation(asr_train_config, asr_model_file, fs, ngpu, batch_size, dtype, kaldi_style_text, text_converter, time_stamps)