File size: 13,559 Bytes
abf4122 6b0a568 abf4122 6b0a568 abf4122 6b0a568 abf4122 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets Authors and the HuggingFace Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Lint as: python3
"""CSJ: Corpus of Spontaneous Japanese for Automatic Speech Recognition."""
import os
import re
from pathlib import Path
import datasets
import numpy as np
import librosa
from datasets.tasks import AutomaticSpeechRecognition
import soundfile as sf
_CITATION = """\
@article{article,
author = {Maekawa, Kikuo},
year = {2003},
month = {01},
pages = {},
title = {Corpus of Spontaneous Japanese: Its design and evaluation},
journal = {Proceedings of SSPR}
}
"""
_DESCRIPTION = """\
Corpus of Spontaneous Japanese, or CSJ, is a large-scale database of spontaneous Japanese. It contains speech signal and transcription of about 7 million words along with various annotations like POS and phonetic labels. After describing its design issues, preliminary evaluation of the CSJ was presented. The results suggest strongly the usefulness of the CSJ as the resource for the study of spontaneous speech.
"""
_HOMEPAGE = "https://clrd.ninjal.ac.jp/csj/en/"
_ROOT_DIRNAME = "csj"
class CSJConfig(datasets.BuilderConfig):
"""BuilderConfig for CSJ."""
def __init__(self, **kwargs):
"""
Args:
data_dir: `string`, the path to the folder containing the files in the
downloaded .tar
citation: `string`, citation for the data set
url: `string`, url for information about the data set
**kwargs: keyword arguments forwarded to super.
"""
# version history
# 0.1.0: First release
super(CSJConfig, self).__init__(version=datasets.Version("0.1.0", ""), **kwargs)
class CSJ(datasets.GeneratorBasedBuilder):
"""CSJ dataset."""
DEFAULT_CONFIG_NAME = "all"
BUILDER_CONFIGS = [
CSJConfig(name="core", description="'core' speech."),
CSJConfig(name="noncore", description="'noncore', more challenging, speech."),
CSJConfig(name="all", description="Combined clean and other dataset."),
]
@property
def manual_download_instructions(self):
return (
"To use CSJ you have to download it manually. "
"Please create an account and download the dataset from "
"https://clrd.ninjal.ac.jp/csj/en/ \n"
"Then load the dataset with: "
"`datasets.load_dataset('csj', data_dir='path/to/folder/folder_name')`"
)
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"id": datasets.Value("string"),
"audio": datasets.Audio(sampling_rate=16_000),
"text": datasets.Value("string"),
"original_text": datasets.Value("string")
}
),
supervised_keys=("id", "text"),
homepage=_HOMEPAGE,
citation=_CITATION,
task_templates=[AutomaticSpeechRecognition(audio_column="audio", transcription_column="katakana")],
)
def _split_generators(self, dl_manager):
# Step 1. Extract all zip files
# Step 2. Get scripts
# Step 3. Generate samples
data_dir = os.path.abspath(os.path.expanduser(dl_manager.manual_dir))
data_dir = os.path.join(data_dir, _ROOT_DIRNAME)
if not os.path.exists(data_dir):
raise FileNotFoundError(
f"{data_dir} does not exist. Make sure you insert a manual dir via"
"`datasets.load_dataset('csj', data_dir=...)`"
"that includes files. Manual download instructions:"
f"{self.manual_download_instructions}"
)
if self.config.name == 'default':
self.config.name = 'all'
archive_paths = {}
for fname in os.listdir(data_dir):
if (fname.startswith(self.config.name) or (self.config.name == 'all')) and fname.endswith('.zip'):
fname_no_ext = os.path.splitext(fname)[0]
archive_paths[fname_no_ext] = os.path.join(data_dir, fname)
local_extracted_archives = dl_manager.extract(archive_paths)
split_keys = {
"train": [],
"valid": [],
"test": []
}
if self.config.name == 'all':
split_keys["train"] = ["core.train", "noncore.train"]
split_keys["valid"] = ["core.valid", "noncore.valid"]
split_keys["test"] = ["core.test", "noncore.test"]
else:
for k in split_keys:
split_keys[k] = [f"{self.config.name}.{k}"]
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"target_keys": split_keys["train"],
"local_extracted_archives": local_extracted_archives
}
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"target_keys": split_keys["valid"],
"local_extracted_archives": local_extracted_archives
}
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"target_keys": split_keys["test"],
"local_extracted_archives": local_extracted_archives
}
)
]
def _generate_examples(self, target_keys, local_extracted_archives):
"""Generate examples from KsponSpeech archive_path based on the test/train trn information."""
# Iterating the contents of the data to extract the relevant information
"""
audio_data = {
target_key: {
file_id: {
seg_id: String,
duration: Tuple(Float, Float),
channel: String
}
}
}
"""
metadata = {}
for k in target_keys:
local_extracted_archive = os.path.join(local_extracted_archives[k], k)
for fname in os.listdir(local_extracted_archive):
if fname.endswith('.trn'):
with open(os.path.join(local_extracted_archive, fname), encoding='cp932') as f:
words = []
seg_data = {}
is_stereo = False
file_id = os.path.splitext(fname)[0]
sentence = ''
katakana_sentence = ''
seg_id = ''
metadata[file_id] = {
'path': os.path.join(local_extracted_archive, fname),
'data': {}
}
for line in f:
if not line.startswith('%'):
if 'L:' in line or 'R:' in line:
# audio line
items = line.split(" ")
if len(items) == 3:
if seg_id != '' and sentence != '' and katakana_sentence != '':
metadata[file_id]['data'][seg_id]['text'] = sentence.strip()
metadata[file_id]['data'][seg_id]['katakana'] = parse_tag(katakana_sentence).strip()
sentence = ''
katakana_sentence = ''
seg_id, duration, channel_slot = items
start_sec, end_sec = duration.split("-")
channel = channel_slot.split(":")[0]
metadata[file_id]['data'][seg_id] = {
'duration': (float(start_sec), float(end_sec)),
'channel': channel
}
if channel == 'R':
is_stereo = True
else:
print(f"None audio line contains ':' at {fname}\n->{line}")
elif '&' in line:
# text line
text, katakana = line.split('&')
text = text.strip()
katakana = katakana.strip()
sentence += ' ' + text
katakana_sentence += ' ' + katakana
else:
print(f"Unknown line type. at {fname}\n->{line}")
elif '<EOT>' in line:
if seg_id != '' and sentence != '' and katakana_sentence != '':
metadata[file_id]['data'][seg_id]['text'] = sentence.strip()
metadata[file_id]['data'][seg_id]['katakana'] = parse_tag(katakana_sentence).strip()
sentence = ''
katakana_sentence = ''
if is_stereo:
file_id_left = file_id+'-L'
file_id_right = file_id+'-R'
metadata[file_id_left] = {
'path': metadata[file_id]['path'].replace(file_id, file_id_left),
'data': {}
}
metadata[file_id_right] = {
'path': metadata[file_id]['path'].replace(file_id, file_id_right),
'data': {}
}
for seg_id in metadata[file_id]['data']:
if metadata[file_id]['data'][seg_id]['channel'] == 'L':
metadata[file_id_left]['data'][seg_id] = metadata[file_id]['data'][seg_id]
elif metadata[file_id]['data'][seg_id]['channel'] == 'R':
metadata[file_id_right]['data'][seg_id] = metadata[file_id]['data'][seg_id]
else:
print(f"Unknwon channel. at {file_id}, {seg_id}, {metadata[file_id]['data'][seg_id]['channel']}")
del metadata[file_id]
key = 0
for file_id in metadata:
audio_path = metadata[file_id]['path'].replace('.trn','.wav')
if os.path.exists(audio_path):
audio_array, sampling_rate = sf.read(audio_path)
for seg_id in metadata[file_id]['data']:
if "katakana" in metadata[file_id]['data'][seg_id] and len(metadata[file_id]['data'][seg_id]['katakana']) > 0:
start_sec, end_sec = metadata[file_id]['data'][seg_id]["duration"]
start_idx = int(start_sec * sampling_rate)
end_idx = int(end_sec * sampling_rate)
audio_segment = audio_array[start_idx:end_idx]
audio = {
"path": f"{audio_path}:{start_sec}-{end_sec}",
"array": audio_segment,
"sampling_rate": sampling_rate
}
yield key, {
"id": file_id + '.' + seg_id,
"audio": audio,
"text": metadata[file_id]['data'][seg_id]["katakana"],
"original_text": metadata[file_id]['data'][seg_id]["text"]
}
key += 1
else:
print(f"Audio doesn't exist: {audio_path}")
"""
(F) ํ๋ฌ
(F text) -> text
(D) ๋ค์ ๋งํ๊ธฐ
(D text) -> text
(D2) ์กฐ์ฌ ๋ฑ์ ๋ค์ ๋งํ๊ธฐ
(D2 text) -> text
(?) ์์ ๋ฃ๊ธฐ ์ด๋ ค์์ ์ ์ฌ์ ์์ ์ด ์๋ ๊ฒฝ์ฐ
(? text) -> text
(? text1, text2) -> text1
(?) text -> text
(M) ์์ด๋ ๋จ์ด์ ์ธ์ฉ
(M text) -> text
(R) ๊ฐ์ธ์ ๋ณด
(R xxx) -> ''
(X) ๋น๋ฌธ๋ฒ
(X text) -> text
(A) ์ํ๋ฒณ ๋๋ ์ซ์, ๊ธฐํธ์ ํ๊ธฐ ; ์์ ๋ฐ์ ๋ค๋ ํ๊ธฐ
(A text; notation) -> text
(K) ์ด๋ค ์์ธ์ผ๋ก ํ์ํ๊ธฐ๊ฐ ํ ์ ์์ ๋
(K ใฒ(F ใใผ) ใ ใ;ๅทฆ) -> ใฒใใผใ ใ
(W) ์ผ์์ ๋ฐ์ ์ค์
(W mistake_pronounciation; correct_pronounciation) -> mistake_pronounciation
(B) ๋ฐฐ๊ฒฝ์ง์ ๋ถ์กฑ์ ๋ฐ๋ฅธ ๋ง ์ค์
(B mistake_pronounciation; correct_pronounciation) -> mistake_pronounciation
(็ฌ) ์์ผ๋ฉด์ ๋งํจ
(็ฌ text) -> text
(ๆณฃ) ์ธ๋ฉด์ ๋งํจ
(ๆณฃ text) -> text
(ๅณ) ๊ธฐ์นจํ๋ฉด์ ๋งํจ
(ๅณ text) -> text
(L) ์์ญ์ด๊ฑฐ๋ ์์ ๋ชฉ์๋ฆฌ๋ก ๋งํจ
(L text) -> text
<FV> ๋ณด์ปฌ ํ๋ผ์ด ๋ฑ์ผ๋ก ๋ชจ์์ ์๋ณ ํ ์์๋ ๊ฒฝ์ฐ
<VN> "์/ํ /ํ" ์๋ฆฌ๋ฅผ ํ์
ํ๊ธฐ ์ด๋ ค์ด ๊ฒฝ์ฐ
<H> ์ธ๋ฐ์์ด ๋ชจ์์ ๊ธธ๊ฒ ๋ฐ์
<Q> ์ธ๋ฐ์์ด ์์์ ๊ธธ๊ฒ ๋ฐ์
<็ฌ> ์์
<ๆณฃ> ์
<ๅณ> ๊ธฐ์นจ
<ๆฏ> ์จ์๋ฆฌ
<P> 2์ด ์ด์์ ์ ์
<P:starttime-endtime> -> ''
"""
def deal_with_tag(tag, text):
result = text
if tag == '?':
if ',' in text:
result = text.split(',')[0].strip()
else:
result = text.strip()
elif tag == 'R':
result = ''
elif tag == 'A' or tag == 'B' or tag == 'W' or tag == 'K':
result = text.split(';')[0].strip()
return result
def parse_tag(text):
tag_stack = []
content_stack = []
tag_flag = False
tag2_flag = False
content_flag = False
tag = ''
content = ''
result = ''
for c in text:
if tag2_flag:
if c == '>':
tag2_flag = False
else:
if tag_flag:
if c == ' ' or c == '?':
tag += c
tag_stack.append(tag.strip())
tag = ''
tag_flag = False
content_flag = True
else:
tag += c
elif c == '<':
tag2_flag = True
elif c == '(':
if content_flag:
content_stack.append(content)
content = ''
tag_flag = True
elif c == ')':
if content_flag:
processed_content = deal_with_tag(tag_stack.pop(), content)
if len(content_stack) == 0:
result += processed_content
content = ''
content_flag = False
else:
content = content_stack.pop()
content += processed_content
else:
content = ''
elif content_flag:
content += c
else:
result += c
assert '(' not in result, text
assert ')' not in result, text
assert '<' not in result, text
assert '>' not in result, text
return result
|