code: def prepare_json(
      model_name,
      seg_lst,
      json_file,
      wavs_folder,
      csv_reader,
      phoneme_alignments_folder,
      durations_folder,
      pitch_folder,
      pitch_n_fft,
      pitch_hop_length,
      pitch_min_f0,
      pitch_max_f0,
      use_custom_cleaner=False,
      device="cpu",
  ):
      """
      Creates json file given a list of indexes.
  
      Arguments
      ---------
      model_name : str
          Model name (used to prepare additional model specific data)
      seg_lst : list
          The list of json indexes of a given data split
      json_file : str
          Output json path
      wavs_folder : str
          LJspeech wavs folder
      csv_reader : _csv.reader
          LJspeech metadata
      phoneme_alignments_folder : path
          Path where the phoneme alignments are stored
      durations_folder : path
          Folder where to store the duration values of each audio
      pitch_folder : path
          Folder where to store the pitch of each audio
      pitch_n_fft : int
          Number of fft points for pitch computation
      pitch_hop_length : int
          Hop length for pitch computation
      pitch_min_f0 : int
          Minimum f0 for pitch compuation
      pitch_max_f0 : int
          Max f0 for pitch computation
      use_custom_cleaner : bool
          If True, uses custom cleaner defined for this recipe
      device : str
          Device for to be used for computation (used as required)
  
      Returns
      -------
      None
      """
  
      logger.info(f"preparing {json_file}.")
      if model_name in ["Tacotron2", "FastSpeech2WithAlignment"]:
          logger.info(
              "Computing phonemes for LJSpeech labels using SpeechBrain G2P. This may take a while."
          )
          g2p = GraphemeToPhoneme.from_hparams(
              "speechbrain/soundchoice-g2p", run_opts={"device": device}
          )
      if model_name is not None and "FastSpeech2" in model_name:
          logger.info(
              "Computing pitch as required for FastSpeech2. This may take a while."
          )
  
      json_dict = {}
      for index in tqdm(seg_lst):
          # Common data preparation
          id = list(csv_reader)[index][0]
          wav = os.path.join(wavs_folder, f"{id}.wav")
          label = list(csv_reader)[index][2]
          if use_custom_cleaner:
              label = custom_clean(label, model_name)
  
          json_dict[id] = {
              "uttid": id,
              "wav": wav,
              "label": label,
              "segment": True if "train" in json_file else False,
          }
  
          # FastSpeech2 specific data preparation
          if model_name == "FastSpeech2":
              audio, fs = torchaudio.load(wav)
  
              # Parses phoneme alignments
              textgrid_path = os.path.join(
                  phoneme_alignments_folder, f"{id}.TextGrid"
              )
              textgrid = tgt.io.read_textgrid(
                  textgrid_path, include_empty_intervals=True
              )
  
              last_phoneme_flags = get_last_phoneme_info(
                  textgrid.get_tier_by_name("words"),
                  textgrid.get_tier_by_name("phones"),
              )
              (
                  phonemes,
                  duration,
                  start,
                  end,
                  trimmed_last_phoneme_flags,
              ) = get_alignment(
                  textgrid.get_tier_by_name("phones"),
                  fs,
                  pitch_hop_length,
                  last_phoneme_flags,
              )
  
              # Gets label phonemes
              label_phoneme = " ".join(phonemes)
              spn_labels = [0] * len(phonemes)
              for i in range(1, len(phonemes)):
                  if phonemes[i] == "spn":
                      spn_labels[i - 1] = 1
              if start >= end:
                  print(f"Skipping {id}")
                  continue
  
              # Saves durations
              duration_file_path = os.path.join(
                  durations_folder, f"{id}.npy"
              )
              np.save(duration_file_path, duration)
  
              # Computes pitch
              audio = audio[:, int(fs * start) : int(fs * end)]
              pitch_file = wav.replace(".wav", ".npy").replace(
                  wavs_folder, pitch_folder
              )
              if not os.path.isfile(pitch_file):
                  pitch = torchaudio.functional.detect_pitch_frequency(
                      waveform=audio,
                      sample_rate=fs,
                      frame_time=(pitch_hop_length / fs),
                      win_length=3,
                      freq_low=pitch_min_f0,
                      freq_high=pitch_max_f0,
                  ).squeeze(0)
  
                  # Concatenate last element to match duration.
                  pitch = torch.cat([pitch, pitch[-1].unsqueeze(0)])
  
                  # Mean and Variance Normalization
                  mean = 256.1732939688805
                  std = 328.319759158607
  
                  pitch = (pitch - mean) / std
  
                  pitch = pitch[: sum(duration)]
                  np.save(pitch_file, pitch)
  
              # Updates data for the utterance
              json_dict[id].update({"label_phoneme": label_phoneme})
              json_dict[id].update({"spn_labels": spn_labels})
              json_dict[id].update({"start": start})
              json_dict[id].update({"end": end})
              json_dict[id].update({"durations": duration_file_path})
              json_dict[id].update({"pitch": pitch_file})
              json_dict[id].update(
                  {"last_phoneme_flags": trimmed_last_phoneme_flags}
              )
  
          # FastSpeech2WithAlignment specific data preparation
          if model_name == "FastSpeech2WithAlignment":
              audio, fs = torchaudio.load(wav)
              # Computes pitch
              pitch_file = wav.replace(".wav", ".npy").replace(
                  wavs_folder, pitch_folder
              )
              if not os.path.isfile(pitch_file):
                  if torchaudio.__version__ < "2.1":
                      pitch = torchaudio.functional.compute_kaldi_pitch(
                          waveform=audio,
                          sample_rate=fs,
                          frame_length=(pitch_n_fft / fs * 1000),
                          frame_shift=(pitch_hop_length / fs * 1000),
                          min_f0=pitch_min_f0,
                          max_f0=pitch_max_f0,
                      )[0, :, 0]
                  else:
                      pitch = (
                          torchaudio.functional.detect_pitch_frequency(
                              waveform=audio,
                              sample_rate=fs,
                              frame_time=(pitch_hop_length / fs),
                              win_length=3,
                              freq_low=pitch_min_f0,
                              freq_high=pitch_max_f0,
                          ).squeeze(0)
                      )
  
                      # Concatenate last element to match duration.
                      pitch = torch.cat([pitch, pitch[-1].unsqueeze(0)])
  
                      # Mean and Variance Normalization
                      mean = 256.1732939688805
                      std = 328.319759158607
  
                      pitch = (pitch - mean) / std
  
                  np.save(pitch_file, pitch)
  
              phonemes = _g2p_keep_punctuations(g2p, label)
              # Updates data for the utterance
              json_dict[id].update({"phonemes": phonemes})
              json_dict[id].update({"pitch": pitch_file})
  
      # Writing the dictionary to the json file
      with open(json_file, mode="w") as json_f:
          json.dump(json_dict, json_f, indent=2)
  
      logger.info(f"{json_file} successfully created!")
  
imports: import os
  import csv
  import json
  import random
  import logging
  import torch
  import torchaudio
  import numpy
  from tqdm import tqdm
  from speechbrain.utils.data_utils import download_file
  from speechbrain.dataio.dataio import load_pkl, save_pkl
  import tgt
  from speechbrain.inference.text import GraphemeToPhoneme
  import re
  from unidecode import unidecode
  from speechbrain.utils.text_to_sequence import _g2p_keep_punctuations
label_desc: Use image node_id 4 for calling a global function with example usage: prepare_json(model_name, seg_lst, json_file, wavs_folder, csv_reader, phoneme_alignments_folder, durations_folder, pitch_folder, pitch_n_fft, pitch_hop_length, pitch_min_f0, pitch_max_f0, use_custom_cleaner, device) without return types