ashesicsis1 commited on
Commit
f0c5efb
·
1 Parent(s): a8462a8

Upload asr-sample.py

Browse files
Files changed (1) hide show
  1. asr-sample.py +159 -0
asr-sample.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # Lint as: python3
17
+ """Sample automatic speech recognition dataset by Dennis Owusu."""
18
+
19
+
20
+ import os
21
+
22
+ import datasets
23
+ from datasets.tasks import AutomaticSpeechRecognition
24
+
25
+
26
+ _CITATION = """\
27
+ @inproceedings{panayotov2015librispeech,
28
+ title={Librispeech: an ASR corpus based on public domain audio books},
29
+ author={Panayotov, Vassil and Chen, Guoguo and Povey, Daniel and Khudanpur, Sanjeev},
30
+ booktitle={Acoustics, Speech and Signal Processing (ICASSP), 2015 IEEE International Conference on},
31
+ pages={5206--5210},
32
+ year={2015},
33
+ organization={IEEE}
34
+ }
35
+ """
36
+
37
+ _DESCRIPTION = """\
38
+ Sample automatic speech recognition dataset from Librispeech (clean) by Dennis Owusu.
39
+ """
40
+
41
+ _URL = "http://www.openslr.org/12"
42
+ _DL_URL = "http://www.openslr.org/resources/12/"
43
+
44
+
45
+ _DL_URLS = {
46
+ "clean": {
47
+ "dev": _DL_URL + "dev-clean.tar.gz",
48
+ "test": _DL_URL + "test-clean.tar.gz",
49
+ }
50
+ }
51
+
52
+
53
+ class LibrispeechASRConfig(datasets.BuilderConfig):
54
+ """BuilderConfig for LibriSpeechASR."""
55
+
56
+ def __init__(self, **kwargs):
57
+ """
58
+ Args:
59
+ data_dir: `string`, the path to the folder containing the files in the
60
+ downloaded .tar
61
+ citation: `string`, citation for the data set
62
+ url: `string`, url for information about the data set
63
+ **kwargs: keyword arguments forwarded to super.
64
+ """
65
+ super(LibrispeechASRConfig, self).__init__(version=datasets.Version("2.1.0", ""), **kwargs)
66
+
67
+
68
+ class LibrispeechASR(datasets.GeneratorBasedBuilder):
69
+ """Librispeech dataset."""
70
+
71
+ DEFAULT_WRITER_BATCH_SIZE = 256
72
+ DEFAULT_CONFIG_NAME = "clean"
73
+ BUILDER_CONFIGS = [
74
+ LibrispeechASRConfig(name="clean", description="'Clean' speech."),
75
+ ]
76
+
77
+ def _info(self):
78
+ return datasets.DatasetInfo(
79
+ description=_DESCRIPTION,
80
+ features=datasets.Features(
81
+ {
82
+ "file": datasets.Value("string"),
83
+ "audio": datasets.Audio(sampling_rate=16_000),
84
+ "text": datasets.Value("string"),
85
+ "speaker_id": datasets.Value("int64"),
86
+ "chapter_id": datasets.Value("int64"),
87
+ "id": datasets.Value("string"),
88
+ }
89
+ ),
90
+ supervised_keys=("file", "text"),
91
+ homepage=_URL,
92
+ citation=_CITATION,
93
+ task_templates=[AutomaticSpeechRecognition(audio_column="audio", transcription_column="text")],
94
+ )
95
+
96
+ def _split_generators(self, dl_manager):
97
+ archive_path = dl_manager.download(_DL_URLS[self.config.name])
98
+ # (Optional) In non-streaming mode, we can extract the archive locally to have actual local audio files:
99
+ local_extracted_archive = dl_manager.extract(archive_path) if not dl_manager.is_streaming else {}
100
+
101
+ if self.config.name == "clean":
102
+ dev_splits = [
103
+ datasets.SplitGenerator(
104
+ name=datasets.Split.VALIDATION,
105
+ gen_kwargs={
106
+ "local_extracted_archive": local_extracted_archive.get("dev"),
107
+ "files": dl_manager.iter_archive(archive_path["dev"]),
108
+ },
109
+ )
110
+ ]
111
+ test_splits = [
112
+ datasets.SplitGenerator(
113
+ name=datasets.Split.TEST,
114
+ gen_kwargs={
115
+ "local_extracted_archive": local_extracted_archive.get("test"),
116
+ "files": dl_manager.iter_archive(archive_path["test"]),
117
+ },
118
+ )
119
+ ]
120
+
121
+ return dev_splits + test_splits
122
+
123
+ def _generate_examples(self, files, local_extracted_archive):
124
+ """Generate examples from a LibriSpeech archive_path."""
125
+ key = 0
126
+ audio_data = {}
127
+ transcripts = []
128
+ for path, f in files:
129
+ if path.endswith(".flac"):
130
+ id_ = path.split("/")[-1][: -len(".flac")]
131
+ audio_data[id_] = f.read()
132
+ elif path.endswith(".trans.txt"):
133
+ for line in f:
134
+ if line:
135
+ line = line.decode("utf-8").strip()
136
+ id_, transcript = line.split(" ", 1)
137
+ audio_file = f"{id_}.flac"
138
+ speaker_id, chapter_id = [int(el) for el in id_.split("-")[:2]]
139
+ audio_file = (
140
+ os.path.join(local_extracted_archive, audio_file)
141
+ if local_extracted_archive
142
+ else audio_file
143
+ )
144
+ transcripts.append(
145
+ {
146
+ "id": id_,
147
+ "speaker_id": speaker_id,
148
+ "chapter_id": chapter_id,
149
+ "file": audio_file,
150
+ "text": transcript,
151
+ }
152
+ )
153
+ if audio_data and len(audio_data) == len(transcripts):
154
+ for transcript in transcripts:
155
+ audio = {"path": transcript["file"], "bytes": audio_data[transcript["id"]]}
156
+ yield key, {"audio": audio, **transcript}
157
+ key += 1
158
+ audio_data = {}
159
+ transcripts = []