from typing import Counter


def get_polaity_chunks(seq, aspect_lab_chunks, default="O", must_predict=False):
    """
    Args:
        seq: [POSITIVE, O, POSITIVE, POSITIVE, NEUTRAL, O, POSITIVE, NEUTRAL, NEUTRAL, O, POSITIVE] sequence of labels
        aspect_lab_chunks: [('AP', 0, 1), ('AP', 2, 3), ('AP', 3, 5), ('AP', 6, 9), ('AP', 10, 11)]
    Returns:
        list of (chunk_type, chunk_start, chunk_end)
    Example:
        seq = ["POSITIVE", "O", "POSITIVE", "POSITIVE", "NEUTRAL", "O", "POSITIVE", "NEUTRAL", "NEUTRAL", "O", "POSITIVE"]
        aspect_lab_chunks = [('AP', 0, 1), ('AP', 2, 3), ('AP', 3, 5), ('AP', 6, 9), ('AP', 10, 11)]
        result = [('POSITIVE', 0, 1), ('POSITIVE', 2, 3), ('POSITIVE', 3, 5), ('NEUTRAL', 6, 9), ('POSITIVE', 10, 11)]
    """
    chunks = []
    for i, chunk in enumerate(aspect_lab_chunks):
        segs = seq[chunk[1]:chunk[2]]
        ins_counter = Counter(segs)
        if len(ins_counter) > 1:
            chunk_type = ins_counter.most_common(1)[0][0]
            if default != chunk_type:
                chunk_type = ins_counter.most_common(2)[1][0]
        else:
            chunk_type = ins_counter.most_common(1)[0][0]
        if must_predict or default != chunk_type:
            chunk = (chunk_type, chunk[1], chunk[2])
            chunks.append(chunk)
    return chunks