File size: 26,395 Bytes
0f218f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f28bfbf
0f218f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f28bfbf
15676c8
f28bfbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7188b32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f218f8
 
 
7a18504
0f218f8
 
 
 
 
 
 
 
 
 
 
 
 
f28bfbf
 
 
 
0f218f8
f28bfbf
0f218f8
 
f28bfbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a18504
 
 
 
 
 
 
 
15676c8
0f218f8
f28bfbf
 
 
7a18504
 
 
 
f28bfbf
 
 
 
 
 
0f218f8
f28bfbf
7188b32
 
f28bfbf
 
 
 
 
 
 
7188b32
f28bfbf
 
 
 
 
 
 
 
 
15676c8
f28bfbf
 
 
 
 
 
15676c8
 
 
7a18504
15676c8
 
7a18504
15676c8
 
7a18504
15676c8
 
f28bfbf
 
 
 
 
 
 
 
15676c8
f28bfbf
 
 
 
 
 
 
7a18504
 
f28bfbf
 
 
 
 
7a18504
 
f28bfbf
7a18504
f28bfbf
 
7a18504
f28bfbf
 
 
7a18504
f28bfbf
 
7188b32
 
 
 
 
f28bfbf
 
 
 
0f218f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15676c8
0f218f8
 
f28bfbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7188b32
 
f28bfbf
15676c8
 
f28bfbf
 
 
 
 
 
0f218f8
f28bfbf
 
 
 
 
 
 
 
 
 
7188b32
 
f28bfbf
 
15676c8
 
f28bfbf
15676c8
f28bfbf
15676c8
f28bfbf
7188b32
 
 
 
 
 
 
 
 
 
15676c8
f28bfbf
7188b32
 
 
 
f28bfbf
7188b32
f28bfbf
 
 
 
 
 
 
7188b32
 
 
 
 
 
 
 
 
 
f28bfbf
 
 
 
7188b32
15676c8
f28bfbf
 
 
 
 
15676c8
 
 
7188b32
 
15676c8
7188b32
15676c8
 
f28bfbf
15676c8
7188b32
15676c8
7188b32
15676c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f28bfbf
 
 
 
 
 
 
 
 
 
 
 
 
 
7188b32
 
 
 
f28bfbf
 
 
 
7188b32
 
 
 
 
 
 
 
 
 
 
f28bfbf
 
7188b32
 
 
 
f28bfbf
 
 
 
 
 
 
7188b32
 
 
 
