File size: 12,726 Bytes
3f5d38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import glob
from dataclasses import dataclass
from typing import Dict, List
from pathlib import Path

import datasets


def remove_prefix(a: str, prefix: str) -> str:
    if a.startswith(prefix):
        a = a[len(prefix) :]
    return a


def parse_brat_file(
    txt_file: Path,
    annotation_file_suffixes: List[str] = None,
    parse_notes: bool = False,
) -> Dict:
    """
    Parse a brat file into the schema defined below.
    `txt_file` should be the path to the brat '.txt' file you want to parse, e.g. 'data/1234.txt'
    Assumes that the annotations are contained in one or more of the corresponding '.a1', '.a2' or '.ann' files,
    e.g. 'data/1234.ann' or 'data/1234.a1' and 'data/1234.a2'.
    Will include annotator notes, when `parse_notes == True`.
    brat_features = datasets.Features(
        {
            "id": datasets.Value("string"),
            "document_id": datasets.Value("string"),
            "text": datasets.Value("string"),
            "text_bound_annotations": [  # T line in brat, e.g. type or event trigger
                {
                    "offsets": datasets.Sequence([datasets.Value("int32")]),
                    "text": datasets.Sequence(datasets.Value("string")),
                    "type": datasets.Value("string"),
                    "id": datasets.Value("string"),
                }
            ],
            "events": [  # E line in brat
                {
                    "trigger": datasets.Value(
                        "string"
                    ),  # refers to the text_bound_annotation of the trigger,
                    "id": datasets.Value("string"),
                    "type": datasets.Value("string"),
                    "arguments": datasets.Sequence(
                        {
                            "role": datasets.Value("string"),
                            "ref_id": datasets.Value("string"),
                        }
                    ),
                }
            ],
            "relations": [  # R line in brat
                {
                    "id": datasets.Value("string"),
                    "head": {
                        "ref_id": datasets.Value("string"),
                        "role": datasets.Value("string"),
                    },
                    "tail": {
                        "ref_id": datasets.Value("string"),
                        "role": datasets.Value("string"),
                    },
                    "type": datasets.Value("string"),
                }
            ],
            "equivalences": [  # Equiv line in brat
                {
                    "id": datasets.Value("string"),
                    "ref_ids": datasets.Sequence(datasets.Value("string")),
                }
            ],
            "attributes": [  # M or A lines in brat
                {
                    "id": datasets.Value("string"),
                    "type": datasets.Value("string"),
                    "ref_id": datasets.Value("string"),
                    "value": datasets.Value("string"),
                }
            ],
            "normalizations": [  # N lines in brat
                {
                    "id": datasets.Value("string"),
                    "type": datasets.Value("string"),
                    "ref_id": datasets.Value("string"),
                    "resource_name": datasets.Value(
                        "string"
                    ),  # Name of the resource, e.g. "Wikipedia"
                    "cuid": datasets.Value(
                        "string"
                    ),  # ID in the resource, e.g. 534366
                    "text": datasets.Value(
                        "string"
                    ),  # Human readable description/name of the entity, e.g. "Barack Obama"
                }
            ],
            ### OPTIONAL: Only included when `parse_notes == True`
            "notes": [  # # lines in brat
                {
                    "id": datasets.Value("string"),
                    "type": datasets.Value("string"),
                    "ref_id": datasets.Value("string"),
                    "text": datasets.Value("string"),
                }
            ],
        },
        )
    """

    example = {}
    example["document_id"] = txt_file.with_suffix("").name
    with txt_file.open() as f:
        example["text"] = f.read()

    # If no specific suffixes of the to-be-read annotation files are given - take standard suffixes
    # for event extraction
    if annotation_file_suffixes is None:
        annotation_file_suffixes = [".a1", ".a2", ".ann"]

    if len(annotation_file_suffixes) == 0:
        raise AssertionError(
            "At least one suffix for the to-be-read annotation files should be given!"
        )

    ann_lines = []
    for suffix in annotation_file_suffixes:
        annotation_file = txt_file.with_suffix(suffix)
        if annotation_file.exists():
            with annotation_file.open() as f:
                ann_lines.extend(f.readlines())

    example["text_bound_annotations"] = []
    example["events"] = []
    example["relations"] = []
    example["equivalences"] = []
    example["attributes"] = []
    example["normalizations"] = []

    if parse_notes:
        example["notes"] = []

    for line in ann_lines:
        line = line.strip()
        if not line:
            continue

        if line.startswith("T"):  # Text bound
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]
            ann["type"] = fields[1].split()[0]
            ann["offsets"] = []
            span_str = remove_prefix(fields[1], (ann["type"] + " "))
            text = fields[2]
            for span in span_str.split(";"):
                start, end = span.split()
                ann["offsets"].append([int(start), int(end)])

            # Heuristically split text of discontiguous entities into chunks
            ann["text"] = []
            if len(ann["offsets"]) > 1:
                i = 0
                for start, end in ann["offsets"]:
                    chunk_len = end - start
                    ann["text"].append(text[i : chunk_len + i])
                    i += chunk_len
                    while i < len(text) and text[i] == " ":
                        i += 1
            else:
                ann["text"] = [text]

            example["text_bound_annotations"].append(ann)

        elif line.startswith("E"):
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]

            ann["type"], ann["trigger"] = fields[1].split()[0].split(":")

            ann["arguments"] = []
            for role_ref_id in fields[1].split()[1:]:
                argument = {
                    "role": (role_ref_id.split(":"))[0],
                    "ref_id": (role_ref_id.split(":"))[1],
                }
                ann["arguments"].append(argument)

            example["events"].append(ann)

        elif line.startswith("R"):
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]
            ann["type"] = fields[1].split()[0]

            ann["head"] = {
                "role": fields[1].split()[1].split(":")[0],
                "ref_id": fields[1].split()[1].split(":")[1],
            }
            ann["tail"] = {
                "role": fields[1].split()[2].split(":")[0],
                "ref_id": fields[1].split()[2].split(":")[1],
            }

            example["relations"].append(ann)

        # '*' seems to be the legacy way to mark equivalences,
        # but I couldn't find any info on the current way
        # this might have to be adapted dependent on the brat version
        # of the annotation
        elif line.startswith("*"):
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]
            ann["ref_ids"] = fields[1].split()[1:]

            example["equivalences"].append(ann)

        elif line.startswith("A") or line.startswith("M"):
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]

            info = fields[1].split()
            ann["type"] = info[0]
            ann["ref_id"] = info[1]

            if len(info) > 2:
                ann["value"] = info[2]
            else:
                ann["value"] = ""

            example["attributes"].append(ann)

        elif line.startswith("N"):
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]
            ann["text"] = fields[2]

            info = fields[1].split()

            ann["type"] = info[0]
            ann["ref_id"] = info[1]
            ann["resource_name"] = info[2].split(":")[0]
            ann["cuid"] = info[2].split(":")[1]
            example["normalizations"].append(ann)

        elif parse_notes and line.startswith("#"):
            ann = {}
            fields = line.split("\t")

            ann["id"] = fields[0]
            ann["text"] = fields[2] if len(fields) == 3 else None

            info = fields[1].split()

            ann["type"] = info[0]
            ann["ref_id"] = info[1]
            example["notes"].append(ann)

    return example


