def find_nearest_wordpiece_index(offset_index, offset_to_wp, scan_right=True):
  """According to offset_to_wp dictionary, find the wordpiece index for offset.

  Some offsets do not have mapping to word piece index if they are delimited.
  If scan_right is True, we return the word piece index of nearest right byte,
  nearest left byte otherwise.

  Args:
    offset_index: the target byte offset.
    offset_to_wp: a dictionary mapping from byte offset to wordpiece index.
    scan_right: When there is no valid wordpiece for the offset_index, will
      consider offset_index+i if this is set to True, offset_index-i otherwise.

  Returns:
    The index of the nearest word piece of `offset_index`
    or -1 if no match is possible.
  """

  for i in range(0, len(offset_to_wp.items())):
    next_ind = offset_index + i if scan_right else offset_index - i
    if next_ind >= 0 and next_ind in offset_to_wp:
      return_ind = offset_to_wp[next_ind]
      # offset has a match.
      if return_ind > -1:
        return return_ind
  return -1