f28bfbf
 
 
 
 
 
 
15676c8
7188b32
 
 
 
 
f28bfbf
 
 
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
523
524
525
526
527
528
529
530
531
532
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""\
MobIE is a German-language dataset which is human-annotated with 20 coarse- and fine-grained entity types and entity linking information for geographically linkable entities. The dataset consists of 3,232 social media texts and traffic reports with 91K tokens, and contains 20.5K annotated entities, 13.1K of which are linked to a knowledge base. A subset of the dataset is human-annotated with seven mobility-related, n-ary relation types, while the remaining documents are annotated using a weakly-supervised labeling approach implemented with the Snorkel framework. The dataset combines annotations for NER, EL and RE, and thus can be used for joint and multi-task learning of these fundamental information extraction tasks."""

import re
import json
from json import JSONDecodeError, JSONDecoder

import datasets


_CITATION = """\
        @inproceedings{hennig-etal-2021-mobie,
    title = "{M}ob{IE}: A {G}erman Dataset for Named Entity Recognition, Entity Linking and Relation Extraction in the Mobility Domain",
    author = "Hennig, Leonhard  and
      Truong, Phuc Tran  and
      Gabryszak, Aleksandra",
    booktitle = "Proceedings of the 17th Conference on Natural Language Processing (KONVENS 2021)",
    month = "6--9 " # sep,
    year = "2021",
    address = {D{\"u}sseldorf, Germany},
    publisher = "KONVENS 2021 Organizers",
    url = "https://aclanthology.org/2021.konvens-1.22",
    pages = "223--227",
}
"""

_DESCRIPTION = """\
MobIE is a German-language dataset which is human-annotated with 20 coarse- and fine-grained entity types and entity linking information for geographically linkable entities. The dataset consists of 3,232 social media texts and traffic reports with 91K tokens, and contains 20.5K annotated entities, 13.1K of which are linked to a knowledge base. A subset of the dataset is human-annotated with seven mobility-related, n-ary relation types, while the remaining documents are annotated using a weakly-supervised labeling approach implemented with the Snorkel framework. The dataset combines annotations for NER, EL and RE, and thus can be used for joint and multi-task learning of these fundamental information extraction tasks."""

_HOMEPAGE = "https://github.com/dfki-nlp/mobie"

_LICENSE = "CC-BY 4.0"

_URLs = {
    "train": "https://github.com/DFKI-NLP/MobIE/raw/master/v1_20210811/train.jsonl.gz",
    "dev": "https://github.com/DFKI-NLP/MobIE/raw/master/v1_20210811/dev.jsonl.gz",
    "test": "https://github.com/DFKI-NLP/MobIE/raw/master/v1_20210811/test.jsonl.gz",
}


def simplify_dict(d, remove_attribute=True):
    """Simplify nested dictionary by removing unnecessary keys"""
    if isinstance(d, dict):
        new_dict = {}
        for k, v in d.items():
            if remove_attribute and k == "attributes":
                continue
            if isinstance(v, dict) and len(v) == 1:
                if "string" in v:
                    new_dict[k] = v["string"]
                elif "map" in v:
                    new_dict[k] = v["map"]
                elif "array" in v:
                    new_dict[k] = simplify_dict(v["array"])
                else:
                    new_dict[k] = simplify_dict(v)
            else:
                new_dict[k] = simplify_dict(v)
        return new_dict
    elif isinstance(d, list):
        return [simplify_dict(x) for x in d]
    else:
        return d


def find_concept_mention_token_offsets(sentence, concept_mention):
    arg_char_start = concept_mention["span"]["start"]
    arg_char_end = concept_mention["span"]["end"]
    arg_start = -1
    arg_end = -1
    for idx, token in enumerate(sentence["tokens"]):
        if token["span"]["start"] == arg_char_start:
            arg_start = idx
        if token["span"]["end"] == arg_char_end:
            arg_end = idx+1
    assert arg_start != -1 and arg_end != -1, f"Could not find token offsets for {concept_mention['id']}"
    return arg_start, arg_end


def fix_doc(doc):
    """Fix document with faulty spans. REMOVE IF FIXED IN DATASET!"""
    if doc["id"] == "1111185208647274501":
        offset = 0
        # Fix token spans
        tokens = doc["tokens"]["array"]
        for idx, token in enumerate(tokens):
            if idx == 6:
                offset += 1
            token["span"]["start"] -= offset
            if idx == 3:
                offset += 1
            token["span"]["end"] -= offset
        # Fix concept mentions and relation mentions
        offset = 0
        concept_mentions = doc["conceptMentions"]["array"]
        for idx, cm in enumerate(concept_mentions):
            if idx == 1 or idx == 2:
                offset += 1
            cm["span"]["start"] -= offset
            cm["span"]["end"] -= offset
        rm = doc["relationMentions"]["array"][0]
        rm["span"]["start"] -= 1
        rm["span"]["end"] -= 2
        rm["args"]["array"][0]["conceptMention"]["span"]["start"] -= 1
        rm["args"]["array"][0]["conceptMention"]["span"]["end"] -= 1
        rm["args"]["array"][1]["conceptMention"]["span"]["start"] -= 2
        rm["args"]["array"][1]["conceptMention"]["span"]["end"] -= 2

        doc["tokens"]["array"] = tokens
        doc["sentences"]["array"][0]["span"]["end"] -= 2
        doc["sentences"]["array"][0]["tokens"]["array"] = tokens[:20]
        doc["sentences"]["array"][0]["conceptMentions"]["array"] = concept_mentions[:-1]
        doc["sentences"]["array"][0]["relationMentions"]["array"] = [rm]
        doc["sentences"]["array"][1]["span"]["start"] -= 2
        doc["sentences"]["array"][1]["span"]["end"] -= 2
        doc["sentences"]["array"][1]["tokens"]["array"] = tokens[20:]
        doc["sentences"]["array"][1]["conceptMentions"]["array"] = [concept_mentions[-1]]
        print("Fixed spans")
    return doc


class Mobie(datasets.GeneratorBasedBuilder):
    """MobIE is a German-language dataset which is human-annotated with 20 coarse- and fine-grained entity types and entity linking information for geographically linkable entities"""

    VERSION = datasets.Version("1.1.0")

    # This is an example of a dataset with multiple configurations.
    # If you don't want/need to define several sub-sets in your dataset,
    # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

    # If you need to make complex sub-parts in the datasets with configurable options
    # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
    # BUILDER_CONFIG_CLASS = MyBuilderConfig

    # You will be able to load one or the other configurations in the following list with
    # data = datasets.load_dataset('my_dataset', 'first_domain')
    # data = datasets.load_dataset('my_dataset', 'second_domain')
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="ner", version=VERSION, description="MobIE V1 NER"),
        datasets.BuilderConfig(name="el", version=VERSION, description="MobIE V1 Entity Linking"),
        datasets.BuilderConfig(name="re", version=VERSION, description="MobIE V1 Relation Extraction"),
        datasets.BuilderConfig(name="ee", version=VERSION, description="MobIE V1 Event Extraction"),
    ]
    DEFAULT_CONFIG_NAME = "ner"

    def _info(self):
        labels = [
            "date",
            "disaster-type",
            "distance",
            "duration",
            "event-cause",
            "location",
            "location-city",
            "location-route",
            "location-stop",
            "location-street",
            "money",
            "number",
            "organization",
            "organization-company",
            "org-position",
            "percent",
            "person",
            "set",
            "time",
            "trigger",
        ]
        event_types = [
            "O", "Accident", "CanceledRoute", "CanceledStop", "Delay", "Obstruction",
            "RailReplacementService", "TrafficJam"
        ]
        event_roles = [
            "no_arg", "trigger", "location", "delay", "direction", "start_loc", "end_loc",
            "start_date", "end_date", "cause", "jam_length", "route"
        ]
        entity_mentions = [
            {
                "text": datasets.Value("string"),
                "start": datasets.Value("int32"),
                "end": datasets.Value("int32"),
                "char_start": datasets.Value("int32"),
                "char_end": datasets.Value("int32"),
                "type": datasets.features.ClassLabel(names=["O"]+labels),
                "entity_id": datasets.Value("string"),
                "refids": [
                    {
                        "key": datasets.Value("string"),
                        "value": datasets.Value("string")
                    }
                ]
            }
        ]
        prefixes = ["B", "I"]
        ner_tags = ["O"] + [f"{prefix}-{label}" for prefix in prefixes for label in labels]
        if self.config.name == "ner":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "ner_tags": datasets.Sequence(
                        datasets.features.ClassLabel(
                            names=ner_tags
                        )
                    ),
                }
            )
        elif self.config.name == "el":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "entity_mentions": entity_mentions
                }
            )
        elif self.config.name == "re":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "entities": datasets.Sequence([datasets.Value("int32")]),
                    "entity_roles": datasets.Sequence(datasets.features.ClassLabel(
                        names=event_roles
                    )),
                    "entity_types": datasets.Sequence(datasets.features.ClassLabel(
                        names=["O"] + labels
                    )),
                    "event_type": datasets.features.ClassLabel(
                        names=event_types
                    ),
                    "entity_ids": datasets.Sequence(datasets.Value("string"))
                }
            )
        elif self.config.name == "ee":
            # Inspired by https://github.com/nlpcl-lab/ace2005-preprocessing?tab=readme-ov-file#format
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "text": datasets.Value("string"),
                    "entity_mentions": entity_mentions,
                    "event_mentions": [
                        {
                            "id": datasets.Value("string"),
                            "trigger": {
                                "text": datasets.Value("string"),
                                "start": datasets.Value("int32"),
                                "end": datasets.Value("int32"),
                                "char_start": datasets.Value("int32"),
                                "char_end": datasets.Value("int32")
                            },
                            "arguments": [{
                                "text": datasets.Value("string"),
                                "start": datasets.Value("int32"),
                                "end": datasets.Value("int32"),
                                "char_start": datasets.Value("int32"),
                                "char_end": datasets.Value("int32"),
                                "role": datasets.features.ClassLabel(
                                    names=event_roles
                                ),
                                "type": datasets.features.ClassLabel(
                                    names=["O"] + labels
                                )
                            }],
                            "event_type": datasets.features.ClassLabel(
                                names=event_types
                            ),
                        }
                    ],
                    "tokens": datasets.Sequence(datasets.Value("string")),
                    "pos_tags": datasets.Sequence(datasets.Value("string")),
                    "lemma": datasets.Sequence(datasets.Value("string")),
                    "ner_tags": datasets.Sequence(datasets.features.ClassLabel(names=ner_tags))
                }
            )
        else:
            raise ValueError("Invalid configuration name")

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""

        # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
        # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
        # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
        data_dir = dl_manager.download_and_extract(_URLs)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={"filepath": data_dir["train"], "split": "train"},
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={"filepath": data_dir["test"], "split": "test"},
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={"filepath": data_dir["dev"], "split": "dev"},
            ),
        ]

    def _generate_examples(self, filepath, split, sentence_level=False):
        """Yields examples."""

        if self.config.name == "ner":
            NOT_WHITESPACE = re.compile(r"[^\s]")

            def decode_stacked(document, pos=0, decoder=JSONDecoder()):
                while True:
                    match = NOT_WHITESPACE.search(document, pos)
                    if not match:
                        return
                    pos = match.start()
                    try:
                        obj, pos = decoder.raw_decode(document, pos)
                    except JSONDecodeError:
                        raise
                    yield obj

            with open(filepath, encoding="utf-8") as f:
                raw = f.read()

            for doc in decode_stacked(raw):
                if doc["id"] == "1111185208647274501":
                    doc = fix_doc(doc)
                text = doc["text"]["string"]
                iterable = doc["sentences"]["array"] if sentence_level else [doc]
                for s in iterable:
                    toks = []
                    lbls = []
                    sid = s["id"]
                    for x in s["tokens"]["array"]:
                        toks.append(text[x["span"]["start"]: x["span"]["end"]])
                        lbls.append(x["ner"]["string"])

                    yield sid, {
                        "id": sid,
                        "tokens": toks,
                        "ner_tags": lbls,
                    }
        else:
            example_idx = 0
            with open(filepath, encoding="utf-8") as f:
                for line in f:
                    doc = json.loads(line)
                    if doc["id"] == "1111185208647274501":
                        doc = fix_doc(doc)
                    doc = simplify_dict(doc)
                    text = doc["text"]
                    iterable = doc["sentences"] if sentence_level else [doc]
                    for sentence in iterable:
                        sentence_id = sentence["id"]
                        sentence_start = sentence["span"]["start"] if "span" in sentence else 0
                        mobie_cms = sentence["conceptMentions"]
                        entity_mentions = []
                        for cm in mobie_cms:
                            char_start = cm["span"]["start"]
                            char_end = cm["span"]["end"]
                            # Find token offsets for entity mentions
                            start, end = find_concept_mention_token_offsets(sentence, cm)
                            cm_text = text[char_start:char_end]
                            entity_id = "NIL"
                            for refid in cm["refids"]:
                                if refid["key"] == "osm_id":
                                    entity_id = refid["value"]
                                    break
                            entity_mentions.append({
                                "text": cm_text,
                                "start": start,
                                "end": end,
                                "char_start": char_start - sentence_start,
                                "char_end": char_end - sentence_start,
                                "type": cm["type"],
                                "entity_id": entity_id,
                                "refids": [
                                    {
                                        "key": refid["key"], 
                                        "value": refid["value"]
                                    } for refid in cm["refids"]
                                ] if "refids" in cm and cm["refids"] else []
                            })
                        tokens = []
                        lemmas = []
                        ner_tags = []
                        pos_tags = []
                        for token in sentence["tokens"]:
                            token_text = text[token["span"]["start"]:token["span"]["end"]]
                            tokens.append(token_text)
                            lemmas.append(token["lemma"])
                            ner_tags.append(token["ner"])
                            pos_tags.append(token["posTag"])
                        if self.config.name == "el":
                            yield sentence_id, {
                                "id": sentence_id,
                                "text": text,
                                "tokens": tokens,
                                "entity_mentions": entity_mentions
                            }
                        elif self.config.name == "re":
                            mobie_rms = sentence["relationMentions"]
                            if not mobie_rms:
                                continue
                            entities = []
                            entity_types = []
                            entity_ids = []
                            for cm in entity_mentions:
                                entities.append([cm["start"], cm["end"]])
                                entity_types.append(cm["type"])
                                entity_ids.append(cm["entity_id"])
                            for rm in mobie_rms:
                                entity_roles = ["no_arg"] * len(entities)
                                for arg in rm["args"]:
                                    entity_role = arg["role"]
                                    # Matching via ids does not work, need to match via positions
                                    cm = arg["conceptMention"]
                                    start, end = find_concept_mention_token_offsets(sentence, cm)
                                    entity_idx = -1
                                    for idx, entity in enumerate(entities):
                                        if entity == [start, end]:
                                            entity_idx = idx
                                            break
                                    assert entity_idx != -1, f"Could not find entity for {cm['id']}"
                                    entity_roles[entity_idx] = entity_role
                                yield f"{sentence_id}_{example_idx}", {
                                    "id": f"{sentence_id}_{example_idx}",
                                    "tokens": tokens,
                                    "entities": entities,
                                    "entity_roles": entity_roles,
                                    "entity_types": entity_types,
                                    "event_type": rm["name"],
                                    "entity_ids": entity_ids
                                }
                                example_idx += 1
                        elif self.config.name == "ee":
                            mobie_rms = sentence["relationMentions"]
                            if not mobie_rms:
                                continue
                            event_mentions = []
                            for rm in mobie_rms:
                                # Find trigger in rm["args"]
                                trigger = None
                                for arg in rm["args"]:
                                    if arg["role"] == "trigger":
                                        trigger = arg
                                        break
                                if trigger is None:
                                    continue
                                trigger_char_start = trigger["conceptMention"]["span"]["start"]
                                trigger_char_end = trigger["conceptMention"]["span"]["end"]
                                trigger_start, trigger_end = find_concept_mention_token_offsets(sentence, trigger["conceptMention"])
                                trigger_text = text[trigger_char_start:trigger_char_end]
                                args = []
                                for arg in rm["args"]:
                                    if arg["role"] == "trigger":
                                        continue
                                    arg_char_start = arg["conceptMention"]["span"]["start"]
                                    arg_char_end = arg["conceptMention"]["span"]["end"]
                                    arg_start = -1
                                    arg_end = -1
                                    for idx, token in enumerate(sentence["tokens"]):
                                        if token["span"]["start"] == arg_char_start:
                                            arg_start = idx
                                        if token["span"]["end"] == arg_char_end:
                                            arg_end = idx+1
                                    assert arg_start != -1 and arg_end != -1, f"Could not find token offsets for {arg['conceptMention']['id']}"
                                    arg_text = text[arg_char_start:arg_char_end]
                                    args.append({
                                        "text": arg_text,
                                        "start": arg_start,
                                        "end": arg_end,
                                        "char_start": arg_char_start - sentence_start,
                                        "char_end": arg_char_end - sentence_start,
                                        "role": arg["role"],
                                        "type": arg["conceptMention"]["type"]
                                    })
                                event_mentions.append({
                                    "id": rm["id"],
                                    "trigger": {
                                        "text": trigger_text,
                                        "start": trigger_start,
                                        "end": trigger_end,
                                        "char_start": trigger_char_start - sentence_start,
                                        "char_end": trigger_char_end - sentence_start
                                    },
                                    "arguments": args,
                                    "event_type": rm["name"]
                                })
                            yield sentence_id, {
                                "id": sentence_id,
                                "text": text,
                                "entity_mentions": entity_mentions,
                                "event_mentions": event_mentions,
                                "tokens": tokens,
                                "pos_tags": pos_tags,
                                "lemma": lemmas,
                                "ner_tags": ner_tags
                            }
                        else:
                            raise ValueError("Invalid configuration name")