CoolFace
Apppublic

chendl/compositional_test

sourceHugging Faceupdated 3y agoView on Hugging Face
1likes
1#!/usr/bin/env python32import argparse3import re4from typing import Dict5 6import torch7from datasets import Audio, Dataset, load_dataset, load_metric8 9from transformers import AutoFeatureExtractor, pipeline10 11 12def log_results(result: Dataset, args: Dict[str, str]):13    """DO NOT CHANGE. This function computes and logs the result metrics."""14 15    log_outputs = args.log_outputs16    dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])17 18    # load metric19    wer = load_metric("wer")20    cer = load_metric("cer")21 22    # compute metrics23    wer_result = wer.compute(references=result["target"], predictions=result["prediction"])24    cer_result = cer.compute(references=result["target"], predictions=result["prediction"])25 26    # print & log results27    result_str = f"WER: {wer_result}\nCER: {cer_result}"28    print(result_str)29 30    with open(f"{dataset_id}_eval_results.txt", "w") as f:31        f.write(result_str)32 33    # log all results in text file. Possibly interesting for analysis34    if log_outputs is not None:35        pred_file = f"log_{dataset_id}_predictions.txt"36        target_file = f"log_{dataset_id}_targets.txt"37 38        with open(pred_file, "w") as p, open(target_file, "w") as t:39            # mapping function to write output40            def write_to_file(batch, i):41                p.write(f"{i}" + "\n")42                p.write(batch["prediction"] + "\n")43                t.write(f"{i}" + "\n")44                t.write(batch["target"] + "\n")45 46            result.map(write_to_file, with_indices=True)47 48 49def normalize_text(text: str) -> str:50    """DO ADAPT FOR YOUR USE CASE. this function normalizes the target text."""51 52    chars_to_ignore_regex = '[,?.!\-\;\:"“%‘”�—’…–]'  # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training53 54    text = re.sub(chars_to_ignore_regex, "", text.lower())55 56    # In addition, we can normalize the target text, e.g. removing new lines characters etc...57    # note that order is important here!58    token_sequences_to_ignore = ["\n\n", "\n", "   ", "  "]59 60    for t in token_sequences_to_ignore:61        text = " ".join(text.split(t))62 63    return text64 65 66def main(args):67    # load dataset68    dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)69 70    # for testing: only process the first two examples as a test71    # dataset = dataset.select(range(10))72 73    # load processor74    feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)75    sampling_rate = feature_extractor.sampling_rate76 77    # resample audio78    dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))79 80    # load eval pipeline81    if args.device is None:82        args.device = 0 if torch.cuda.is_available() else -183    asr = pipeline("automatic-speech-recognition", model=args.model_id, device=args.device)84 85    # map function to decode audio86    def map_to_pred(batch):87        prediction = asr(88            batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s89        )90 91        batch["prediction"] = prediction["text"]92        batch["target"] = normalize_text(batch["sentence"])93        return batch94 95    # run inference on all examples96    result = dataset.map(map_to_pred, remove_columns=dataset.column_names)97 98    # compute and log_results99    # do not change function below100    log_results(result, args)101 102 103if __name__ == "__main__":104    parser = argparse.ArgumentParser()105 106    parser.add_argument(107        "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"108    )109    parser.add_argument(110        "--dataset",111        type=str,112        required=True,113        help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets",114    )115    parser.add_argument(116        "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'`  for Common Voice"117    )118    parser.add_argument("--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`")119    parser.add_argument(120        "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to 5 seconds."121    )122    parser.add_argument(123        "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to 1 second."124    )125    parser.add_argument(126        "--log_outputs", action="store_true", help="If defined, write outputs to log file for analysis."127    )128    parser.add_argument(129        "--device",130        type=int,131        default=None,132        help="The device to run the pipeline on. -1 for CPU (default), 0 for the first GPU and so on.",133    )134    args = parser.parse_args()135 136    main(args)137