from typing import Counter
import itertools


def build_vocab(sentences, max_vocab=30000):
    """
    Builds a vocabulary mapping from word to index based on the sentences.
    Returns vocabulary mapping and inverse vocabulary mapping.
    """

    # Build vocabulary. Cap to a max.
    word_counts = Counter(itertools.chain(*sentences))
    # Mapping from index to word. Use the 'max_vocab' most common.
    vocabulary_inv = [x[0] for x in word_counts.most_common(max_vocab)]
    vocabulary_inv = list(sorted(vocabulary_inv))
    # Mapping from word to index
    vocabulary = {x: i for i, x in enumerate(vocabulary_inv)}
    return [vocabulary, vocabulary_inv]