code: def diarize_session(
      sess_name,
      pipeline,
      wav_files,
      uem_boundaries=None,
      merge_closer_delta=1.5,
      max_length_merged=60,
      max_n_speakers=4,
  ):
      # take the min len across all wavs
      minlen = min([sf.SoundFile(w).frames for w in wav_files])
      fs = sf.SoundFile(wav_files[0]).samplerate
      if uem_boundaries is not None:
          uem_boundaries = [round(x * fs) for x in uem_boundaries]
      else:
          uem_boundaries = [0, minlen]
  
      # now for each audio file run inference
      all_segmentation = []
      all_audio = []
      print(
          "Running Segmentation on each of the {} channels".format(
              len(wav_files)
          )
      )
      for w_f in wav_files:
          c_audio, c_fs = sf.read(w_f, dtype="float32")
          assert fs == c_fs
          c_audio = c_audio[: min(minlen, uem_boundaries[1])]
          c_audio = c_audio[uem_boundaries[0] :]
          c_audio = torch.from_numpy(c_audio[None, ...])
          if (c_audio**2).mean() < 1e-8:
              print(
                  "Not running inference on {}, because the signal amplitude is "
                  "too low, is it all zeros ?".format(c_audio)
              )
              continue
          if IS_CUDA:
              c_audio = c_audio.cuda()
          c_seg = pipeline.get_segmentations(
              {"waveform": c_audio, "sample_rate": fs}
          )
          c_seg = binarize(
              c_seg,
              onset=pipeline.segmentation.threshold,
              initial_state=False,
          )
  
          all_segmentation.append(
              c_seg
          )  # move to cpu for less mem consumption
          all_audio.append(c_audio)
  
      # here we select the best channel based on one with most activations.
      # not an optimal criterion but at least the clustering afterwards will be fast.
      sliding_window = all_segmentation[0].sliding_window
      all_audio = torch.cat(all_audio, 0)
      num_channels = all_audio.shape[0]
      num_chunks, frames, local_spk = all_segmentation[0].data.shape
      all_segmentation = SlidingWindowFeature(
          np.stack([x.data for x in all_segmentation], -1),
          sliding_window,
      )
  
      selected_audio = torch.zeros_like(c_audio)
      selected_seg = []
      print(
          "Running Channel Selection by using the segmentation output"
      )
      for indx, (seg_b, segmentation) in enumerate(all_segmentation):
          c_seg = all_audio[
              :,
              math.floor(seg_b.start * fs) : math.floor(seg_b.end * fs),
          ]
          # median filter here seems to improve performance on chime6 in high overlap
          # conditions
          segmentation = medfilt2d(
              segmentation.reshape((frames, local_spk * num_channels)),
              (7, 1),
          ).reshape((frames, local_spk, num_channels))
          # why not the fine-tuned model is used ?
          # because that one is trained on chime6 to be robust against noise and
          # reverberation and position of the mic.
          # we want instead a model that is not so robust against that to use
          # to select the best channel from which the embeddings will be extracted.
          selection = np.argmax(
              segmentation.sum((0, 1))
          )  # not the best selection criteria
          # however this keeps it simple and fast.
          selected_audio[
              :,
              math.floor(seg_b.start * fs) : math.floor(seg_b.end * fs),
          ] = c_seg[selection]
          selected_seg.append(segmentation[..., selection])
      # stack em
      selected_seg = SlidingWindowFeature(
          np.stack([x.data for x in selected_seg]), sliding_window
      )
      count = Inference.trim(
          selected_seg, warm_up=(0.1, 0.1)
      )  # default value in Pyannote
      count = Inference.aggregate(
          np.sum(count, axis=-1, keepdims=True),
          frames=pipeline._frames,
          hamming=False,
          missing=0.0,
          skip_average=False,
      )
      count.data = np.rint(count.data).astype(np.uint8)
      print("Extracting Embeddings.")
      embeddings = pipeline.get_embeddings(
          {"waveform": selected_audio, "sample_rate": fs},
          selected_seg,
          exclude_overlap=pipeline.embedding_exclude_overlap,
      )
      #  shape: (num_chunks, local_num_speakers, dimension)
      print("Clustering.")
      hard_clusters, _ = pipeline.clustering(
          embeddings=embeddings,
          segmentations=selected_seg,
          num_clusters=None,
          min_clusters=0,
          max_clusters=max_n_speakers,  # max-speakers are ok
          file={
              "waveform": selected_audio,
              "sample_rate": fs,
          },  # <== for oracle clustering
          frames=pipeline._frames,  # <== for oracle clustering
      )
      # reconstruct discrete diarization from raw hard clusters
      # keep track of inactive speakers
      inactive_speakers = np.sum(selected_seg.data, axis=1) == 0
      #  shape: (num_chunks, num_speakers)
      hard_clusters[inactive_speakers] = -2
      # reshape now to multi-channel
      discrete_diarization = pipeline.reconstruct(
          selected_seg,
          hard_clusters,
          count,
      )
      # convert to annotation
      to_annotation = Binarize(
          onset=0.5,
          offset=0.5,
          min_duration_on=pipeline.segmentation.min_duration_on,
          min_duration_off=pipeline.segmentation.min_duration_off,
          pad_onset=pipeline.segmentation.pad_onset,
          pad_offset=pipeline.segmentation.pad_offset,
      )
      result = to_annotation(discrete_diarization)
      offset = uem_boundaries[0] / fs
      new_annotation = Annotation(uri=sess_name)  # new annotation
      speakers = result.labels()
      for spk in speakers:
          for seg in result.label_timeline(spk):
              new_annotation[
                  Segment(seg.start + offset, seg.end + offset)
              ] = spk
  
      new_annotation = merge_closer(
          new_annotation,
          delta=merge_closer_delta,
          max_len=max_length_merged,
          min_len=10,
      )
      return new_annotation
  
imports: import argparse
  import glob
  import json
  import math
  import os.path
  import re
  from pathlib import Path
  import numpy
  import soundfile
  import torch
  from pyannote.audio import Model, Pipeline
  from pyannote.audio.core.inference import Inference
  from pyannote.audio.pipelines import SpeakerDiarization
  from pyannote.audio.utils.signal import Binarize, binarize
  from pyannote.core import SlidingWindowFeature
  from pyannote.metrics.segmentation import Annotation, Segment
  from scipy.signal import medfilt2d
label_desc: Use image node_id 4 for calling a global function with example usage: diarize_session(sess_name, pipeline, wav_files, uem_boundaries, merge_closer_delta, max_length_merged, max_n_speakers) and returns: new_annotation