docstr: Perform preprocessing and create a final data batch:
  1. Sort batch instances by text-length
  2. Convert Audio signal to Spectrograms.
  3. PAD sequences wrt r.
  4. Load to Torch.
docstr_tok: ["Perform","preprocessing","and","create","a","final","data","batch",":","1",".","Sort","batch","instances","by","text-length","2",".","Convert","Audio","signal","to","Spectrograms",".","3",".","PAD","sequences","wrt","r.","4",".","Load","to","Torch","."]
code: def collate_fn(self, batch):
      r"""
      Perform preprocessing and create a final data batch:
      1. Sort batch instances by text-length
      2. Convert Audio signal to Spectrograms.
      3. PAD sequences wrt r.
      4. Load to Torch.
      """
  
      # Puts each data field into a tensor with outer dimension batch size
      if isinstance(batch[0], collections.Mapping):
          text_lenghts = np.array([len(d["text"]) for d in batch])
  
          # sort items with text input length for RNN efficiency
          text_lenghts, ids_sorted_decreasing = torch.sort(
              torch.LongTensor(text_lenghts), dim=0, descending=True
          )
  
          wav = [batch[idx]["wav"] for idx in ids_sorted_decreasing]
          item_idxs = [
              batch[idx]["item_idx"] for idx in ids_sorted_decreasing
          ]
          text = [batch[idx]["text"] for idx in ids_sorted_decreasing]
  
          speaker_name = [
              batch[idx]["speaker_name"]
              for idx in ids_sorted_decreasing
          ]
          # get speaker embeddings
          if self.speaker_mapping is not None:
              wav_files_names = [
                  batch[idx]["wav_file_name"]
                  for idx in ids_sorted_decreasing
              ]
              speaker_embedding = [
                  self.speaker_mapping[w]["embedding"]
                  for w in wav_files_names
              ]
          else:
              speaker_embedding = None
          # compute features
          mel = [
              self.ap.melspectrogram(w).astype("float32") for w in wav
          ]
  
          mel_lengths = [m.shape[1] for m in mel]
  
          # compute 'stop token' targets
          stop_targets = [
              np.array([0.0] * (mel_len - 1) + [1.0])
              for mel_len in mel_lengths
          ]
  
          # PAD stop targets
          stop_targets = prepare_stop_target(
              stop_targets, self.outputs_per_step
          )
  
          # PAD sequences with longest instance in the batch
          text = prepare_data(text).astype(np.int32)
  
          # PAD features with longest instance
          mel = prepare_tensor(mel, self.outputs_per_step)
  
          # B x D x T --> B x T x D
          mel = mel.transpose(0, 2, 1)
  
          # convert things to pytorch
          text_lenghts = torch.LongTensor(text_lenghts)
          text = torch.LongTensor(text)
          mel = torch.FloatTensor(mel).contiguous()
          mel_lengths = torch.LongTensor(mel_lengths)
          stop_targets = torch.FloatTensor(stop_targets)
  
          if speaker_embedding is not None:
              speaker_embedding = torch.FloatTensor(speaker_embedding)
  
          # compute linear spectrogram
          if self.compute_linear_spec:
              linear = [
                  self.ap.spectrogram(w).astype("float32") for w in wav
              ]
              linear = prepare_tensor(linear, self.outputs_per_step)
              linear = linear.transpose(0, 2, 1)
              assert mel.shape[1] == linear.shape[1]
              linear = torch.FloatTensor(linear).contiguous()
          else:
              linear = None
  
          # collate attention alignments
          if batch[0]["attn"] is not None:
              attns = [
                  batch[idx]["attn"].T for idx in ids_sorted_decreasing
              ]
              for idx, attn in enumerate(attns):
                  pad2 = mel.shape[1] - attn.shape[1]
                  pad1 = text.shape[1] - attn.shape[0]
                  attn = np.pad(attn, [[0, pad1], [0, pad2]])
                  attns[idx] = attn
              attns = prepare_tensor(attns, self.outputs_per_step)
              attns = torch.FloatTensor(attns).unsqueeze(1)
          else:
              attns = None
          return (
              text,
              text_lenghts,
              speaker_name,
              linear,
              mel,
              mel_lengths,
              stop_targets,
              item_idxs,
              speaker_embedding,
              attns,
          )
  
      raise TypeError(
          (
              "batch must contain tensors, numbers, dicts or lists;\
                           found {}".format(
                  type(batch[0])
              )
          )
      )
  
imports: import collections
  import os
  import random
  from multiprocessing import Manager, Pool
  import numpy
  import torch
  import tqdm
  from torch.utils.data import Dataset
  from TTS.tts.utils.data import prepare_data, prepare_stop_target, prepare_tensor
  from TTS.tts.utils.text import pad_with_eos_bos, phoneme_to_sequence, text_to_sequence
label_desc: Use image node_id 12 for calling the MyDataset obj's underlying member method code with example usage: obj.collate_fn(batch) and returns: text,  text_lenghts,  speaker_name,  linear,  mel,  mel_lengths,  stop_targets,  item_idxs,  speaker_embedding,  attns