# 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 '' 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 보컬 플라이 등으로 모음을 식별 할 수없는 경우 "응/흠/훙" 소리를 파악하기 어려운 경우 쓸데없이 모음을 길게 발음 쓸데없이 자음을 길게 발음 <笑> 웃음 <泣> 움 <咳> 기침 <息> 숨소리

2초 이상의 정적 -> '' """ 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