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.
  
  Attributes
  ---------
  asr_model : EncoderDecoderASR
      Speechbrain ASR interface. This requires a model that has a
      trained CTC layer for inference. It is better to use a model with
      single-character tokens to get a better time resolution.
      Please note that the inference complexity with Transformer models
      usually increases quadratically with audio length.
      It is therefore recommended to use RNN-based models, if available.
  kaldi_style_text : bool
      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 : str
      How CTC segmentation handles text.
      "tokenize": Use the ASR model tokenizer to tokenize the text.
      "classic": The text is preprocessed as text pieces which takes
      token length into account. If the ASR model has longer tokens,
      this option may yield better results. Default: "tokenize".
  time_stamps : str
      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.
      The full list of parameters is found in ``set_config``.
  
  Example
  -------
      >>> # using example file included in the SpeechBrain repository
      >>> from speechbrain.inference.ASR import EncoderDecoderASR
      >>> from speechbrain.alignment.ctc_segmentation import CTCSegmentation
      >>> # load an ASR model
      >>> pre_trained = "speechbrain/asr-transformer-transformerlm-librispeech"
      >>> asr_model = EncoderDecoderASR.from_hparams(source=pre_trained)  # doctest: +SKIP
      >>> aligner = CTCSegmentation(asr_model, kaldi_style_text=False)  # doctest: +SKIP
      >>> # load data
      >>> audio_path = "tests/samples/single-mic/example1.wav"
      >>> text = ["THE BIRCH CANOE", "SLID ON THE", "SMOOTH PLANKS"]
      >>> segments = aligner(audio_path, text, name="example1")  # doctest: +SKIP
  
  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 obj́ect.
  
  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: Preprocess text, and gather text and lpz into a task object.
  
  Text is pre-processed and tokenized depending on configuration.
  If ``speech_len`` is given, the timing configuration is updated.
  Text, lpz, and configuration is collected in a CTCSegmentationTask
  object. The resulting object can be serialized and passed in a
  multiprocessing computation.
  
  It is recommended that you normalize the text beforehand, e.g.,
  change numbers into their spoken equivalent word, remove special
  characters, and convert UTF-8 characters to chars corresponding to
  your ASR model dictionary.
  
  The text is tokenized based on the ``text_converter`` setting:
  
  The "tokenize" method is more efficient and the easiest for models
  based on latin or cyrillic script that only contain the main chars,
  ["a", "b", ...] or for Japanese or Chinese ASR models with ~3000
  short Kanji / Hanzi tokens.
  
  The "classic" method improves the the accuracy of the alignments
  for models that contain longer tokens, but with a greater complexity
  for computation. The function scans for partial tokens which may
  improve time resolution.
  For example, the word "▁really" will be broken down into
  ``['▁', '▁r', '▁re', '▁real', '▁really']``. The alignment will be
  based on the most probable activation sequence given by the network.
  
  Arguments
  ---------
  text : list
      List or multiline-string with utterance ground truths.
  lpz : np.ndarray
      Log CTC posterior probabilities obtained from the CTC-network;
      numpy array shaped as ( <time steps>, <classes> ).
  name : str
      Audio file name that will be included in the segments output.
      Choose a unique name, or the original audio
      file name, to distinguish multiple audio files. Default: None.
  speech_len : int
      Number of sample points. If given, the timing
      configuration is automatically derived from length of fs, length
      of speech and length of lpz. If None is given, make sure the
      timing parameters are correct, see time_stamps for reference!
      Default: None.
  
  Returns
  -------
  CTCSegmentationTask
      Task object that can be passed to
      ``CTCSegmentation.get_segments()`` in order to obtain alignments.
