from typing import Sequence
from typing import Tuple
from typing import List


def _convert_answer_spans(answer_unigram_spans: Sequence[Tuple[int, int]],
                          unigram_to_token_map: Sequence[int],
                          num_tokens: int) -> List[Tuple[int, int]]:
  """Converts answer unigram spans to token spans."""
  answer_token_spans = []
  for unigram_begin, unigram_end in answer_unigram_spans:
    token_begin = unigram_to_token_map[unigram_begin]
    if unigram_end + 1 < len(unigram_to_token_map):
      token_end = unigram_to_token_map[unigram_end + 1] - 1
    else:
      token_end = num_tokens - 1
    answer_token_spans.append((token_begin, token_end))
  return answer_token_spans