_CITATION = """\
@inproceedings{lauscher2018b,
  title = {An argument-annotated corpus of scientific publications},
  booktitle = {Proceedings of the 5th Workshop on Mining Argumentation},
  publisher = {Association for Computational Linguistics},
  author = {Lauscher, Anne and Glava\v{s}, Goran and Ponzetto, Simone Paolo},
  address = {Brussels, Belgium},
  year = {2018},
  pages = {40–46}
}
"""
_DESCRIPTION = """\
The SciArg dataset is an extension of the Dr. Inventor corpus (Fisas et al., 2015, 2016) with an annotation layer containing 
fine-grained argumentative components and relations. It is the first argument-annotated corpus of scientific 
publications (in English), which allows for joint analyses of argumentation and other rhetorical dimensions of 
scientific writing.
"""
_URL = "http://data.dws.informatik.uni-mannheim.de/sci-arg/compiled_corpus.zip"
_HOMEPAGE = "https://github.com/anlausch/ArguminSci"


@dataclass
class SciArgConfig(datasets.BuilderConfig):
    data_url = _URL
    subdirectory_mapping = {"compiled_corpus": datasets.Split.TRAIN}
    filename_blacklist = []  #["A28"]


class SciArg(datasets.GeneratorBasedBuilder):
    """Scientific Argument corpus"""

    DEFAULT_CONFIG_CLASS = SciArgConfig

    BUILDER_CONFIGS = [
        SciArgConfig(
            name="full",
            version="1.0.0",
        ),
    ]

    DEFAULT_CONFIG_NAME = "full"

    def _info(self) -> datasets.DatasetInfo:
        features = datasets.Features(
            {
                "document_id": datasets.Value("string"),
                "text": datasets.Value("string"),
                "text_bound_annotations": [
                    {
                        "offsets": datasets.Sequence([datasets.Value("int32")]),
                        "text": datasets.Value("string"),
                        "type": datasets.Value("string"),
                        "id": datasets.Value("string"),
                    }
                ],
                "relations": [
                    {
                        "id": datasets.Value("string"),
                        "head": {
                            "ref_id": datasets.Value("string"),
                            "role": datasets.Value("string"),
                        },
                        "tail": {
                            "ref_id": datasets.Value("string"),
                            "role": datasets.Value("string"),
                        },
                        "type": datasets.Value("string"),
                    }
                ],
            }
        )

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
        """Returns SplitGenerators."""
        data_dir = self.config.data_dir or Path(dl_manager.download_and_extract(self.config.data_url))

        return [
            datasets.SplitGenerator(name=split, gen_kwargs={"filepath": data_dir / subdir})
            for subdir, split in self.config.subdirectory_mapping.items()
        ]

    def _generate_examples(self, filepath):
        for txt_file in glob.glob(filepath / "*.txt"):

            brat_parsed = parse_brat_file(Path(txt_file))
            if brat_parsed["document_id"] in self.config.filename_blacklist:
                continue
            relevant_subset = {f_name: brat_parsed[f_name] for f_name in self.info.features}
            yield brat_parsed["document_id"], relevant_subset