docstr_tok: ["Preprocess","text",",","and","gather","text","and","lpz","into","a","task","object",".","Text","is","pre-processed","and","tokenized","depending","on","configuration",".","If","``","speech_len","``","is","given",",","the","timing","configuration","is","updated",".","Text",",","lpz",",","and","configuration","is","collected","in","a","CTCSegmentationTask","object",".","The","resulting","object","can","be","serialized","and","passed","in","a","multiprocessing","computation",".","It","is","recommended","that","you","normalize","the","text","beforehand",",","e.g.",",","change","numbers","into","their","spoken","equivalent","word",",","remove","special","characters",",","and","convert","UTF-8","characters","to","chars","corresponding","to","your","ASR","model","dictionary",".","The","text","is","tokenized","based","on","the","``","text_converter","``","setting",":","The","``","tokenize","''","method","is","more","efficient","and","the","easiest","for","models","based","on","latin","or","cyrillic","script","that","only","contain","the","main","chars",",","[","``","a","''",",","``","b","''",",","...","]","or","for","Japanese","or","Chinese","ASR","models","with","~3000","short","Kanji","\/","Hanzi","tokens",".","The","``","classic","''","method","improves","the","the","accuracy","of","the","alignments","for","models","that","contain","longer","tokens",",","but","with","a","greater","complexity","for","computation",".","The","function","scans","for","partial","tokens","which","may","improve","time","resolution",".","For","example",",","the","word","``","\u2581really","''","will","be","broken","down","into","``","[","'\u2581","'",",","'\u2581r","'",",","'\u2581re","'",",","'\u2581real","'",",","'\u2581really","'","]","``",".","The","alignment","will","be","based","on","the","most","probable","activation","sequence","given","by","the","network",".","Arguments","--","--","--","--","-","text",":","list","List","or","multiline-string","with","utterance","ground","truths",".","lpz",":","np.ndarray","Log","CTC","posterior","probabilities","obtained","from","the","CTC-network",";","numpy","array","shaped","as","(","<","time","steps",">",",","<","classes",">",")",".","name",":","str","Audio","file","name","that","will","be","included","in","the","segments","output",".","Choose","a","unique","name",",","or","the","original","audio","file","name",",","to","distinguish","multiple","audio","files",".","Default",":","None",".","speech_len",":","int","Number","of","sample","points",".","If","given",",","the","timing","configuration","is","automatically","derived","from","length","of","fs",",","length","of","speech","and","length","of","lpz",".","If","None","is","given",",","make","sure","the","timing","parameters","are","correct",",","see","time_stamps","for","reference","!","Default",":","None",".","Returns","--","--","--","-","CTCSegmentationTask","Task","object","that","can","be","passed","to","``","CTCSegmentation.get_segments","(",")","``","in","order","to","obtain","alignments","."]
code: def prepare_segmentation_task(
      self, text, lpz, name=None, speech_len=None
  ):
      """Preprocess text, and gather text and lpz into a task object.
  
      Text is pre-processed and tokenized depending on configuration.
      If ``speech_len`` is given, the timing configuration is updated.
      Text, lpz, and configuration is collected in a CTCSegmentationTask
      object. The resulting object can be serialized and passed in a
      multiprocessing computation.
  
      It is recommended that you normalize the text beforehand, e.g.,
      change numbers into their spoken equivalent word, remove special
      characters, and convert UTF-8 characters to chars corresponding to
      your ASR model dictionary.
  
      The text is tokenized based on the ``text_converter`` setting:
  
      The "tokenize" method is more efficient and the easiest for models
      based on latin or cyrillic script that only contain the main chars,
      ["a", "b", ...] or for Japanese or Chinese ASR models with ~3000
      short Kanji / Hanzi tokens.
  
      The "classic" method improves the the accuracy of the alignments
      for models that contain longer tokens, but with a greater complexity
      for computation. The function scans for partial tokens which may
      improve time resolution.
      For example, the word "▁really" will be broken down into
      ``['▁', '▁r', '▁re', '▁real', '▁really']``. The alignment will be
      based on the most probable activation sequence given by the network.
  
      Arguments
      ---------
      text : list
          List or multiline-string with utterance ground truths.
      lpz : np.ndarray
          Log CTC posterior probabilities obtained from the CTC-network;
          numpy array shaped as ( <time steps>, <classes> ).
      name : str
          Audio file name that will be included in the segments output.
          Choose a unique name, or the original audio
          file name, to distinguish multiple audio files. Default: None.
      speech_len : int
          Number of sample points. If given, the timing
          configuration is automatically derived from length of fs, length
          of speech and length of lpz. If None is given, make sure the
          timing parameters are correct, see time_stamps for reference!
          Default: None.
  
      Returns
      -------
      CTCSegmentationTask
          Task object that can be passed to
          ``CTCSegmentation.get_segments()`` in order to obtain alignments.
      """
      config = self.config
      # Update timing parameters, if needed
      if speech_len is not None:
          lpz_len = lpz.shape[0]
          timing_cfg = self.get_timing_config(speech_len, lpz_len)
          config.set(**timing_cfg)
      # `text` is needed in the form of a list.
      utt_ids, text = self._split_text(text)
      # Obtain utterance & label sequence from text
      if self.text_converter == "tokenize":
          # list of str --tokenize--> list of np.array
          token_list = [
              np.array(self._tokenizer.encode_as_ids(utt))
              for utt in text
          ]
          # filter out any instances of the <unk> token
          unk = config.char_list.index("<unk>")
          token_list = [utt[utt != unk] for utt in token_list]
          ground_truth_mat, utt_begin_indices = prepare_token_list(
              config, token_list
          )
      else:
          assert self.text_converter == "classic"
          text_pieces = [
              "".join(self._tokenizer.encode_as_pieces(utt))
              for utt in text
          ]
          # filter out any instances of the <unk> token
          text_pieces = [
              utt.replace("<unk>", "") for utt in text_pieces
          ]
          ground_truth_mat, utt_begin_indices = prepare_text(
              config, text_pieces
          )
      task = CTCSegmentationTask(
          config=config,
          name=name,
          text=text,
          ground_truth_mat=ground_truth_mat,
          utt_begin_indices=utt_begin_indices,
          utt_ids=utt_ids,
          lpz=lpz,
      )
      return task
  
imports: import logging
  from pathlib import Path
  from types import SimpleNamespace
  from typing import Optional
  from typing import Union
  import numpy
  import torch
  from typing import List
  from speechbrain.inference.ASR import EncoderASR, EncoderDecoderASR
label_desc: Use image node_id 7 for calling the CTCSegmentation obj's underlying member method code with example usage: obj.prepare_segmentation_task(text, lpz, name, speech_len) and returns: task