Spaces:
No application file
No application file
File size: 17,110 Bytes
d08dd00 |
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 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 |
import csv
import json
import os
from .examples import MultipleChoiceExample, TextExample, TokensExample
class DataProcessor:
"""Base class for data converters for sequence classification data sets."""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_examples(self, lang, mode):
if mode == 'train':
return self.get_train_examples(lang)
elif mode == 'dev':
return self.get_dev_examples(lang)
elif mode == 'test':
return self.get_test_examples(lang)
def modes(self):
return ['train', 'dev', 'test']
def get_train_examples(self, lang):
"""Gets a collection of :class:`InputExample` for the train set."""
raise NotImplementedError()
def get_dev_examples(self, lang):
"""Gets a collection of :class:`InputExample` for the dev set."""
raise NotImplementedError()
def get_test_examples(self, lang):
"""Gets a collection of :class:`InputExample` for the test set."""
raise NotImplementedError()
def get_labels(self, lang):
"""Gets the list of labels for this data set."""
raise NotImplementedError()
@classmethod
def read_csv(cls, input_file, quotechar=None):
"""Reads a tab separated value file."""
with open(input_file, encoding='utf-8') as fp:
return list(csv.reader(fp, delimiter=','))
@classmethod
def read_json(cls, input_file):
"""Reads a json file file."""
with open(input_file, encoding='utf-8') as fp:
return json.load(fp)
@classmethod
def readlines(cls, filepath):
with open(filepath, encoding='utf-8') as fp:
return fp.readlines()
@classmethod
def read_jsonl(cls, filepath):
with open(filepath, 'r', encoding='utf-8') as fp:
data = fp.readlines()
data = list(map(lambda l: json.loads(l), data))
return data
class IndicNLPHeadlines(DataProcessor):
"""Processor for the Headline Predction dataset"""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_train_examples(self, lang):
"""See base class."""
fname = '{}/{}-train.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'train')
def get_dev_examples(self, lang):
'''See base class.'''
fname = '{}/{}-valid.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'dev')
def get_test_examples(self, lang):
'''See base class.'''
fname = '{}/{}-test.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'test')
def get_labels(self, lang):
"""See base class."""
return ['A', 'B', 'C', 'D']
def _create_examples(self, items, set_type):
"""Creates examples for the training and dev sets."""
examples = [
MultipleChoiceExample(
example_id=idx,
question='',
contexts=[item['content'], item['content'], item['content'],
item['content']],
endings=[item['optionA'], item['optionB'], item['optionC'],
item['optionD']],
label=item['correctOption'],
)
for idx, item in enumerate(items)
]
return examples
class WikiCloze(DataProcessor):
"""Processor for Wiki Cloze QA dataset"""
def __init__(self, data_dir):
self.data_dir = data_dir
def modes(self):
return ['test']
def get_test_examples(self, lang):
"""See base class."""
fname = '{}.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath)['cloze_data'], 'test')
def get_labels(self, lang):
"""See base class."""
return list(range(4))
def _create_examples(self, items, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, item) in enumerate(items):
if '' in [option.strip() for option in item['options']]:
continue
example = MultipleChoiceExample(
example_id=i,
question=item['question'].replace('<MASK>', '[MASK]'),
contexts=[],
endings=item['options'],
label=item['options'].index(item['answer'])
)
examples.append(example)
return examples
class IndicNLPGenre(DataProcessor):
"""Processor for the Article Genre Classification data set"""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_train_examples(self, lang):
"""See base class."""
fname = '{}/{}-train.csv'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'train')
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/{}-valid.csv'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'dev')
def get_test_examples(self, lang):
fname = '{}/{}-test.csv'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'test')
def get_labels(self, lang):
"""See base class."""
filename = '{}/{}-train.csv'.format(lang, lang)
lines = self.read_csv(os.path.join(self.data_dir, filename))
labels = map(lambda l: l[0], lines)
labels = list(set(labels))
return labels
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
example = TextExample(
guid=('%s-%s' % (set_type, i)),
text_a=line[1],
label=line[0]
)
examples.append(example)
return examples
class WikiNER(DataProcessor):
def __init__(self, data_dir):
self.data_dir = data_dir
def get_examples(self, lang, mode):
mode = 'valid' if mode == 'dev' else mode
file_path = os.path.join(self.data_dir, lang, f'{mode}.txt')
guid_index = 1
examples = []
with open(file_path, encoding='utf-8') as f:
words = []
labels = []
for line in f:
if line.startswith('-DOCSTART-') or line == '' or line == '\n':
if words:
example = TokensExample(
guid=f'{mode}-{guid_index}',
words=words,
labels=labels
)
examples.append(example)
guid_index += 1
words = []
labels = []
else:
splits = line.split(' ')
words.append(splits[0])
if len(splits) > 1:
labels.append(splits[-1].replace('\n', ''))
else:
# Examples could have no label for mode = 'test'
labels.append('O')
if words:
example = TokensExample(
guid=f'{mode}-{guid_index}',
words=words,
labels=labels
)
examples.append(example)
return examples
def get_labels(self, lang):
path = os.path.join(self.data_dir, lang, 'labels.txt')
with open(path, 'r') as f:
labels = f.read().splitlines()
if 'O' not in labels:
labels = ['O'] + labels
return labels
class WikiSectionTitles(DataProcessor):
"""Processor for the Wikipedia Section Title Prediction dataset"""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_train_examples(self, lang):
"""See base class."""
fname = '{}/{}-train.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'train')
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/{}-valid.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'dev')
def get_test_examples(self, lang):
"""See base class."""
fname = '{}/{}-test.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'test')
def get_labels(self, lang):
"""See base class."""
return ['titleA', 'titleB', 'titleC', 'titleD']
def _create_examples(self, items, set_type):
"""Creates examples for the training and dev sets."""
examples = [
MultipleChoiceExample(
example_id=idx,
question='',
contexts=[item['sectionText'], item['sectionText'],
item['sectionText'], item['sectionText']],
endings=[item['titleA'], item['titleB'], item['titleC'],
item['titleD']],
label=item['correctTitle'],
)
for idx, item in enumerate(items)
]
return examples
class ManKiBaat(DataProcessor):
"""Processor for Man ki Baat dataset"""
def __init__(self, data_dir):
self.data_dir = data_dir
def modes(self):
return ['en', 'in']
def get_examples(self, lang, mode):
if mode == 'en':
return self.get_examples_en(lang)
elif mode == 'in':
return self.get_examples_in(lang)
def get_examples_en(self, lang):
"""Get examples of English language"""
fname = 'en-{}/mkb.en'.format(lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.readlines(fpath), 'en')
def get_examples_in(self, lang):
"""Get examples of the Indian language"""
fname = 'en-{}/mkb.{}'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.readlines(fpath), 'in')
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
example = TextExample(
guid=('%s-%s' % (set_type, i)),
text_a=line,
label=i
)
examples.append(example)
return examples
def get_labels(self, lang):
# return dummy value greater than number of examples
return list(range(10000))
class ACTSA(IndicNLPGenre):
pass
class BBCNews(IndicNLPGenre):
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/{}-test.csv'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'dev')
class INLTKHeadlines(IndicNLPGenre):
pass
class SohamArticles(IndicNLPGenre):
pass
class IITPMovies(IndicNLPGenre):
pass
class IITProducts(IndicNLPGenre):
pass
class AmritaParaphraseExact(IndicNLPGenre):
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/{}-test.csv'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'dev')
def get_labels(self, lang):
"""See base class."""
filename = '{}/{}-train.csv'.format(lang, lang)
lines = self.read_csv(os.path.join(self.data_dir, filename))
labels = map(lambda l: l[2], lines)
labels = list(set(labels))
return labels
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
example = TextExample(
guid=('%s-%s' % (set_type, i)),
text_a=line[0],
text_b=line[1],
label=line[2]
)
examples.append(example)
return examples
class AmritaParaphraseFuzzy(AmritaParaphraseExact):
pass
class MidasDiscourse(DataProcessor):
"""Processor for the Article Genre Classification data set"""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_train_examples(self, lang):
"""See base class."""
fname = '{}/train.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'train')
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/val.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'dev')
def get_test_examples(self, lang):
fname = '{}/test.json'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_json(fpath), 'test')
def get_labels(self, lang):
"""See base class."""
filename = '{}/train.json'.format(lang, lang)
lines = self.read_json(os.path.join(self.data_dir, filename))
labels = map(lambda l: l['Discourse Mode'], lines)
labels = list(set(labels))
return labels
def _create_examples(self, lines, set_type):
"""Creates examples for the training and dev sets."""
examples = []
for (i, line) in enumerate(lines):
example = TextExample(
guid=('%s-%s' % (set_type, i)),
text_a=line['Sentence'],
label=line['Discourse Mode']
)
examples.append(example)
return examples
class WNLI(DataProcessor):
"""Processor for the WNLI data set (GLUE version)."""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_train_examples(self, lang):
"""See base class."""
fname = '{}/train.csv'.format(lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'train')
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/dev.csv'.format(lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'dev')
def get_test_examples(self, lang):
"""See base class."""
fname = '{}/dev.csv'.format(lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_csv(fpath), 'test')
def get_labels(self, lang):
"""See base class."""
return ['0', '1']
def _create_examples(self, lines, set_type):
"""Creates examples for the training, dev and test sets."""
examples = []
for (i, line) in enumerate(lines):
if i == 0:
continue
guid = "%s-%s" % (set_type, line[0])
text_a = line[1]
text_b = line[2]
label = line[-1]
examples.append(TextExample(guid=guid, text_a=text_a, text_b=text_b, label=label))
return examples
class COPA(DataProcessor):
"""Processor for the Wikipedia Section Title Prediction dataset"""
def __init__(self, data_dir):
self.data_dir = data_dir
def get_train_examples(self, lang):
"""See base class."""
fname = '{}/train.jsonl'.format(lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_jsonl(fpath), 'train')
def get_dev_examples(self, lang):
"""See base class."""
fname = '{}/val.jsonl'.format(lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_jsonl(fpath), 'dev')
def get_test_examples(self, lang):
"""See base class."""
fname = '{}/val.jsonl'.format(lang, lang)
fpath = os.path.join(self.data_dir, fname)
return self._create_examples(self.read_jsonl(fpath), 'test')
def get_labels(self, lang):
"""See base class."""
return [0, 1]
def _create_examples(self, items, set_type):
"""Creates examples for the training and dev sets."""
examples = [
MultipleChoiceExample(
example_id=idx,
question='',
contexts=[item['premise'], item['premise']],
endings=[item['choice1'], item['choice2']],
label=item['label'],
)
for idx, item in enumerate(items)
]
return examples
|