code: def add_spectrogram_from_audio(
      parser_builder,
      sampler_builder,
      preprocessor_builder,
      input_feature_name="WAVEFORM/feature/floats",
      output_feature_name="spectrogram",
      is_training=True,
      # Wave related parameters (stride is always assumed to be 1).
      sample_rate: int = 16000,
      add_gaussian_noise: bool = False,
      add_masking_noise: bool = False,
      snr: Optional[float] = None,
      visualness_score_threshold: float = 0.2,
      random_mask_noise_rate: float = 0.4,
      max_word_len: int = 128,
      max_num_masks: int = -1,
      extend_mask_boundaries_ms: float = 0.0,
      add_word_mask: bool = True,
      add_word_mask_info: bool = False,
      eval_noise_types: Sequence[str] = tuple(),
      environment_noise_configs: Optional[Dict[str, Any]] = None,
      environment_noise_path: Optional[str] = None,
      packet_loss_noise_configs: Optional[Dict[str, Any]] = None,
      aligned_caption_feature_name: str = "caption/label/string",
      word_tokenizer: Optional[tokenizers.TextTokenizer] = None,
      max_num_word_tokens: int = 8,
      prepend_bos: bool = True,
      append_eos: bool = True,
      patch_size: Sequence[int] = tuple(),
      max_num_masked_input_indices: int = 64,
      # Spectrogram computation parameters.
      spectrogram_type: str = "logmf",
      frame_length: int = 400,
      frame_step: int = 160,
      num_features: int = 80,
      lower_edge_hertz: float = 80.0,
      upper_edge_hertz: float = 7600.0,
      # Spectrogram related parameters.
      num_frames=5,
      spec_augment=True,
      spec_augment_params=None,
      zero_centering_image=False,
      dataset_mean=0.0,
      dataset_stddev=1.0,
  ):
      """Add audio spectrogram computed from waveform.
  
      Args:
        parser_builder: An instance of a builders.BaseParserBuilder.
        sampler_builder: An instance of a builders.SamplerBuilder.
        preprocessor_builder: An instance of a builders.PreprocessorBuilder.
        input_feature_name: Name of the feature in the input SequenceExample.
          Exposing this as an argument allows using this function for different
          image features.
        output_feature_name: Name of the feature in the output features dictionary.
        is_training: Whether or not in training mode.
        sample_rate: The sample rate of the input audio.
        add_gaussian_noise: Whether to add Gaussian noise.
        add_masking_noise: Whether to add word masking noise.
        snr: Signal-to-noise ratio used to inject white noise. For word masking
          noise, white noise is added to the masked region. If None, no white noise
          is added to the masked region.
        visualness_score_threshold: The threshold for determining the visual words.
        random_mask_noise_rate: The random mask noise sampling ratio. If 1, the word
          masking is deterministic. If below 1, the masking noise is random and each
          word is masked out with this chance.
        max_word_len: Maximum length of the words. This is used to pad and truncate
          noise_word_mask added to the batch dictionary in the word masking noise
          addition.
        max_num_masks: Maximum number of word masks to apply. -1 means unlimited.
        extend_mask_boundaries_ms: If set, the start and end boundaries of each
          maksing region in the signal is extended.
        add_word_mask: If set, add masks indicating masked words into the batch
          dict. Used for computing recovery rate of the masked words.
        add_word_mask_info: If set, add word masking related information such as
          timestamps and masks to the batch dict. Used for applying masked word
          prediction loss.
        eval_noise_types: A tuple of noise type strings used in evaluation. Each
          string should be either `environment_noise` or `packet_loss_noise`.
        environment_noise_configs: A config dict for environment noise addition.
          Used if eval_noise_types contain `environment_noise`. The dict contains
          `snr`.
        environment_noise_path: Path to the npy file containing noise waveforms in
          numpy array.
        packet_loss_noise_configs: A config dict for packet loss noise addition.
          Used if eval_noise_types contain `packet_loss_noise`. The dict contains
          `max_num_bursts` and `max_length_rate`.
        aligned_caption_feature_name: The feature name to parse to extract the
          caption aligned with the timestamps. Used for the masked word prediction.
        word_tokenizer: Tokenizer used to tokenize the masked words for masked word
          prediction.
        max_num_word_tokens: Maximum number of tokens for each masked word.
        prepend_bos: Whether to add BOS token to a tokenized word.
        append_eos: Whether to add EOS token to a tokenized word.
        patch_size: The patch size used in the network architecture for spectrogram
          token embedding. Used to compute the token index.
        max_num_masked_input_indices: Maximum number of masked input tokens
          (spectrogram tokens).
        spectrogram_type: The type of the spectrogram to be extracted from the
          waveform. Can be either `spectrogram`, `logmf`, and `mfcc`.
        frame_length: The length of each spectroram frame.
        frame_step: The stride of spectrogram frames.
        num_features: The number of spectrogram features.
        lower_edge_hertz: Lowest frequency to consider.
        upper_edge_hertz: Highest frequency to consider.  crop are used.
        num_frames: Number of seconds to sample per subclip.
        spec_augment: Whether to apply augmentation using SpecAugment.
        spec_augment_params: Dict of parameters for SpecAugment.
        zero_centering_image: If `True`, frames are normalized to values in [-1, 1].
          If `False`, values in [0, 1].
        dataset_mean: Mean of values over the dataset.
        dataset_stddev: Standard deviation of values of the dataset.
      """
  
      ##############################################################################
      ### Load audio signal and sample from the beginning.
      ##############################################################################
      # Keep audio signal.
      parser_builder.parse_feature(
          feature_name=input_feature_name,
          # Entire signal stored in one Feature.
          feature_type=tf.io.VarLenFeature(dtype=tf.float32),
          output_name=output_feature_name,
      )
  
      # Densify and flatten.
      sampler_builder.add_fn(
          fn=lambda x: tf.reshape(tf.sparse.to_dense(x), [-1]),
          feature_name=output_feature_name,
          fn_name=f"{output_feature_name}_sparse_to_dense",
      )
  
      # Add noise
      if eval_noise_types:
          for noise_type in eval_noise_types:
              if noise_type not in VALID_EVAL_NOISE_TYPES:
                  raise ValueError(
                      f"noise_type `{noise_type}` not supported."
                  )
          if "environment_noise" in eval_noise_types:
              # Load environment noise samples dumped in a numpy array in a .npy file.
              with tf.io.gfile.GFile(environment_noise_path, "rb") as f:
                  noise_db = tf.constant(np.load(f), tf.float32)
              sampler_builder.add_fn(
                  fn=functools.partial(
                      add_environment_noise,
                      **environment_noise_configs,
                      noise_db=noise_db,
                  ),
                  feature_name=output_feature_name,
                  fn_name=f"{output_feature_name}_add_environment_noise",
              )
          if "packet_loss_noise" in eval_noise_types:
              sampler_builder.add_fn(
                  fn=functools.partial(
                      add_packet_loss_noise, **packet_loss_noise_configs
                  ),
                  feature_name=output_feature_name,
                  fn_name=f"{output_feature_name}_add_packet_loss_noise",
              )
  
      if add_masking_noise:
          logging.info("Adding word masking noise to the signal.")
          # First, parse related data: visualness score, word start and end timestamps
          parser_builder.parse_feature(
              feature_name="clip/label/align/visualness",
              feature_type=tf.io.VarLenFeature(dtype=tf.float32),
              output_name="visualness_score",
              is_context=True,
          )
  
          parser_builder.parse_feature(
              feature_name="clip/label/align/start_ms",
              feature_type=tf.io.VarLenFeature(dtype=tf.float32),
              output_name="word_start_timestamp",
              is_context=True,
          )
  
          parser_builder.parse_feature(
              feature_name="clip/label/align/end_ms",
              feature_type=tf.io.VarLenFeature(dtype=tf.float32),
              output_name="word_end_timestamp",
              is_context=True,
          )
  
          # Densify and flatten.
          sampler_builder.add_fn(
              fn=tf.sparse.to_dense,
              feature_name="visualness_score",
              fn_name="visualness_score_sparse_to_dense",
          )
  
          sampler_builder.add_fn(
              fn=tf.sparse.to_dense,
              feature_name="word_start_timestamp",
              fn_name="word_start_timestamp_sparse_to_dense",
          )
  
          sampler_builder.add_fn(
              fn=tf.sparse.to_dense,
              feature_name="word_end_timestamp",
              fn_name="word_end_timestamp_sparse_to_dense",
          )
  
          sampler_builder.add_fn(
              fn=functools.partial(
                  add_visual_word_masking_noise,
                  wave_feature_name=output_feature_name,
                  snr=snr,
                  sample_rate=sample_rate,
                  vis_threshold=visualness_score_threshold,
                  max_word_len=max_word_len,
                  mask_rate=random_mask_noise_rate,
                  max_num_masks=max_num_masks,
                  extend_boundaries_ms=extend_mask_boundaries_ms,
                  add_word_mask=add_word_mask,
                  add_word_mask_info=add_word_mask_info,
              ),
              fn_name=f"{output_feature_name}_add_masking_noise",
          )
      elif add_gaussian_noise and snr is not None and snr > 0.0:
          logging.info("Adding Gaussian white noise to the signal.")
          sampler_builder.add_fn(
              fn=lambda x: add_white_noise(x, snr),
              feature_name=output_feature_name,
              fn_name=f"{output_feature_name}_add_white_noise",
          )
      else:
          logging.info("Adding no noise to the signal.")
  
      # Normalize the waveform before spectrogram computation.
      sampler_builder.add_fn(
          fn=normalize_input,
          feature_name=output_feature_name,
          fn_name=f"{output_feature_name}_normalize",
      )
  
      ##############################################################################
      ### Compute spectrograms from the loaded audio.
      ##############################################################################
      # Extract audio spectrograms.
      sampler_builder.add_fn(
          functools.partial(
              processors.compute_audio_spectrogram,
              sample_rate=sample_rate,
              spectrogram_type=spectrogram_type,
              frame_length=frame_length,
              frame_step=frame_step,
              num_features=num_features,
              lower_edge_hertz=lower_edge_hertz,
              upper_edge_hertz=upper_edge_hertz,
              audio_feature_name=output_feature_name,
              spectrogram_feature_name=output_feature_name,
          )
      )
  
      ##############################################################################
      ### Generate meta data needed for masked word prediction.
      ##############################################################################
      if add_masking_noise and add_word_mask_info:
          sampler_builder.add_fn(
              fn=functools.partial(
                  convert_ms_to_frame_number,
                  spectrogram_feature_name=output_feature_name,
              ),
              fn_name="word_mask_info_convert_ms_to_frame_number",
          )
          add_text_untokenized(
              parser_builder,
              sampler_builder,
              aligned_caption_feature_name,
              "mwp_caption_string",
          )
          sampler_builder.add_fn(
              fn=functools.partial(
                  tokenize_masked_words,
                  tokenizer=word_tokenizer,
                  max_num_tokens=max_num_word_tokens,
                  prepend_bos=prepend_bos,
                  append_eos=append_eos,
              ),
              fn_name="word_mask_info_tokenize_masked_words",
          )
  
      ##############################################################################
      ### Preprocess the computed spectrograms.
      ##############################################################################
  
      # We apply spec_augment after the signal truncation but before padding.
      # In this way, we apply spec_augment to the valid signals only excluding
      # padding and the truncated non-target signals.
  
      # Temporal sampling (beginning_sample)
      num_time_bins = tf.cast(
          num_frames * (sample_rate / frame_step), dtype=tf.int32
      )
      preprocessor_builder.add_fn(
          fn=lambda x: x[:num_time_bins],
          feature_name=output_feature_name,
          fn_name=f"{output_feature_name}_beginning_sample",
      )
  
      preprocessor_builder.add_fn(
          # pylint: disable=g-long-lambda
          fn=lambda x: _decode_spectrogram(
              x,
              True,
              zero_centering_image,
              dataset_mean,
              dataset_stddev,
          ),
          # pylint: enable=g-long-lambda
          feature_name=output_feature_name,
          fn_name=f"{output_feature_name}_decode_spectrogram",
      )
  
      if is_training and spec_augment:
          # Apply specaugment
          preprocessor_builder.add_fn(
              fn=lambda x, s=None: apply_specaugment(
                  x, spec_augment_params
              ),
              feature_name=output_feature_name,
              fn_name=f"{output_feature_name}_specaugment",
          )
  
      # Padding
      pad_value = 0.0
      preprocessor_builder.add_fn(
          fn=lambda x: pad_first_dim(x, num_time_bins, pad_value),
          feature_name=output_feature_name,
          fn_name=f"{output_feature_name}_pad",
      )
  
      ##############################################################################
      ### Finalize the word mask info by truncating, padding and converting indices.
      ##############################################################################
      if add_masking_noise and add_word_mask_info:
          preprocessor_builder.add_fn(
              fn=functools.partial(
                  finalize_word_mask_info,
                  spectrogram_feature_name=output_feature_name,
                  patch_size=patch_size,
                  max_num_word_masks=max_num_masks,
                  max_num_masked_input_indices=max_num_masked_input_indices,
              ),
              fn_name="finalize_word_mask_info",
          )
  
imports: import functools
  from typing import Any, Dict, Optional, Sequence
  from absl import logging
  from dmvr import builders
  from dmvr import processors
  from dmvr import tokenizers
  import numpy
  from scenic.projects.mbt.datasets.dataset_utils import _decode_spectrogram
  from scenic.projects.mbt.datasets.dataset_utils import apply_specaugment
  import tensorflow
label_desc: Use image node_id 11 for calling a global function with example usage: add_spectrogram_from_audio(parser_builder, sampler_builder, preprocessor_builder, input_feature_name, output_feature_name, is_training, sample_rate, add_gaussian_noise, add_masking_noise, snr, visualness_score_threshold, random_mask_noise_rate, max_word_len, max_num_masks, extend_mask_boundaries_ms, add_word_mask, add_word_mask_info, eval_noise_types, environment_noise_configs, environment_noise_path, packet_loss_noise_configs, aligned_caption_feature_name, word_tokenizer, max_num_word_tokens, prepend_bos, append_eos, patch_size, max_num_masked_input_indices, spectrogram_type, frame_length, frame_step, num_features, lower_edge_hertz, upper_edge_hertz, num_frames, spec_augment, spec_augment_params, zero_centering_image, dataset_mean, dataset_stddev) without return types