File size: 10,049 Bytes
1022f4b 7b1ef87 1022f4b 7b1ef87 1022f4b 8501562 7b1ef87 1022f4b 7b1ef87 1022f4b 8501562 1022f4b 8501562 44c3aea 8501562 1022f4b 1b737b4 1022f4b 44c3aea 1022f4b 7b1ef87 1022f4b 08b423e 1022f4b 1b737b4 1022f4b 1b737b4 44a5db7 1b737b4 1022f4b 1b737b4 44a5db7 1022f4b 44a5db7 1022f4b |
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 |
"""The IWSLT Challenge Dataset, adapted to punctuation as described by Ueffing et al. (2013)"""
from enum import Enum
from typing import Union
from abc import abstractmethod
import logging
import itertools
#import paired
from xml.dom import minidom
import nltk
import datasets
import numpy as np
nltk.download("punkt")
tknzr = nltk.tokenize.TweetTokenizer()
_CITATION = """\
@inproceedings{Ueffing2013,
title={Improved models for automatic punctuation prediction for spoken and written text},
author={B. Ueffing and M. Bisani and P. Vozila},
booktitle={INTERSPEECH},
year={2013}
}
@article{Federico2011,
author = {M. Federico and L. Bentivogli and M. Paul and S. Stüker},
year = {2011},
month = {01},
pages = {},
title = {Overview of the IWSLT 2011 Evaluation Campaign},
journal = {Proceedings of the International Workshop on Spoken Language Translation (IWSLT), San Francisco, CA}
}
"""
_DESCRIPTION = """\
Both manual transcripts and ASR outputs from the IWSLT2011 speech translation evalutation campaign are often used for the related \
punctuation annotation task. This dataset takes care of preprocessing said transcripts and automatically inserts punctuation marks \
given in the manual transcripts in the ASR outputs using Levenshtein aligment.
"""
_VERSION = "0.0.1"
def window(a, w = 4, o = 2):
sh = (a.size - w + 1, w)
st = a.strides * 2
view = np.lib.stride_tricks.as_strided(a, strides = st, shape = sh)[0::o]
return view.copy()
class Punctuation(Enum):
NONE = "<none>"
PERIOD = "<period>"
COMMA = "<comma>"
QUESTION = "<question>"
class LabelSubword(Enum):
IGNORE = "<ignore>"
NONE = "<none>"
class Task(Enum):
TAGGING = 0
SEQ2SEQ = 1
class TaggingTask:
"""Treat punctuation prediction as a sequence tagging problem."""
def __init__(
self, window_size=120, window_stride=60
):
self.window_size = window_size
self.window_stride = window_stride
def __eq__(self, other):
return Task.TAGGING == other
class IWSLT11Config(datasets.BuilderConfig):
"""The IWSLT11 Dataset."""
def __init__(
self,
segmented: bool = False,
asr_or_ref: str = "ref",
tokenizer = None,
label_subword = LabelSubword.IGNORE,
window_size = None,
window_stride = None,
**kwargs
):
"""BuilderConfig for IWSLT2011.
Args:
task: the task to prepare the dataset for.
segmented: if segmentation present in IWSLT2011 should be respected. removes segmenation by default.
**kwargs: keyword arguments forwarded to super.
"""
self.task = TaggingTask()
if window_size is not None:
self.task.window_size = window_size
if window_stride is not None:
self.task.window_stride = window_stride
self.segmented = segmented
self.asr_or_ref = asr_or_ref
self.punctuation = [
Punctuation.NONE,
Punctuation.PERIOD,
Punctuation.COMMA,
Punctuation.QUESTION,
label_subword.IGNORE
]
self.label_subword = label_subword
self.tokenizer = tokenizer
super(IWSLT11Config, self).__init__(**kwargs)
def __eq__(self, other):
return True
class IWSLT11(datasets.GeneratorBasedBuilder):
"""The IWSLT11 Dataset, adapted for punctuation prediction."""
BUILDER_CONFIGS = [
IWSLT11Config(name="ref", asr_or_ref="ref"),
IWSLT11Config(name="asr", asr_or_ref="asr"),
]
def __init__(self, *args, **kwargs):
if 'label_subword' in kwargs:
label_subword = kwargs['label_subword']
if isinstance(label_subword, str):
if 'ignore' == label_subword.lower():
label_subword = LabelSubword.IGNORE
elif 'none' == label_subword.lower():
label_subword = LabelSubword.NONE
kwargs['label_subword'] = label_subword
super(IWSLT11, self).__init__(*args, **kwargs)
def _info(self):
if self.config.task == Task.TAGGING:
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"ids": datasets.Sequence(datasets.Value("int32")),
"tokens": datasets.Sequence(datasets.Value("int32")),
"labels": datasets.Sequence(
datasets.features.ClassLabel(
names=[p.name for p in self.config.punctuation]
)
),
}
),
supervised_keys=None,
homepage="http://iwslt2011.org/doku.php",
citation=_CITATION,
version=_VERSION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
urls_to_download = {
"train": "https://raw.githubusercontent.com/IsaacChanghau/neural_sequence_labeling/master/data/raw/LREC_converted/train.txt",
"valid": "https://github.com/IsaacChanghau/neural_sequence_labeling/blob/master/data/raw/LREC_converted/dev.txt?raw=true",
"test_ref": "https://github.com/IsaacChanghau/neural_sequence_labeling/raw/master/data/raw/LREC_converted/ref.txt",
"test_asr": "https://github.com/IsaacChanghau/neural_sequence_labeling/raw/master/data/raw/LREC_converted/asr.txt",
}
files = dl_manager.download_and_extract(urls_to_download)
if self.config.asr_or_ref == "asr":
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": files["train"]
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepath": files["valid"]
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepath": files["test_asr"]
},
),
]
else:
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": files["train"]
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepath": files["valid"]
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepath": files["test_ref"]
},
),
]
def _generate_examples(self, filepath):
logging.info("⏳ Generating examples from = %s", filepath)
text = open(filepath).read()
text = (
text
.replace(',COMMA', ',')
.replace('.PERIOD', '.')
.replace('?QUESTIONMARK', '?')
)
tokens = []
labels = []
for token in tknzr.tokenize(text):
if token in [',', '.', '?']:
if ',' in token:
labels[-1] = Punctuation.COMMA
if '.' in token:
labels[-1] = Punctuation.PERIOD
if '?' in token:
labels[-1] = Punctuation.QUESTION
else:
labels.append(Punctuation.NONE)
tokens.append(token)
tokens = np.array(tokens)
labels = np.array(labels)
token_len = len(tokens)
assert len(tokens) == len(labels)
if self.config.task == Task.TAGGING:
def apply_window(l):
return window(
l,
self.config.task.window_size,
self.config.task.window_stride
)
ids = apply_window(np.arange(len(tokens)))
tokens = apply_window(tokens)
tokens = self.config.tokenizer(
[t.tolist() for t in tokens],
is_split_into_words=True,
return_offsets_mapping=True,
padding=True,
truncation=True,
max_length=int(self.config.task.window_size*2),
pad_to_multiple_of=int(self.config.task.window_size*2)
)
labels = apply_window(labels)
for i, (ids, labels) in enumerate(zip(ids, labels)):
if self.config.tokenizer is None:
raise ValueError('tokenizer argument has to be passed to load_dataset')
else:
words = tokens[i].words
input_ids = tokens['input_ids'][i]
offsets = np.array(tokens['offset_mapping'][i])
enc_labels = np.array([self.config.label_subword.name]*len(offsets), dtype=object)
count = 0
for j, word_id in enumerate(words):
if word_id is not None and (j == 0 or words[j-1] != word_id):
enc_labels[j] = labels[count].name
count += 1
elif input_ids[j] == self.config.tokenizer.pad_token_id:
enc_labels[j] = LabelSubword.IGNORE.name
labels = enc_labels
yield i, {
"ids": ids,
"tokens": input_ids,
"labels": labels,
}
logging.info(f"Loaded number of tokens = {token_len}") |