File size: 14,559 Bytes
14844e8
 
8b963a9
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6dfc86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b963a9
e6dfc86
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6dfc86
 
 
 
 
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e6dfc86
 
 
 
 
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5311176
14844e8
 
e6dfc86
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5311176
14844e8
 
e6dfc86
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5311176
14844e8
 
 
 
 
 
 
 
5311176
14844e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import random
import requests

import datasets
import numpy as np

_CITATION = """\
 @misc{
    dalloux,
    title={Datasets – Clément Dalloux},
    url={http://clementdalloux.fr/?page_id=28},
    journal={Clément Dalloux},
    author={Dalloux, Clément}
} 
"""

_DESCRIPTION = """\
We manually annotated two corpora from the biomedical field. The ESSAI corpus \
contains clinical trial protocols in French. They were mainly obtained from the \
National Cancer Institute The typical protocol consists of two parts: the \
summary of the trial, which indicates the purpose of the trial and the methods \
applied; and a detailed description of the trial with the inclusion and \
exclusion criteria. The CAS corpus contains clinical cases published in \
scientific literature and training material. They are published in different \
journals from French-speaking countries (France, Belgium, Switzerland, Canada, \
African countries, tropical countries) and are related to various medical \
specialties (cardiology, urology, oncology, obstetrics, pulmonology, \
gastro-enterology). The purpose of clinical cases is to describe clinical \
situations of patients. Hence, their content is close to the content of clinical \
narratives (description of diagnoses, treatments or procedures, evolution, \
family history, expected audience, etc.). In clinical cases, the negation is \
frequently used for describing the patient signs, symptoms, and diagnosis. \
Speculation is present as well but less frequently.

This version only contain the annotated ESSAI corpus
"""

_HOMEPAGE = "https://clementdalloux.fr/?page_id=28"

_LICENSE = 'Data User Agreement'

class StringIndex:

    def __init__(self, vocab):

        self.vocab_struct = {}

        print("Start building the index!")
        for t in vocab:

            if len(t) == 0:
                continue

            # Index terms by their first letter and length
            key = (t[0], len(t))

            if (key in self.vocab_struct) == False:
                self.vocab_struct[key] = []
            
            self.vocab_struct[key].append(t)

        print("Finished building the index!")

    def find(self, t):
        
        key = (t[0], len(t))
        
        if (key in self.vocab_struct) == False:
            return "is_oov"
        
        return "is_not_oov" if t in self.vocab_struct[key] else "is_oov"

_VOCAB = StringIndex(vocab=requests.get("https://huggingface.co/datasets/BioMedTok/vocabulary_nachos_lowercased/resolve/main/vocabulary_nachos_lowercased.txt").text.split("\n"))

