csj / csj.py
Jaegeon's picture
change text and katakana to original text and text
6b0a568
# 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