import random


def build_batches(sentences, batch_size, num_chunks_in_batch=1):
    """
    Randomize batches sequences along sentences if dataset indexes.
    https://gist.github.com/pommedeterresautee/1a334b665710bec9bb65965f662c94c8#file-trainer-py-L181
    https://wandb.ai/pommedeterresautee/speed_training/reports/Train-HuggingFace-Models-Twice-As-Fast--VmlldzoxMDgzOTI

    Args:
        sentences (list): List of samples.
        batch_size (int): Batch size.
        num_chunks_in_batch (int, optional): Training batch should consist of
            several "chunks" of samples with different sequece lengths to make
            training more random. Default is 1, which mean in batch would be
            samples with the same length.
    """
    chunk_size = int(batch_size/num_chunks_in_batch)
    batch_ordered_sentences = list()
    while len(sentences) > 0:
        to_take = min(chunk_size, len(sentences))
        select = random.randint(0, len(sentences) - to_take)
        batch_ordered_sentences += sentences[select:select + to_take]
        del sentences[select:select + to_take]
    return batch_ordered_sentences