code: def align_f0_to_durations(f0, durations, f0_code_ratio, tol=1):
      code_len = durations.sum()
      targ_len = int(f0_code_ratio * code_len)
      diff = f0.size(0) - targ_len
      assert abs(diff) <= tol, (
          f"Cannot subsample F0: |{f0.size(0)} - {f0_code_ratio}*{code_len}|"
          f" > {tol} (dur=\n{durations})"
      )
      if diff > 0:
          f0 = f0[:targ_len]
      elif diff < 0:
          f0 = torch.cat((f0, f0.new_full((-diff,), f0[-1])), 0)
  
      f0_offset = 0.0
      seg_f0s = []
      for dur in durations:
          f0_dur = dur.item() * f0_code_ratio
          seg_f0 = f0[int(f0_offset) : int(f0_offset + f0_dur)]
          seg_f0 = seg_f0[seg_f0 != 0]
          if len(seg_f0) == 0:
              seg_f0 = torch.tensor(0).type(seg_f0.type())
          else:
              seg_f0 = seg_f0.mean()
          seg_f0s.append(seg_f0)
          f0_offset += f0_dur
  
      assert int(f0_offset) == f0.size(
          0
      ), f"{f0_offset} {f0.size()} {durations.sum()}"
      return torch.tensor(seg_f0s)
  
imports: import json
  import logging
  import os
  import random
  from pathlib import Path
  import numpy
  import torch
  import torch.utils.data
  from .None import data_utils
  from fairseq.data.fairseq_dataset import FairseqDataset
label_desc: Use image node_id 9 for calling a global function with example usage: align_f0_to_durations(f0, durations, f0_code_ratio, tol) and returns: torch