ygorg commited on
Commit
69d4e68
·
verified ·
1 Parent(s): 0b42ceb

Delete loading script

Browse files
Files changed (1) hide show
  1. DEFT2021.py +0 -641
DEFT2021.py DELETED
@@ -1,641 +0,0 @@
1
- import os
2
- import random
3
- from typing import Dict, List
4
-
5
- from pathlib import Path
6
- import numpy as np
7
-
8
- import datasets
9
-
10
- _DESCRIPTION = """\
11
- ddd
12
- """
13
-
14
- _HOMEPAGE = "ddd"
15
-
16
- _LICENSE = "unknown"
17
-
18
- _CITATION = r"""\
19
- @inproceedings{grouin-etal-2021-classification,
20
- title = "Classification de cas cliniques et {\'e}valuation automatique de r{\'e}ponses d{'}{\'e}tudiants : pr{\'e}sentation de la campagne {DEFT} 2021 (Clinical cases classification and automatic evaluation of student answers : Presentation of the {DEFT} 2021 Challenge)",
21
- author = "Grouin, Cyril and
22
- Grabar, Natalia and
23
- Illouz, Gabriel",
24
- booktitle = "Actes de la 28e Conf{\'e}rence sur le Traitement Automatique des Langues Naturelles. Atelier D{\'E}fi Fouille de Textes (DEFT)",
25
- month = "6",
26
- year = "2021",
27
- address = "Lille, France",
28
- publisher = "ATALA",
29
- url = "https://aclanthology.org/2021.jeptalnrecital-deft.1",
30
- pages = "1--13",
31
- abstract = "Le d{\'e}fi fouille de textes (DEFT) est une campagne d{'}{\'e}valuation annuelle francophone. Nous pr{\'e}sentons les corpus et baselines {\'e}labor{\'e}es pour trois t{\^a}ches : (i) identifier le profil clinique de patients d{\'e}crits dans des cas cliniques, (ii) {\'e}valuer automatiquement les r{\'e}ponses d{'}{\'e}tudiants sur des questionnaires en ligne (Moodle) {\`a} partir de la correction de l{'}enseignant, et (iii) poursuivre une {\'e}valuation de r{\'e}ponses d{'}{\'e}tudiants {\`a} partir de r{\'e}ponses d{\'e}j{\`a} {\'e}valu{\'e}es par l{'}enseignant. Les r{\'e}sultats varient de 0,394 {\`a} 0,814 de F-mesure sur la premi{\`e}re t{\^a}che (7 {\'e}quipes), de 0,448 {\`a} 0,682 de pr{\'e}cision sur la deuxi{\`e}me (3 {\'e}quipes), et de 0,133 {\`a} 0,510 de pr{\'e}cision sur la derni{\`e}re (3 {\'e}quipes).",
32
- language = "French",
33
- }
34
- """
35
-
36
- _SPECIALITIES = ['immunitaire', 'endocriniennes', 'blessures', 'chimiques', 'etatsosy', 'nutritionnelles', 'infections', 'virales', 'parasitaires', 'tumeur', 'osteomusculaires', 'stomatognathique', 'digestif', 'respiratoire', 'ORL', 'nerveux', 'oeil', 'homme', 'femme', 'cardiovasculaires', 'hemopathies', 'genetique', 'peau']
37
-
38
- _LABELS_BASE = ['anatomie', 'date', 'dose', 'duree', 'examen', 'frequence', 'mode', 'moment', 'pathologie', 'sosy', 'substance', 'traitement', 'valeur']
39
-
40
- _URL = "data.zip"
41
-
42
-
43
- class DEFT2021(datasets.GeneratorBasedBuilder):
44
-
45
- DEFAULT_CONFIG_NAME = "ner"
46
-
47
- BUILDER_CONFIGS = [
48
- datasets.BuilderConfig(name="cls", version="1.0.0", description="DEFT 2021 corpora - Classification task"),
49
- datasets.BuilderConfig(name="ner", version="1.0.0", description="DEFT 2021 corpora - Named-entity recognition task"),
50
- ]
51
-
52
- def _info(self):
53
-
54
- if self.config.name.find("cls") != -1:
55
-
56
- features = datasets.Features(
57
- {
58
- "id": datasets.Value("string"),
59
- "document_id": datasets.Value("string"),
60
- "text": datasets.Value("string"),
61
- "specialities": datasets.Sequence(
62
- datasets.features.ClassLabel(names=_SPECIALITIES),
63
- ),
64
- "specialities_one_hot": datasets.Sequence(
65
- datasets.Value("float"),
66
- ),
67
- }
68
- )
69
-
70
- elif self.config.name.find("ner") != -1:
71
-
72
- features = datasets.Features(
73
- {
74
- "id": datasets.Value("string"),
75
- "document_id": datasets.Value("string"),
76
- "tokens": datasets.Sequence(datasets.Value("string")),
77
- "ner_tags": datasets.Sequence(
78
- datasets.features.ClassLabel(
79
- names=[
80
- 'O', 'B-anatomie', 'I-anatomie', 'B-date', 'I-date', 'B-dose',
81
- 'I-dose', 'B-duree', 'I-duree', 'B-examen', 'I-examen', 'B-frequence',
82
- 'I-frequence', 'B-mode', 'I-mode', 'B-moment', 'I-moment',
83
- 'B-pathologie', 'I-pathologie', 'B-sosy', 'I-sosy', 'B-substance',
84
- 'I-substance', 'B-traitement', 'I-traitement', 'B-valeur', 'I-valeur'
85
- ],
86
- )
87
- ),
88
- }
89
- )
90
-
91
- return datasets.DatasetInfo(
92
- description=_DESCRIPTION,
93
- features=features,
94
- supervised_keys=None,
95
- homepage=_HOMEPAGE,
96
- license=str(_LICENSE),
97
- citation=_CITATION,
98
- )
99
-
100
- def _split_generators(self, dl_manager):
101
-
102
- data_dir = dl_manager.download_and_extract(_URL).rstrip("/")
103
-
104
- return [
105
- datasets.SplitGenerator(
106
- name=datasets.Split.TRAIN,
107
- gen_kwargs={
108
- "data_dir": data_dir,
109
- "split": "train",
110
- },
111
- ),
112
- datasets.SplitGenerator(
113
- name=datasets.Split.VALIDATION,
114
- gen_kwargs={
115
- "data_dir": data_dir,
116
- "split": "validation",
117
- },
118
- ),
119
- datasets.SplitGenerator(
120
- name=datasets.Split.TEST,
121
- gen_kwargs={
122
- "data_dir": data_dir,
123
- "split": "test",
124
- },
125
- ),
126
- ]
127
-
128
- def remove_prefix(self, a: str, prefix: str) -> str:
129
- if a.startswith(prefix):
130
- a = a[len(prefix):]
131
- return a
132
-
133
- def parse_brat_file(self, txt_file: Path, annotation_file_suffixes: List[str] = None, parse_notes: bool = False) -> Dict:
134
-
135
- example = {}
136
- example["document_id"] = txt_file.with_suffix("").name
137
- with txt_file.open() as f:
138
- example["text"] = f.read()
139
-
140
- # If no specific suffixes of the to-be-read annotation files are given - take standard suffixes
141
- # for event extraction
142
- if annotation_file_suffixes is None:
143
- annotation_file_suffixes = [".a1", ".a2", ".ann"]
144
-
145
- if len(annotation_file_suffixes) == 0:
146
- raise AssertionError(
147
- "At least one suffix for the to-be-read annotation files should be given!"
148
- )
149
-
150
- ann_lines = []
151
- for suffix in annotation_file_suffixes:
152
- annotation_file = txt_file.with_suffix(suffix)
153
- if annotation_file.exists():
154
- with annotation_file.open() as f:
155
- ann_lines.extend(f.readlines())
156
-
157
- example["text_bound_annotations"] = []
158
- example["events"] = []
159
- example["relations"] = []
160
- example["equivalences"] = []
161
- example["attributes"] = []
162
- example["normalizations"] = []
163
-
164
- if parse_notes:
165
- example["notes"] = []
166
-
167
- for line in ann_lines:
168
- line = line.strip()
169
- if not line:
170
- continue
171
-
172
- if line.startswith("T"): # Text bound
173
- ann = {}
174
- fields = line.split("\t")
175
-
176
- ann["id"] = fields[0]
177
- ann["type"] = fields[1].split()[0]
178
- ann["offsets"] = []
179
- span_str = self.remove_prefix(fields[1], (ann["type"] + " "))
180
- text = fields[2]
181
- for span in span_str.split(";"):
182
- start, end = span.split()
183
- ann["offsets"].append([int(start), int(end)])
184
-
185
- # Heuristically split text of discontiguous entities into chunks
186
- ann["text"] = []
187
- if len(ann["offsets"]) > 1:
188
- i = 0
189
- for start, end in ann["offsets"]:
190
- chunk_len = end - start
191
- ann["text"].append(text[i:chunk_len + i])
192
- i += chunk_len
193
- while i < len(text) and text[i] == " ":
194
- i += 1
195
- else:
196
- ann["text"] = [text]
197
-
198
- example["text_bound_annotations"].append(ann)
199
-
200
- elif line.startswith("E"):
201
- ann = {}
202
- fields = line.split("\t")
203
-
204
- ann["id"] = fields[0]
205
-
206
- ann["type"], ann["trigger"] = fields[1].split()[0].split(":")
207
-
208
- ann["arguments"] = []
209
- for role_ref_id in fields[1].split()[1:]:
210
- argument = {
211
- "role": (role_ref_id.split(":"))[0],
212
- "ref_id": (role_ref_id.split(":"))[1],
213
- }
214
- ann["arguments"].append(argument)
215
-
216
- example["events"].append(ann)
217
-
218
- elif line.startswith("R"):
219
- ann = {}
220
- fields = line.split("\t")
221
-
222
- ann["id"] = fields[0]
223
- ann["type"] = fields[1].split()[0]
224
-
225
- ann["head"] = {
226
- "role": fields[1].split()[1].split(":")[0],
227
- "ref_id": fields[1].split()[1].split(":")[1],
228
- }
229
- ann["tail"] = {
230
- "role": fields[1].split()[2].split(":")[0],
231
- "ref_id": fields[1].split()[2].split(":")[1],
232
- }
233
-
234
- example["relations"].append(ann)
235
-
236
- # '*' seems to be the legacy way to mark equivalences,
237
- # but I couldn't find any info on the current way
238
- # this might have to be adapted dependent on the brat version
239
- # of the annotation
240
- elif line.startswith("*"):
241
- ann = {}
242
- fields = line.split("\t")
243
-
244
- ann["id"] = fields[0]
245
- ann["ref_ids"] = fields[1].split()[1:]
246
-
247
- example["equivalences"].append(ann)
248
-
249
- elif line.startswith("A") or line.startswith("M"):
250
- ann = {}
251
- fields = line.split("\t")
252
-
253
- ann["id"] = fields[0]
254
-
255
- info = fields[1].split()
256
- ann["type"] = info[0]
257
- ann["ref_id"] = info[1]
258
-
259
- if len(info) > 2:
260
- ann["value"] = info[2]
261
- else:
262
- ann["value"] = ""
263
-
264
- example["attributes"].append(ann)
265
-
266
- elif line.startswith("N"):
267
- ann = {}
268
- fields = line.split("\t")
269
-
270
- ann["id"] = fields[0]
271
- ann["text"] = fields[2]
272
-
273
- info = fields[1].split()
274
-
275
- ann["type"] = info[0]
276
- ann["ref_id"] = info[1]
277
- ann["resource_name"] = info[2].split(":")[0]
278
- ann["cuid"] = info[2].split(":")[1]
279
- example["normalizations"].append(ann)
280
-
281
- elif parse_notes and line.startswith("#"):
282
- ann = {}
283
- fields = line.split("\t")
284
-
285
- ann["id"] = fields[0]
286
- ann["text"] = fields[2] if len(fields) == 3 else "<BB_NULL_STR>"
287
-
288
- info = fields[1].split()
289
-
290
- ann["type"] = info[0]
291
- ann["ref_id"] = info[1]
292
- example["notes"].append(ann)
293
- return example
294
-
295
- def _to_source_example(self, brat_example: Dict) -> Dict:
296
-
297
- source_example = {
298
- "document_id": brat_example["document_id"],
299
- "text": brat_example["text"],
300
- }
301
-
302
- source_example["entities"] = []
303
-
304
- for entity_annotation in brat_example["text_bound_annotations"]:
305
- entity_ann = entity_annotation.copy()
306
-
307
- # Change id property name
308
- entity_ann["entity_id"] = entity_ann["id"]
309
- entity_ann.pop("id")
310
-
311
- # Add entity annotation to sample
312
- source_example["entities"].append(entity_ann)
313
-
314
- return source_example
315
-
316
- def convert_to_prodigy(self, json_object, list_label):
317
-
318
- def prepare_split(text):
319
-
320
- rep_before = ['?', '!', ';', '*']
321
- rep_after = ['’', "'"]
322
- rep_both = ['-', '/', '[', ']', ':', ')', '(', ',', '.']
323
-
324
- for i in rep_before:
325
- text = text.replace(i, ' ' + i)
326
-
327
- for i in rep_after:
328
- text = text.replace(i, i + ' ')
329
-
330
- for i in rep_both:
331
- text = text.replace(i, ' ' + i + ' ')
332
-
333
- text_split = text.split()
334
-
335
- punctuations = [',', '.']
336
- for j in range(0, len(text_split)-1):
337
- if j - 1 >= 0 and j + 1 <= len(text_split) - 1 and text_split[j-1][-1].isdigit() and text_split[j+1][0].isdigit():
338
- if text_split[j] in punctuations:
339
- text_split[j-1:j+2] = [''.join(text_split[j-1:j+2])]
340
-
341
- text = ' '.join(text_split)
342
-
343
- return text
344
-
345
- new_json = []
346
-
347
- for ex in [json_object]:
348
-
349
- text = prepare_split(ex['text'])
350
-
351
- tokenized_text = text.split()
352
-
353
- list_spans = []
354
-
355
- for a in ex['entities']:
356
-
357
- for o in range(len(a['offsets'])):
358
-
359
- text_annot = prepare_split(a['text'][o])
360
-
361
- offset_start = a['offsets'][o][0]
362
- offset_end = a['offsets'][o][1]
363
-
364
- nb_tokens_annot = len(text_annot.split())
365
-
366
- txt_offsetstart = prepare_split(ex['text'][:offset_start])
367
-
368
- nb_tokens_before_annot = len(txt_offsetstart.split())
369
-
370
- token_start = nb_tokens_before_annot
371
- token_end = token_start + nb_tokens_annot - 1
372
-
373
- if a['type'] in list_label:
374
- list_spans.append({
375
- 'start': offset_start,
376
- 'end': offset_end,
377
- 'token_start': token_start,
378
- 'token_end': token_end,
379
- 'label': a['type'],
380
- 'id': a['entity_id'],
381
- 'text': a['text'][o],
382
- })
383
-
384
- res = {
385
- 'id': ex['document_id'],
386
- 'document_id': ex['document_id'],
387
- 'text': ex['text'],
388
- 'tokens': tokenized_text,
389
- 'spans': list_spans
390
- }
391
-
392
- new_json.append(res)
393
-
394
- return new_json
395
-
396
- def convert_to_hf_format(self, json_object):
397
-
398
- dict_out = []
399
-
400
- for i in json_object:
401
-
402
- # Filter annotations to keep the longest annotated spans when there is nested annotations
403
- selected_annotations = []
404
-
405
- if 'spans' in i:
406
-
407
- for idx_j, j in enumerate(i['spans']):
408
-
409
- len_j = int(j['end']) - int(j['start'])
410
- range_j = [l for l in range(int(j['start']), int(j['end']), 1)]
411
-
412
- keep = True
413
-
414
- for idx_k, k in enumerate(i['spans'][idx_j+1:]):
415
-
416
- len_k = int(k['end']) - int(k['start'])
417
- range_k = [l for l in range(int(k['start']), int(k['end']), 1)]
418
-
419
- inter = list(set(range_k).intersection(set(range_j)))
420
- if len(inter) > 0 and len_j < len_k:
421
- keep = False
422
-
423
- if keep:
424
- selected_annotations.append(j)
425
-
426
- # Create list of labels + id to separate different annotation and prepare IOB2 format
427
- nb_tokens = len(i['tokens'])
428
- ner_tags = ['O'] * nb_tokens
429
-
430
- for slct in selected_annotations:
431
-
432
- for x in range(slct['token_start'], slct['token_end'] + 1, 1):
433
-
434
- if i['tokens'][x] not in slct['text']:
435
- if ner_tags[x-1] == 'O':
436
- ner_tags[x-1] = slct['label'] + '-' + slct['id']
437
- else:
438
- if ner_tags[x] == 'O':
439
- ner_tags[x] = slct['label'] + '-' + slct['id']
440
-
441
- # Make IOB2 format
442
- ner_tags_IOB2 = []
443
- for idx_l, label in enumerate(ner_tags):
444
-
445
- if label == 'O':
446
- ner_tags_IOB2.append('O')
447
- else:
448
- current_label = label.split('-')[0]
449
- current_id = label.split('-')[1]
450
- if idx_l == 0:
451
- ner_tags_IOB2.append('B-' + current_label)
452
- elif current_label in ner_tags[idx_l-1]:
453
- if current_id == ner_tags[idx_l-1].split('-')[1]:
454
- ner_tags_IOB2.append('I-' + current_label)
455
- else:
456
- ner_tags_IOB2.append('B-' + current_label)
457
- else:
458
- ner_tags_IOB2.append('B-' + current_label)
459
-
460
- dict_out.append({
461
- 'id': i['id'],
462
- 'document_id': i['document_id'],
463
- "ner_tags": ner_tags_IOB2,
464
- "tokens": i['tokens'],
465
- })
466
-
467
- return dict_out
468
-
469
- def split_sentences(self, json_o):
470
- """
471
- Split each document in sentences to fit the 512 maximum tokens of BERT.
472
- """
473
-
474
- final_json = []
475
-
476
- for i in json_o:
477
-
478
- ind_punc = [index for index, value in enumerate(i['tokens']) if value == '.'] + [len(i['tokens'])]
479
-
480
- for index, value in enumerate(ind_punc):
481
-
482
- if index == 0:
483
- final_json.append({
484
- 'id': i['id'] + '_' + str(index),
485
- 'document_id': i['document_id'],
486
- 'ner_tags': i['ner_tags'][:value+1],
487
- 'tokens': i['tokens'][:value+1]
488
- })
489
- else:
490
- prev_value = ind_punc[index-1]
491
- final_json.append({
492
- 'id': i['id'] + '_' + str(index),
493
- 'document_id': i['document_id'],
494
- 'ner_tags': i['ner_tags'][prev_value+1:value+1],
495
- 'tokens': i['tokens'][prev_value+1:value+1]
496
- })
497
-
498
- return final_json
499
-
500
- def _generate_examples(self, data_dir, split):
501
-
502
- if self.config.name.find("cls") != -1:
503
-
504
- all_res = {}
505
-
506
- key = 0
507
-
508
- if split == 'train' or split == 'validation':
509
- split_eval = 'train'
510
- else:
511
- split_eval = 'test'
512
-
513
- path_labels = Path(data_dir) / 'evaluations' / f"ref-{split_eval}-deft2021.txt"
514
-
515
- with open(os.path.join(data_dir, 'distribution-corpus.txt')) as f_dist:
516
-
517
- doc_specialities_ = {}
518
-
519
- with open(path_labels) as f_spec:
520
-
521
- doc_specialities = [line.strip() for line in f_spec.readlines()]
522
-
523
- for raw in doc_specialities:
524
-
525
- raw_split = raw.split('\t')
526
-
527
- if len(raw_split) == 3 and raw_split[0] in doc_specialities_:
528
- doc_specialities_[raw_split[0]].append(raw_split[1])
529
-
530
- elif len(raw_split) == 3 and raw_split[0] not in doc_specialities_:
531
- doc_specialities_[raw_split[0]] = [raw_split[1]]
532
-
533
- ann_path = Path(data_dir) / "DEFT-cas-cliniques"
534
-
535
- for guid, txt_file in enumerate(sorted(ann_path.glob("*.txt"))):
536
-
537
- ann_file = txt_file.with_suffix("").name.split('.')[0] + '.ann'
538
-
539
- if ann_file in doc_specialities_:
540
-
541
- res = {}
542
- res['document_id'] = txt_file.with_suffix("").name
543
- with txt_file.open() as f:
544
- res["text"] = f.read()
545
-
546
- specialities = doc_specialities_[ann_file]
547
-
548
- # Empty one hot vector
549
- one_hot = [0.0 for i in _SPECIALITIES]
550
-
551
- # Fill up the one hot vector
552
- for s in specialities:
553
- one_hot[_SPECIALITIES.index(s)] = 1.0
554
-
555
- all_res[res['document_id']] = {
556
- "id": str(key),
557
- "document_id": res['document_id'],
558
- "text": res["text"],
559
- "specialities": specialities,
560
- "specialities_one_hot": one_hot,
561
- }
562
-
563
- key += 1
564
-
565
- distribution = [line.strip() for line in f_dist.readlines()]
566
-
567
- random.seed(4)
568
- train = [raw.split('\t')[0] for raw in distribution if len(raw.split('\t')) == 4 and raw.split('\t')[3] == 'train 2021']
569
- random.shuffle(train)
570
- random.shuffle(train)
571
- random.shuffle(train)
572
- train, validation = np.split(train, [int(len(train)*0.7096)])
573
-
574
- test = [raw.split('\t')[0] for raw in distribution if len(raw.split('\t')) == 4 and raw.split('\t')[3] == 'test 2021']
575
-
576
- if split == "train":
577
- allowed_ids = list(train)
578
- elif split == "test":
579
- allowed_ids = list(test)
580
- elif split == "validation":
581
- allowed_ids = list(validation)
582
-
583
- for r in all_res.values():
584
- if r["document_id"] + '.txt' in allowed_ids:
585
- yield r["id"], r
586
-
587
- elif self.config.name.find("ner") != -1:
588
-
589
- all_res = []
590
-
591
- key = 0
592
-
593
- with open(os.path.join(data_dir, 'distribution-corpus.txt')) as f_dist:
594
-
595
- distribution = [line.strip() for line in f_dist.readlines()]
596
-
597
- random.seed(4)
598
- train = [raw.split('\t')[0] for raw in distribution if len(raw.split('\t')) == 4 and raw.split('\t')[3] == 'train 2021']
599
- random.shuffle(train)
600
- random.shuffle(train)
601
- random.shuffle(train)
602
- train, validation = np.split(train, [int(len(train)*0.73)])
603
- test = [raw.split('\t')[0] for raw in distribution if len(raw.split('\t')) == 4 and raw.split('\t')[3] == 'test 2021']
604
-
605
- ann_path = Path(data_dir) / "DEFT-cas-cliniques"
606
-
607
- for guid, txt_file in enumerate(sorted(ann_path.glob("*.txt"))):
608
-
609
- brat_example = self.parse_brat_file(txt_file, parse_notes=True)
610
-
611
- source_example = self._to_source_example(brat_example)
612
-
613
- prod_format = self.convert_to_prodigy(source_example, _LABELS_BASE)
614
-
615
- hf_format = self.convert_to_hf_format(prod_format)
616
-
617
- hf_split = self.split_sentences(hf_format)
618
-
619
- for h in hf_split:
620
-
621
- if len(h['tokens']) > 0 and len(h['ner_tags']) > 0:
622
-
623
- all_res.append({
624
- "id": str(key),
625
- "document_id": h['document_id'],
626
- "tokens": h['tokens'],
627
- "ner_tags": h['ner_tags'],
628
- })
629
-
630
- key += 1
631
-
632
- if split == "train":
633
- allowed_ids = list(train)
634
- elif split == "validation":
635
- allowed_ids = list(validation)
636
- elif split == "test":
637
- allowed_ids = list(test)
638
-
639
- for r in all_res:
640
- if r["document_id"] + '.txt' in allowed_ids:
641
- yield r["id"], r