# Copied from https://github.com/huggingface/datasets/blob/76bb45964df1e62d1411b0a9e9fc673e9a791c9a/metrics/sacrebleu/sacrebleu.py from copy import deepcopy from sacrebleu.metrics import BLEU def compute_bleu( predictions, references, smooth_method="exp", smooth_value=None, force=False, lowercase=False, tokenize=None, effective_order=False, ): references_per_prediction = len(references[0]) if any(len(refs) != references_per_prediction for refs in references): references = deepcopy(references) max_references_per_prediction = max(len(refs) for refs in references) for refs in references: refs.extend([None] * (max_references_per_prediction - len(refs))) transformed_references = [[refs[i] for refs in references] for i in range(references_per_prediction)] bleu = BLEU( smooth_method=smooth_method, smooth_value=smooth_value, force=force, lowercase=lowercase, effective_order=effective_order, **(dict(tokenize=tokenize) if tokenize else {}), ) output = bleu.corpus_score( predictions, transformed_references, ) output_dict = { "score": output.score, **{f"counts-{i+1}": round(p, 4) for i, p in enumerate(output.counts)}, **{f"totals-{i+1}": round(p, 4) for i, p in enumerate(output.totals)}, **{f"precision-{i+1}": round(p, 4) for i, p in enumerate(output.precisions)}, "bp": output.bp, "sys_len": output.sys_len, "ref_len": output.ref_len, } return output_dict