ks / superb_demo.py
cqlizhijun's picture
Create superb_demo.py
cd22391
# 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
"""SUPERB: Speech processing Universal PERformance Benchmark."""
import csv
import glob
import os
import textwrap
import datasets
from datasets.tasks import AutomaticSpeechRecognition
_CITATION = """\
@article{DBLP:journals/corr/abs-2105-01051,
author = {Zhi{-}Jun Lee and
Jia{-}Jie Sehn},
title = {{SUPERB:} Speech processing Universal PERformance Benchmark},
journal = {CoRR},
volume = {abs/2105.01051},
year = {2021},
url = {https://arxiv.org/abs/2105.01051},
archivePrefix = {arXiv},
eprint = {2105.01051},
timestamp = {Thu, 01 Jul 2021 13:30:22 +0200},
biburl = {https://dblp.org/rec/journals/corr/abs-2105-01051.bib},
bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""
_DESCRIPTION = """\
Self-supervised learning (SSL) has proven vital for advancing research in
natural language processing (NLP) and computer vision (CV). The paradigm
pretrains a shared model on large volumes of unlabeled data and achieves
state-of-the-art (SOTA) for various tasks with minimal adaptation. However, the
speech processing community lacks a similar setup to systematically explore the
paradigm. To bridge this gap, we introduce Speech processing Universal
PERformance Benchmark (SUPERB). SUPERB is a leaderboard to benchmark the
performance of a shared model across a wide range of speech processing tasks
with minimal architecture changes and labeled data. Among multiple usages of the
shared model, we especially focus on extracting the representation learned from
SSL due to its preferable re-usability. We present a simple framework to solve
SUPERB tasks by learning task-specialized lightweight prediction heads on top of
the frozen shared model. Our results demonstrate that the framework is promising
as SSL representations show competitive generalizability and accessibility
across SUPERB tasks. We release SUPERB as a challenge with a leaderboard and a
benchmark toolkit to fuel the research in representation learning and general
speech processing.
Note that in order to limit the required storage for preparing this dataset, the
audio is stored in the .flac format and is not converted to a float32 array. To
convert, the audio file to a float32 array, please make use of the `.map()`
function as follows:
```python
import soundfile as sf
def map_to_array(batch):
speech_array, _ = sf.read(batch["file"])
batch["speech"] = speech_array
return batch
dataset = dataset.map(map_to_array, remove_columns=["file"])
```
"""
class SuperbConfig(datasets.BuilderConfig):
"""BuilderConfig for Superb."""
def __init__(
self,
features,
url,
data_url=None,
supervised_keys=None,
task_templates=None,
**kwargs,
):
super().__init__(version=datasets.Version("1.9.0", ""), **kwargs)
self.features = features
self.data_url = data_url
self.url = url
self.supervised_keys = supervised_keys
self.task_templates = task_templates
class Superb(datasets.GeneratorBasedBuilder):
"""Superb dataset."""
BUILDER_CONFIGS = [
SuperbConfig(
name="ks",
description=textwrap.dedent(
"""\
Keyword Spotting (KS) detects preregistered keywords by classifying utterances into a predefined set of
words. The task is usually performed on-device for the fast response time. Thus, accuracy, model size, and
inference time are all crucial. SUPERB uses the widely used Speech Commands dataset v1.0 for the task.
The dataset consists of ten classes of keywords, a class for silence, and an unknown class to include the
false positive. The evaluation metric is accuracy (ACC)"""
),
features=datasets.Features(
{
"file": datasets.Value("string"),
"audio": datasets.features.Audio(sampling_rate=16_000),
"label": datasets.ClassLabel(
names=[
"neunit",
"wake",
"_unknown_",
]
),
}
),
supervised_keys=("file", "label"),
url="https://www.tensorflow.org/datasets/catalog/speech_commands",
data_url="data/speech_commands_test_set_v0.01.zip",
),
]
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=self.config.features,
supervised_keys=self.config.supervised_keys,
homepage=self.config.url,
citation=_CITATION,
task_templates=self.config.task_templates,
)
def _split_generators(self, dl_manager):
if self.config.name == "ks":
archive_path = dl_manager.download_and_extract(self.config.data_url)
return [
datasets.SplitGenerator(
name=datasets.Split.TEST, gen_kwargs={"archive_path": archive_path, "split": "test"}
),
]
def _generate_examples(self, archive_path, split=None):
"""Generate examples."""
if self.config.name == "ks":
words = ["neunit", "wake"]
splits = _split_ks_files(archive_path, split)
for key, audio_file in enumerate(sorted(splits[split])):
base_dir, file_name = os.path.split(audio_file)
_, word = os.path.split(base_dir)
if word in words:
label = word
else:
label = "_unknown_"
yield key, {"file": audio_file, "audio": audio_file, "label": label}
def _split_ks_files(archive_path, split):
audio_path = os.path.join(archive_path, "**/*.wav")
audio_paths = glob.glob(audio_path)
if split == "test":
# use all available files for the test archive
return {"test": audio_paths}
val_list_file = os.path.join(archive_path, "validation_list.txt")
test_list_file = os.path.join(archive_path, "testing_list.txt")
with open(val_list_file, encoding="utf-8") as f:
val_paths = f.read().strip().splitlines()
val_paths = [os.path.join(archive_path, p) for p in val_paths]
with open(test_list_file, encoding="utf-8") as f:
test_paths = f.read().strip().splitlines()
test_paths = [os.path.join(archive_path, p) for p in test_paths]
# the paths for the train set is just whichever paths that do not exist in
# either the test or validation splits
train_paths = list(set(audio_paths) - set(val_paths) - set(test_paths))
return {"train": train_paths, "val": val_paths}