def get_matches_from_labeled_sequence(labels):
    """ From a list of BIO tags, condense into tuples of (start-token-index, end-token-index, tag)
    E.g.:
    index:  0  1     2       3         4         5     6   7
    token: In an explosion , many      people    will get hurt
    labels: O  O     O       B-Patient I-Patient O     O   O

    We generate: (3, 4, Patient)

    :type labels: list[str]
    """
    matches = []
    i = 0
    while i < len(labels):
        start = None
        end = None

        if labels[i] != 'O':
            if i == 0:
                start = i
            else:
                if labels[i].startswith('B-') or (labels[i] != labels[i - 1]):
                    start = i

        if start is not None:
            end = start + 1
            while end < len(labels):
                if labels[end] == 'O':
                    break
                elif labels[end].startswith('B-'):
                    break
                else:  # starts with 'I-'
                    if labels[start][2:] != labels[end][2:]:
                        break
                end += 1

        if start is not None and end is not None:
            matches.append((start, end - 1, labels[start][2:]))
            i = end
        else:
            i += 1

    return matches