class ESSAI(datasets.GeneratorBasedBuilder):

    DEFAULT_CONFIG_NAME = "pos_spec"

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="pos", version="1.0.0", description="The ESSAI corpora - POS Speculation task"),

        datasets.BuilderConfig(name="cls", version="1.0.0", description="The ESSAI corpora - CLS Negation / Speculation task"),

        datasets.BuilderConfig(name="ner_spec", version="1.0.0", description="The ESSAI corpora - NER Speculation task"),
        datasets.BuilderConfig(name="ner_neg", version="1.0.0", description="The ESSAI corpora - NER Negation task"),
    ]

    def _info(self):

        if self.config.name.find("pos") != -1:

            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "document_id": datasets.Value("string"),
                    "tokens": [datasets.Value("string")],
                    "lemmas": [datasets.Value("string")],
                    "pos_tags": [datasets.features.ClassLabel(
                        names = ['B-INT', 'B-PRO:POS', 'B-PRP', 'B-SENT', 'B-PRO', 'B-ABR', 'B-VER:pres', 'B-KON', 'B-SYM', 'B-DET:POS', 'B-VER:', 'B-PRO:IND', 'B-NAM', 'B-ADV', 'B-PRO:DEM', 'B-NN', 'B-PRO:PER', 'B-VER:pper', 'B-VER:ppre', 'B-PUN', 'B-VER:simp', 'B-PREF', 'B-NUM', 'B-VER:futu', 'B-NOM', 'B-VER:impf', 'B-VER:subp', 'B-VER:infi', 'B-DET:ART', 'B-PUN:cit', 'B-ADJ', 'B-PRP:det', 'B-PRO:REL', 'B-VER:cond', 'B-VER:subi'],
                    )],
                    "is_oov": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=['is_not_oov', 'is_oov'],
                        ),
                    ),
                }
            )
        
        elif self.config.name.find("cls") != -1:

            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "document_id": datasets.Value("string"),
                    "tokens": [datasets.Value("string")],
                    "label": datasets.features.ClassLabel(
                        names = ['negation_speculation', 'negation', 'neutral', 'speculation'],
                    ),
                }
            )
        
        elif self.config.name.find("ner") != -1:

            if self.config.name.find("_spec") != -1:
                names = ['O', 'B_cue_spec', 'B_scope_spec', 'I_scope_spec']
            elif self.config.name.find("_neg") != -1:
                names = ['O', 'B_cue_neg', 'B_scope_neg', 'I_scope_neg']

            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "document_id": datasets.Value("string"),
                    "tokens": [datasets.Value("string")],
                    "lemmas": [datasets.Value("string")],
                    "ner_tags": [datasets.features.ClassLabel(
                        names = names,
                    )],
                    "is_oov": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=['is_not_oov', 'is_oov'],
                        ),
                    ),
                }
            )

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=str(_LICENSE),
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):

        if self.config.data_dir is None:
            raise ValueError("This is a local dataset. Please pass the data_dir kwarg to load_dataset.")
        
        else:
            data_dir = self.config.data_dir
            
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "datadir": data_dir,
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "datadir": data_dir,
                    "split": "validation",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "datadir": data_dir,
                    "split": "test",
                },
            ),
        ]

    def _generate_examples(self, datadir, split):

        all_res = []

        key = 0

        subset = self.config.name.split("_")[-1]

        unique_id_doc = []

        if self.config.name.find("ner") != -1:
            docs = [f"ESSAI_{subset}.txt"]
        else:
            docs = ["ESSAI_neg.txt", "ESSAI_spec.txt"]

        for file in docs:

            filename = os.path.join(datadir, file)

            if self.config.name.find("pos") != -1:

                id_docs = []
                id_words = []
                words = []
                lemmas = []
                POS_tags = []

                with open(filename) as f:

                    for line in f.readlines():

                        splitted = line.split("\t")

                        if len(splitted) < 5:
                            continue

                        id_doc, id_word, word, lemma, tag = splitted[0:5]
                        if len(splitted) >= 8:
                            tag = splitted[6]
                        
                        if tag == "@card@":
                            print(splitted)

                        if word == "@card@":
                            print(splitted)

                        if lemma == "000" and tag == "@card@":
                            tag = "NUM"
                            word = "100 000"
                            lemma = "100 000"
                        elif lemma == "45" and tag == "@card@":
                            tag = "NUM"

                        # if id_doc in id_docs:
                        #     continue

                        id_docs.append(id_doc)
                        id_words.append(id_word)
                        words.append(word)
                        lemmas.append(lemma)
                        POS_tags.append('B-'+tag)

                dic = {
                    "id_docs":  np.array(list(map(int, id_docs))),
                    "id_words": id_words,
                    "words":    words,
                    "lemmas":   lemmas,
                    "POS_tags": POS_tags,
                }

                for doc_id in set(dic["id_docs"]):

                    indexes = np.argwhere(dic["id_docs"] == doc_id)[:, 0]
                    tokens = [dic["words"][id] for id in indexes]
                    text_lemmas = [dic["lemmas"][id] for id in indexes]
                    pos_tags = [dic["POS_tags"][id] for id in indexes]

                    if doc_id not in unique_id_doc:

                        all_res.append({
                            "id": str(doc_id),
                            "document_id": doc_id,
                            "tokens": [tok.lower() for tok in tokens],
                            "lemmas": text_lemmas,
                            "pos_tags": pos_tags,
                            "is_oov": [_VOCAB.find(tt.lower()) for tt in tokens],
                        })
                        unique_id_doc.append(doc_id)

                        # key += 1

            elif self.config.name.find("ner") != -1:

                id_docs = []
                id_words = []
                words = []
                lemmas = []
                ner_tags = []

                with open(filename) as f:

                    for line in f.readlines():

                        if len(line.split("\t")) < 5:
                            continue

                        id_doc, id_word, word, lemma, _ = line.split("\t")[0:5]
                        tag = line.replace("\n","").split("\t")[-1]

                        if tag == "***" or tag == "_":
                            tag = "O"
                        elif tag == "v":
                            tag = "I_scope_spec"
                        elif tag == "z":
                            tag = "O"
                        elif tag == "I_scope_spec_":
                            tag = "I_scope_spec"

                        id_docs.append(id_doc)
                        id_words.append(id_word)
                        words.append(word)
                        lemmas.append(lemma)
                        ner_tags.append(tag)

                dic = {
                    "id_docs":  np.array(list(map(int, id_docs))),
                    "id_words": id_words,
                    "words":    words,
                    "lemmas":   lemmas,
                    "ner_tags": ner_tags,
                }

                for doc_id in set(dic["id_docs"]):

                    indexes = np.argwhere(dic["id_docs"] == doc_id)[:, 0]
                    tokens = [dic["words"][id] for id in indexes]
                    text_lemmas = [dic["lemmas"][id] for id in indexes]
                    ner_tags = [dic["ner_tags"][id] for id in indexes]

                    all_res.append({
                        "id": key,
                        "document_id": doc_id,
                        "tokens": [tok.lower() for tok in tokens],
                        "lemmas": text_lemmas,
                        "ner_tags": ner_tags,
                        "is_oov": [_VOCAB.find(tt.lower()) for tt in tokens],
                    })

                    key += 1

            elif self.config.name.find("cls") != -1:

                f_in = open(filename, "r")
                conll = [
                    [b.split("\t") for b in a.split("\n")]
                    for a in f_in.read().split("\n\n")
                ]
                f_in.close()

                classe = "negation" if filename.find("_neg") != -1 else "speculation"

                for document in conll:

                    if document == [""]:
                        continue

                    identifier = document[0][0]

                    unique = list(set([w[-1] for w in document]))
                    tokens = [sent[2] for sent in document if len(sent) > 1]

                    if "***" in unique:
                        l = "neutral"
                    elif "_" in unique:
                        l = classe

                    if identifier in unique_id_doc and l == 'neutral':
                        continue

                    elif identifier in unique_id_doc and l != 'neutral':

                        index_l = unique_id_doc.index(identifier)

                        if all_res[index_l]["label"] != "neutral":
                            l = "negation_speculation"

                        all_res[index_l] = {
                            "id": str(identifier),
                            "document_id": identifier,
                            "tokens": [tok.lower() for tok in tokens],
                            "label": l,
                        }

                    else:

                        all_res.append({
                            "id": str(identifier),
                            "document_id": identifier,
                            "tokens": [tok.lower() for tok in tokens],
                            "label": l,
                        })

                        unique_id_doc.append(identifier)

        ids = [r["id"] for r in all_res]

        random.seed(4)
        random.shuffle(ids)
        random.shuffle(ids)
        random.shuffle(ids)

        train, validation, test = np.split(ids, [int(len(ids)*0.70), int(len(ids)*0.80)])

        if split == "train":
            allowed_ids = list(train)
        elif split == "validation":
            allowed_ids = list(validation)
        elif split == "test":
            allowed_ids = list(test)

        for r in all_res:
            if r["id"] in allowed_ids:
                yield r["id"], r