Eduardo Gonzalez Ponferrada commited on
Commit
99b5a70
1 Parent(s): 334b041

Add wav2vec model with LM

Browse files
README.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - es
4
+ tags:
5
+ - es
6
+ - robust-speech-event
7
+ ---
8
+
9
+ # wav2vec2-xls-r-300m-36-tokens-es
added_tokens.json ADDED
@@ -0,0 +1 @@
 
1
+ {"<s>": 36, "</s>": 37}
alphabet.json ADDED
@@ -0,0 +1 @@
 
1
+ {"labels": [" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "\u00e1", "\u00e9", "\u00ed", "\u00f1", "\u00f3", "\u00fa", "\u00fc", "\u2047", "", "<s>", "</s>"], "is_bpe": false}
common_voice_es_test_eval_results.txt ADDED
@@ -0,0 +1,2 @@
 
 
1
+ WER: 0.15404152388631323
2
+ CER: 0.04559264378545272
config.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "facebook/wav2vec2-xls-r-300m",
3
+ "activation_dropout": 0.0,
4
+ "adapter_kernel_size": 3,
5
+ "adapter_stride": 2,
6
+ "add_adapter": false,
7
+ "apply_spec_augment": true,
8
+ "architectures": [
9
+ "Wav2Vec2ForCTC"
10
+ ],
11
+ "attention_dropout": 0.0,
12
+ "bos_token_id": 1,
13
+ "classifier_proj_size": 256,
14
+ "codevector_dim": 768,
15
+ "contrastive_logits_temperature": 0.1,
16
+ "conv_bias": true,
17
+ "conv_dim": [
18
+ 512,
19
+ 512,
20
+ 512,
21
+ 512,
22
+ 512,
23
+ 512,
24
+ 512
25
+ ],
26
+ "conv_kernel": [
27
+ 10,
28
+ 3,
29
+ 3,
30
+ 3,
31
+ 3,
32
+ 2,
33
+ 2
34
+ ],
35
+ "conv_stride": [
36
+ 5,
37
+ 2,
38
+ 2,
39
+ 2,
40
+ 2,
41
+ 2,
42
+ 2
43
+ ],
44
+ "ctc_loss_reduction": "mean",
45
+ "ctc_zero_infinity": false,
46
+ "diversity_loss_weight": 0.1,
47
+ "do_stable_layer_norm": true,
48
+ "eos_token_id": 2,
49
+ "feat_extract_activation": "gelu",
50
+ "feat_extract_dropout": 0.0,
51
+ "feat_extract_norm": "layer",
52
+ "feat_proj_dropout": 0.0,
53
+ "feat_quantizer_dropout": 0.0,
54
+ "final_dropout": 0.0,
55
+ "gradient_checkpointing": false,
56
+ "hidden_act": "gelu",
57
+ "hidden_dropout": 0.0,
58
+ "hidden_size": 1024,
59
+ "initializer_range": 0.02,
60
+ "intermediate_size": 4096,
61
+ "layer_norm_eps": 1e-05,
62
+ "layerdrop": 0.0,
63
+ "mask_feature_length": 10,
64
+ "mask_feature_min_masks": 0,
65
+ "mask_feature_prob": 0.0,
66
+ "mask_time_length": 10,
67
+ "mask_time_min_masks": 2,
68
+ "mask_time_prob": 0.05,
69
+ "model_type": "wav2vec2",
70
+ "num_adapter_layers": 3,
71
+ "num_attention_heads": 16,
72
+ "num_codevector_groups": 2,
73
+ "num_codevectors_per_group": 320,
74
+ "num_conv_pos_embedding_groups": 16,
75
+ "num_conv_pos_embeddings": 128,
76
+ "num_feat_extract_layers": 7,
77
+ "num_hidden_layers": 24,
78
+ "num_negatives": 100,
79
+ "output_hidden_size": 1024,
80
+ "pad_token_id": 35,
81
+ "proj_codevector_dim": 768,
82
+ "tdnn_dilation": [
83
+ 1,
84
+ 2,
85
+ 3,
86
+ 1,
87
+ 1
88
+ ],
89
+ "tdnn_dim": [
90
+ 512,
91
+ 512,
92
+ 512,
93
+ 512,
94
+ 1500
95
+ ],
96
+ "tdnn_kernel": [
97
+ 5,
98
+ 3,
99
+ 3,
100
+ 1,
101
+ 1
102
+ ],
103
+ "torch_dtype": "float32",
104
+ "transformers_version": "4.16.0.dev0",
105
+ "use_weighted_layer_sum": false,
106
+ "vocab_size": 38,
107
+ "xvector_output_dim": 512
108
+ }
eval.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from datasets import load_dataset, load_metric, Audio, Dataset
3
+ from transformers import pipeline, AutoFeatureExtractor
4
+ import re
5
+ import argparse
6
+ import unicodedata
7
+ from typing import Dict
8
+
9
+
10
+ def log_results(result: Dataset, args: Dict[str, str]):
11
+ """ DO NOT CHANGE. This function computes and logs the result metrics. """
12
+
13
+ log_outputs = args.log_outputs
14
+ dataset_id = "_".join(args.dataset.split("/") + [args.config, args.split])
15
+
16
+ # load metric
17
+ wer = load_metric("wer")
18
+ cer = load_metric("cer")
19
+
20
+ # compute metrics
21
+ wer_result = wer.compute(references=result["target"], predictions=result["prediction"])
22
+ cer_result = cer.compute(references=result["target"], predictions=result["prediction"])
23
+
24
+ # print & log results
25
+ result_str = (
26
+ f"WER: {wer_result}\n"
27
+ f"CER: {cer_result}"
28
+ )
29
+ print(result_str)
30
+
31
+ with open(f"{dataset_id}_eval_results.txt", "w") as f:
32
+ f.write(result_str)
33
+
34
+ # log all results in text file. Possibly interesting for analysis
35
+ if log_outputs is not None:
36
+ pred_file = f"log_{dataset_id}_predictions.txt"
37
+ target_file = f"log_{dataset_id}_targets.txt"
38
+
39
+ with open(pred_file, "w") as p, open(target_file, "w") as t:
40
+
41
+ # mapping function to write output
42
+ def write_to_file(batch, i):
43
+ p.write(f"{i}" + "\n")
44
+ p.write(batch["prediction"] + "\n")
45
+ t.write(f"{i}" + "\n")
46
+ t.write(batch["target"] + "\n")
47
+
48
+ result.map(write_to_file, with_indices=True)
49
+
50
+
51
+ def normalize_text(text: str) -> str:
52
+ """ DO ADAPT FOR YOUR USE CASE. this function normalizes the target text. """
53
+
54
+ # chars_to_ignore_regex = '[,?.!\-\;\:\"“%‘”�—’…–]' # noqa: W605 IMPORTANT: this should correspond to the chars that were ignored during training
55
+ chars_to_ignore_regex = ',\?\¿\.\!\¡\;\;\:\""\%\"\�\ʿ\·\჻\~\՞\؟\،\।\॥\«\»\„\“\”\「\」\‘\’\《\》\(\)\[\]\{\}\=\`\_\+\<\>\…\–\°\´\ʾ\‹\›\©\®\—\→\。\、\﹂\﹁\‧\~\﹏\,\{\}\(\)\[\]\【\】\‥\〽\『\』\〝\〟\⟨\⟩\〜\:\!\?\♪\؛\/\\\º\−\^\ʻ\ˆ\≪\≫'
56
+ chars_to_ignore_regex += "$\&\'\-\|\¨\ª\ß\à\â\ã\ä\å\æ\ç\ê\ë\ì\î\ï\ð\ò\ô\õ\ö\ø\ù\û\ý\þ\ā\ă\ć\č\đ\ė\ę\ě\ğ\ī\ı\ł\ń\ō\ŏ\ő\œ\ř\ś\ş\š\ū\ź\ż\ž\ș\ț\ə\ʷ\ʽ\ː\́\̇\ϙ\а\б\в\г\д\е\и\й\к\л\н\о\п\р\с\т\ч\ш\ы\ь\ю\я\ё\ү\ө\ְ\ִ\ֵ\ָ\ֹ\ּ\ב\ה\ו\י\כ\ל\ם\מ\נ\ס\ק\ר\ש\ת\ا\ب\ة\د\ذ\ر\ل\م\ه\و\ي\ਆ\ਘ\ਤ\ਨ\ਮ\ਸ\ਾ\ਿ\ੰ\ṁ\ṃ\ṇ\ồ\‐\‑\―\し\の\ひ\ら\ゴ\ヒ\ミ\ム\ラ\㓁\口\周\夷\山\戌\日\本\比\毵\消\生\申\真\箱\网\罒\罓\肋\肌\背\良\蝦\鮓\鮨\fi\$\&\'\-\|\¨\ª\ß\à\â\ã\ä\å\æ\ç\ê\ë\ì\î\ï\ð\ò\ô\õ\ö\ø\ù\û\ý\þ\ā\ă\ć\č\đ\ė\ę\ě\ğ\ī\ı\ł\ń\ō\ŏ\ő\œ\ř\ś\ş\š\ū\ź\ż\ž\ș\ț\ə\ʷ\ʽ\ː\́\̇\ϙ\а\б\в\г\д\е\и\й\к\л\н\о\п\р\с\т\ч\ш\ы\ь\ю\я\ё\ү\ө\ְ\ִ\ֵ\ָ\ֹ\ּ\ב\ה\ו\י\כ\ל\ם\מ\נ\ס\ק\ר\ש\ת\ا\ب\ة\د\ذ\ر\ل\م\ه\و\ي\ਆ\ਘ\ਤ\ਨ\ਮ\ਸ\ਾ\ਿ\ੰ\ṁ\ṃ\ṇ\ồ\‐\‑\―\し\の\ひ\ら\ゴ\ヒ\ミ\ム\ラ\㓁\口\周\夷\山\戌\日\本\比\毵\消\生\申\真\箱\网\罒\罓\肋\肌\背\良\蝦\鮓\鮨\fi\"
57
+ chars_to_ignore_regex = "[" + chars_to_ignore_regex + "]"
58
+
59
+ text = text.lower()
60
+ # normalize non-standard (stylized) unicode characters
61
+ text = unicodedata.normalize('NFKC', text)
62
+ # remove punctuation
63
+ text = re.sub(chars_to_ignore_regex, "", text)
64
+
65
+ # Let's also make sure we split on all kinds of newlines, spaces, etc...
66
+ text = " ".join(text.split())
67
+
68
+ return text
69
+
70
+
71
+ def main(args):
72
+ # load dataset
73
+ dataset = load_dataset(args.dataset, args.config, split=args.split, use_auth_token=True)
74
+
75
+ # for testing: only process the first two examples as a test
76
+ # dataset = dataset.select(range(10))
77
+
78
+ # load processor
79
+ feature_extractor = AutoFeatureExtractor.from_pretrained(args.model_id)
80
+ sampling_rate = feature_extractor.sampling_rate
81
+
82
+ # resample audio
83
+ dataset = dataset.cast_column("audio", Audio(sampling_rate=sampling_rate))
84
+
85
+ # load eval pipeline
86
+ # asr = pipeline("automatic-speech-recognition", model=args.model_id)
87
+ asr = pipeline("automatic-speech-recognition", model=args.model_id, device=0)
88
+
89
+ # map function to decode audio
90
+ def map_to_pred(batch):
91
+ prediction = asr(batch["audio"]["array"], chunk_length_s=args.chunk_length_s, stride_length_s=args.stride_length_s)
92
+
93
+ batch["prediction"] = prediction["text"]
94
+ batch["target"] = normalize_text(batch["sentence"])
95
+ return batch
96
+
97
+ # run inference on all examples
98
+ result = dataset.map(map_to_pred, remove_columns=dataset.column_names)
99
+
100
+ # compute and log_results
101
+ # do not change function below
102
+ log_results(result, args)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ parser = argparse.ArgumentParser()
107
+
108
+ parser.add_argument(
109
+ "--model_id", type=str, required=True, help="Model identifier. Should be loadable with 🤗 Transformers"
110
+ )
111
+ parser.add_argument(
112
+ "--dataset", type=str, required=True, help="Dataset name to evaluate the `model_id`. Should be loadable with 🤗 Datasets"
113
+ )
114
+ parser.add_argument(
115
+ "--config", type=str, required=True, help="Config of the dataset. *E.g.* `'en'` for Common Voice"
116
+ )
117
+ parser.add_argument(
118
+ "--split", type=str, required=True, help="Split of the dataset. *E.g.* `'test'`"
119
+ )
120
+ parser.add_argument(
121
+ "--chunk_length_s", type=float, default=None, help="Chunk length in seconds. Defaults to None. For long audio files a good value would be 5.0 seconds."
122
+ )
123
+ parser.add_argument(
124
+ "--stride_length_s", type=float, default=None, help="Stride of the audio chunks. Defaults to None. For long audio files a good value would be 1.0 seconds."
125
+ )
126
+ parser.add_argument(
127
+ "--log_outputs", action='store_true', help="If defined, write outputs to log file for analysis."
128
+ )
129
+ args = parser.parse_args()
130
+
131
+ main(args)
language_model/5gram.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9beb443cf2aab7939c2e484b1bdbbe03f57827dd0068db76a7601bf948656ae6
3
+ size 111822055
language_model/attrs.json ADDED
@@ -0,0 +1 @@
 
1
+ {"alpha": 0.5, "beta": 1.5, "unk_score_offset": -10.0, "score_boundary": true}
language_model/unigrams.txt ADDED
The diff for this file is too large to render. See raw diff
log_common_voice_es_test_predictions.txt ADDED
The diff for this file is too large to render. See raw diff
log_common_voice_es_test_targets.txt ADDED
The diff for this file is too large to render. See raw diff
preprocessor_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "feature_extractor_type": "Wav2Vec2FeatureExtractor",
4
+ "feature_size": 1,
5
+ "padding_side": "right",
6
+ "padding_value": 0.0,
7
+ "processor_class": "Wav2Vec2ProcessorWithLM",
8
+ "return_attention_mask": true,
9
+ "sampling_rate": 16000
10
+ }
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e21c7d862ecf7b5327f2985887bca39fe968d49ea51449eed86bccb9b46dd6aa
3
+ size 1262079473
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "[UNK]", "pad_token": "[PAD]", "additional_special_tokens": [{"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "<s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}, {"content": "</s>", "single_word": false, "lstrip": false, "rstrip": false, "normalized": true}]}
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
1
+ {"unk_token": "[UNK]", "bos_token": "<s>", "eos_token": "</s>", "pad_token": "[PAD]", "do_lower_case": false, "word_delimiter_token": "|", "special_tokens_map_file": null, "tokenizer_file": null, "name_or_path": "edugp/wav2vec2-xls-r-300m-36-tokens-es", "tokenizer_class": "Wav2Vec2CTCTokenizer", "processor_class": "Wav2Vec2ProcessorWithLM"}
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7413e4b25523b52cee9dcbbc7b68c8bded63514be015752c5bda8705c9b1e0af
3
+ size 3055
vocab.json ADDED
@@ -0,0 +1 @@
 
1
+ {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9, "j": 10, "k": 11, "l": 12, "m": 13, "n": 14, "o": 15, "p": 16, "q": 17, "r": 18, "s": 19, "t": 20, "u": 21, "v": 22, "w": 23, "x": 24, "y": 25, "z": 26, "á": 27, "é": 28, "í": 29, "ñ": 30, "ó": 31, "ú": 32, "ü": 33, "|": 0, "[UNK]": 34, "[PAD]": 35}