code: def main():
      """Run CFSD calculation."""
      args = get_parser().parse_args()
  
      # logging info
      if args.verbose > 1:
          logging.basicConfig(
              level=logging.DEBUG,
              format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
          )
      elif args.verbose > 0:
          logging.basicConfig(
              level=logging.INFO,
              format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
          )
      else:
          logging.basicConfig(
              level=logging.WARN,
              format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
          )
          logging.warning("Skip DEBUG/INFO messages")
  
      # find files
      if os.path.isdir(args.gen_wavdir_or_wavscp):
          gen_files = sorted(find_files(args.gen_wavdir_or_wavscp))
      else:
          with open(args.gen_wavdir_or_wavscp) as f:
              gen_files = [
                  line.strip().split(None, 1)[1]
                  for line in f.readlines()
              ]
          if gen_files[0].endswith("|"):
              raise ValueError("Not supported wav.scp format.")
      if os.path.isdir(args.gt_wavdir_or_wavscp):
          gt_files = sorted(find_files(args.gt_wavdir_or_wavscp))
      else:
          with open(args.gt_wavdir_or_wavscp) as f:
              gt_files = [
                  line.strip().split(None, 1)[1]
                  for line in f.readlines()
              ]
          if gt_files[0].endswith("|"):
              raise ValueError("Not supported wav.scp format.")
  
      if len(gen_files) == 0:
          raise FileNotFoundError(
              "Not found any generated audio files."
          )
      if len(gen_files) > len(gt_files):
          raise ValueError(
              "#groundtruth files are less than #generated files "
              f"(#gen={len(gen_files)} vs. #gt={len(gt_files)}). "
              "Please check the groundtruth directory."
          )
      logging.info("The number of utterances = %d" % len(gen_files))
  
      if torch.cuda.is_available() and ("cuda" in args.device):
          device = args.device
      else:
          device = "cpu"
  
      s3prl_frontend = S3prlFrontend(
          download_dir="./hub",
          frontend_conf={"upstream": args.pretrained_model},
      )
      s3prl_frontend.to(device)
  
      # calculate CFSD
      cfsd_dict = dict()
      for i, gen_path in enumerate(gen_files):
          corresponding_list = list(
              filter(
                  lambda gt_path: _get_basename(gt_path) in gen_path,
                  gt_files,
              )
          )
          assert len(corresponding_list) == 1
          gt_path = corresponding_list[0]
          gt_basename = _get_basename(gt_path)
  
          # load wav file as float64
          gen_x, gen_fs = sf.read(gen_path, dtype="float64")
          gt_x, gt_fs = sf.read(gt_path, dtype="float64")
  
          # NOTE: resample because s3prl models support only 16kHz audio currently.
          gen_x = librosa.resample(
              gen_x, orig_sr=gen_fs, target_sr=16000
          )
          gt_x = librosa.resample(gt_x, orig_sr=gt_fs, target_sr=16000)
  
          # prepare input
          gen_x = torch.FloatTensor(gen_x).unsqueeze(0).to(device)
          gen_x_length = torch.LongTensor([gen_x.shape[1]]).to(device)
          gt_x = torch.FloatTensor(gt_x).unsqueeze(0).to(device)
          gt_x_length = torch.LongTensor([gt_x.shape[1]]).to(device)
  
          # speech embedding
          gen_embeds, gen_embeds_len = s3prl_frontend(
              gen_x, gen_x_length
          )  # (B,H)
          gt_embeds, gt_embeds_len = s3prl_frontend(
              gt_x, gt_x_length
          )  # (B,H)
          gen_embeds = gen_embeds.detach().cpu().numpy()[0]
          gt_embeds = gt_embeds.detach().cpu().numpy()[0]
  
          # speech distance
          gen_mu = np.mean(gen_embeds, axis=0)
          gt_mu = np.mean(gt_embeds, axis=0)
          gen_sigma = np.cov(gen_embeds, rowvar=False)
          gt_sigma = np.cov(gt_embeds, rowvar=False)
          cfsd = calculate_frechet_distance(
              gen_mu, gen_sigma, gt_mu, gt_sigma
          )
          logging.info(f"{gt_basename} {cfsd:.4f}")
          cfsd_dict[gt_basename] = cfsd
  
      # calculate statistics
      mean_cfsd = np.mean(np.array([v for v in cfsd_dict.values()]))
      std_cfsd = np.std(np.array([v for v in cfsd_dict.values()]))
      logging.info(f"Average: {mean_cfsd:.4f} ± {std_cfsd:.4f}")
  
      # write results
      if args.outdir is None:
          if os.path.isdir(args.gen_wavdir_or_wavscp):
              args.outdir = args.gen_wavdir_or_wavscp
          else:
              args.outdir = os.path.dirname(args.gen_wavdir_or_wavscp)
      os.makedirs(args.outdir, exist_ok=True)
      with open(f"{args.outdir}/utt2cfsd", "w") as f:
          for utt_id in sorted(cfsd_dict.keys()):
              cfsd = cfsd_dict[utt_id]
              f.write(f"{utt_id} {cfsd:.4f}\n")
      with open(f"{args.outdir}/cfsd_avg_result.txt", "w") as f:
          f.write(f"#utterances: {len(gen_files)}\n")
          f.write(f"Average: {mean_cfsd:.4f} ± {std_cfsd:.4f}")
  
      logging.info("Successfully finished CFSD evaluation.")
  
file_path: espnet/egs2/mustard/asr1/pyscripts/utils/evaluate_cfsd.py
imports: import argparse
  import fnmatch
  import logging
  import os
  from typing import List
  import librosa
  import numpy
  import soundfile
  import torch
  from scipy import linalg
  from espnet2.asr.frontend.s3prl import S3prlFrontend
label_desc: Use image node_id 5 for calling a global function with example usage: main() without return types