jimregan commited on
Commit
c75d108
1 Parent(s): 678e4dd

add initial version of script

Browse files
Files changed (1) hide show
  1. waxholm.py +270 -0
waxholm.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
3
+ # Copyright 2022 Jim O'Regan
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ # Lint as: python3
18
+ """Datasets loader for Waxholm speech corpus"""
19
+
20
+ from io import BytesIO
21
+ import os
22
+ import soundfile as sf
23
+
24
+ import datasets
25
+ from datasets.tasks import AutomaticSpeechRecognition
26
+ from datasets.features import Audio
27
+
28
+ TRAIN_LIST = "alloktrainfiles"
29
+ TEST_LIST = "testfiles"
30
+
31
+
32
+ _DESCRIPTION = """\
33
+ The Waxholm corpus was collected in 1993 - 1994 at the department of Speech, Hearing and Music (TMH), KTH.
34
+ """
35
+
36
+
37
+ _CITATION = """
38
+ @article{bertenstam1995spoken,
39
+ title={Spoken dialogue data collected in the {W}axholm project},
40
+ author={Bertenstam, Johan and Blomberg, Mats and Carlson, Rolf and Elenius, Kjell and Granstr{\"o}m, Bj{\"o}rn and Gustafson, Joakim and Hunnicutt, Sheri and H{\"o}gberg, Jesper and Lindell, Roger and Neovius, Lennart and Nord, Lennart and de~Serpa-Leitao, Antonio and Str{\"o}m, Nikko},
41
+ journal={STH-QPSR, KTH},
42
+ volume={1},
43
+ pages={49--74},
44
+ year={1995}
45
+ }
46
+ @inproceedings{bertenstam1995waxholm,
47
+ title={The {W}axholm application database.},
48
+ author={Bertenstam, J and Blomberg, Mats and Carlson, Rolf and Elenius, Kjell and Granstr{\"o}m, Bj{\"o}rn and Gustafson, Joakim and Hunnicutt, Sheri and H{\"o}gberg, Jesper and Lindell, Roger and Neovius, Lennart and Nord, Lennart and de~Serpa-Leitao, Antonio and Str{\"o}m, Nikko},
49
+ booktitle={EUROSPEECH},
50
+ year={1995}
51
+ }"""
52
+
53
+
54
+ _URL = "http://www.speech.kth.se/waxholm/waxholm2.html"
55
+
56
+
57
+ class WaxholmDataset(datasets.GeneratorBasedBuilder):
58
+ """Dataset script for Waxholm."""
59
+
60
+ VERSION = datasets.Version("1.1.0")
61
+
62
+ BUILDER_CONFIGS = [
63
+ datasets.BuilderConfig(name="waxholm"),
64
+ ]
65
+
66
+ def _info(self):
67
+ features = datasets.Features(
68
+ {
69
+ "id": datasets.Value("string"),
70
+ "text": datasets.Value("string"),
71
+ "audio": datasets.Audio(sampling_rate=16_000)
72
+ }
73
+ )
74
+
75
+ return datasets.DatasetInfo(
76
+ description=_DESCRIPTION,
77
+ features=features,
78
+ supervised_keys=None,
79
+ homepage=_URL,
80
+ citation=_CITATION,
81
+ task_templates=[
82
+ AutomaticSpeechRecognition(audio_file_path_column="path", transcription_column="text")
83
+ ],
84
+ )
85
+
86
+ def _split_generators(self, dl_manager):
87
+ return [
88
+ datasets.SplitGenerator(
89
+ name=datasets.Split.TRAIN,
90
+ gen_kwargs={
91
+ "split": "train",
92
+ "files": TRAIN_LIST
93
+ },
94
+ ),
95
+ datasets.SplitGenerator(
96
+ name=datasets.Split.TEST,
97
+ gen_kwargs={
98
+ "split": "test",
99
+ "files": TEST_LIST
100
+ },
101
+ ),
102
+ ]
103
+
104
+ def _generate_examples(self, split, files):
105
+ with open(f"./waxholm/{files}") as input_file:
106
+ for line in input_file.readlines():
107
+ line = line.strip()
108
+ parts = line.split(".")
109
+ subdir = parts[0]
110
+ audio_file = f"./waxholm/scenes_formatted/{subdir}/{line}"
111
+ if not os.path.exists(audio_file):
112
+ print(f"{audio_file} does not exist: skipping")
113
+ continue
114
+ text_file = f"{audio_file}.mix"
115
+ if not os.path.exists(text_file):
116
+ print(f"{text_file} does not exist: skipping")
117
+ continue
118
+ mix = Mix(text_file)
119
+ samples, sr = smp_read_sf(audio_file)
120
+ buffer = BytesIO()
121
+ sf.write(buffer, samples, sr, format="wav")
122
+ blank = Audio()
123
+ audio_to_pass = blank.encode_example(value = {"bytes": buffer.getvalue(), "sampling_rate": sr, })
124
+ yield line, {
125
+ "id": line,
126
+ "text": mix.text,
127
+ "audio": audio_to_pass
128
+ }
129
+
130
+
131
+ def fix_text(text: str) -> str:
132
+ replacements = text.maketrans("{}|\\", "äåöÖ")
133
+ return text.translate(replacements)
134
+
135
+
136
+ class FR:
137
+ def __init__(self, text: str):
138
+ if not text.startswith("FR"):
139
+ raise IOError("Unknown line type (does not begin with 'FR'): " + text)
140
+ parts = [a.strip() for a in text.split("\t")]
141
+ self.frame = parts[0][2:].strip()
142
+ if parts[-1].strip().endswith(" sec"):
143
+ self.seconds = parts[-1].strip()[0:-4]
144
+ for subpart in parts[1:-1]:
145
+ if subpart.startswith("$#"):
146
+ self.type = 'I'
147
+ self.phone_type = fix_text(subpart[0:2])
148
+ self.phone = fix_text(subpart[2:])
149
+ elif subpart.startswith("$"):
150
+ self.type = 'I'
151
+ self.phone_type = fix_text(subpart[0:2])
152
+ self.phone = fix_text(subpart[2:])
153
+ elif subpart.startswith("#"):
154
+ self.type = 'B'
155
+ self.phone_type = fix_text(subpart[0:2])
156
+ self.phone = fix_text(subpart[2:])
157
+ elif subpart.startswith(">pm "):
158
+ self.pm_type = fix_text(subpart[4:5])
159
+ self.pm = fix_text(subpart[5:])
160
+ elif subpart.startswith(">pm. "):
161
+ self.pm_type = fix_text(subpart[4:5])
162
+ self.pm = fix_text(subpart[5:])
163
+ elif subpart.startswith(">w "):
164
+ self.type = 'B'
165
+ self.word = fix_text(subpart[3:])
166
+ self.pseudoword = False
167
+ elif subpart.startswith(">w. "):
168
+ self.type = 'B'
169
+ self.word = fix_text(subpart[4:])
170
+ self.pseudoword = False
171
+ elif subpart.startswith("X"):
172
+ if hasattr(self, 'type'):
173
+ print(self.type, self.type == 'B')
174
+ self.type = getattr(self, 'type', 'B')
175
+ self.word = fix_text(subpart)
176
+ self.pseudoword = True
177
+ elif subpart == "OK":
178
+ self.type = 'E'
179
+
180
+
181
+ def __repr__(self):
182
+ parts = []
183
+ parts.append(f"type: {self.type}")
184
+ parts.append(f"frame: {self.frame}")
185
+ if self.type != 'E':
186
+ parts.append(f"phone: {self.phone}")
187
+ if 'word' in self.__dict__:
188
+ parts.append(f"word: {self.word}")
189
+ if 'pm_type' in self.__dict__:
190
+ parts.append(f"pm_type: {self.pm_type}")
191
+ if 'pm' in self.__dict__:
192
+ parts.append(f"pm: {self.pm}")
193
+ parts.append(f"sec: {self.seconds}")
194
+ return f"FR(" + ", ".join(parts) + ")"
195
+
196
+
197
+ class Mix():
198
+ def __init__(self, filepath: str):
199
+ self.fr = []
200
+ with open(filepath) as inpf:
201
+ saw_text = False
202
+ saw_phoneme = False
203
+ saw_labels = False
204
+ for line in inpf.readlines():
205
+ if line.startswith("Waxholm dialog."):
206
+ self.filepath = line[15:].strip()
207
+ if line.startswith("TEXT:"):
208
+ saw_text = True
209
+ continue
210
+ if saw_text:
211
+ self.text = fix_text(line.strip())
212
+ saw_text = False
213
+ if line.startswith("FR "):
214
+ if saw_labels:
215
+ saw_labels = False
216
+ self.fr.append(FR(line))
217
+ if line.startswith("Labels: "):
218
+ self.labels = line[8:].strip()
219
+ saw_labels = True
220
+ if saw_labels and line.startswith(" "):
221
+ self.labels += line.strip()
222
+
223
+
224
+ def smp_probe(filename: str) -> bool:
225
+ with open(filename, "rb") as f:
226
+ return f.read(9) == b"file=samp"
227
+
228
+
229
+ def smp_headers(filename: str):
230
+ with open(filename, "rb") as f:
231
+ f.seek(0)
232
+ raw_headers = f.read(1024)
233
+ raw_headers = raw_headers.rstrip(b'\x00')
234
+ asc_headers = raw_headers.decode("ascii")
235
+ asc_headers.rstrip('\x00')
236
+ tmp = [a for a in asc_headers.split("\r\n")]
237
+ back = -1
238
+ while abs(back) > len(tmp) + 1:
239
+ if tmp[back] == '=':
240
+ break
241
+ back -= 1
242
+ tmp = tmp[0:back-1]
243
+ return dict(a.split("=") for a in tmp)
244
+
245
+
246
+ def smp_read_sf(filename: str):
247
+ headers = smp_headers(filename)
248
+ if headers["msb"] == "last":
249
+ ENDIAN = "LITTLE"
250
+ else:
251
+ ENDIAN = "BIG"
252
+
253
+ data, sr = sf.read(filename, channels=int(headers["nchans"]),
254
+ samplerate=16000, endian=ENDIAN, start=512,
255
+ dtype="int16", format="RAW", subtype="PCM_16")
256
+ return (data, sr)
257
+
258
+
259
+ def _write_wav(filename, arr):
260
+ import wave
261
+
262
+ with wave.open(filename, "w") as f:
263
+ f.setnchannels(1)
264
+ f.setsampwidth(2)
265
+ f.setframerate(16000)
266
+ f.writeframes(arr)
267
+
268
+
269
+ #arr, sr = smp_read_sf("/Users/joregan/Playing/waxholm/scenes_formatted//fp2060/fp2060.pr.09.smp")
270
+ #write_wav("out.wav", arr)