phucdev commited on
Commit
15676c8
1 Parent(s): f28bfbf

Change re config to match format described in notion notebook and add option to process on document level

Browse files
Files changed (1) hide show
  1. mobie.py +87 -87
mobie.py CHANGED
@@ -53,6 +53,7 @@ _URLs = {
53
 
54
 
55
  def simplify_dict(d, remove_attribute=True):
 
56
  if isinstance(d, dict):
57
  new_dict = {}
58
  for k, v in d.items():
@@ -123,7 +124,7 @@ class Mobie(datasets.GeneratorBasedBuilder):
123
  "time",
124
  "trigger",
125
  ]
126
- concept_mentions = [
127
  {
128
  "id": datasets.Value("string"),
129
  "text": datasets.Value("string"),
@@ -158,44 +159,31 @@ class Mobie(datasets.GeneratorBasedBuilder):
158
  {
159
  "id": datasets.Value("string"),
160
  "text": datasets.Value("string"),
161
- "concept_mentions": concept_mentions
162
  }
163
  )
164
  elif self.config.name == "re":
165
  features = datasets.Features(
166
  {
167
  "id": datasets.Value("string"),
168
- "text": datasets.Value("string"),
169
- "concept_mentions": concept_mentions,
170
- "relation_mentions": [
171
- {
172
- "id": datasets.Value("string"),
173
- "trigger": {
174
- "id": datasets.Value("string"),
175
- "text": datasets.Value("string"),
176
- "start": datasets.Value("int32"),
177
- "end": datasets.Value("int32")
178
- },
179
- "argument": {
180
- "id": datasets.Value("string"),
181
- "text": datasets.Value("string"),
182
- "start": datasets.Value("int32"),
183
- "end": datasets.Value("int32")
184
- },
185
- "type": datasets.features.ClassLabel(
186
- names=[
187
- "no_arg", "location", "delay", "direction", "start_loc", "end_loc",
188
- "start_date", "end_date", "cause", "jam_length", "route"
189
- ]
190
- ),
191
- "event_type": datasets.features.ClassLabel(
192
- names=[
193
- "O", "Accident", "CanceledRoute", "CanceledStop", "Delay", "Obstruction",
194
- "RailReplacementService", "TrafficJam"
195
- ]
196
- )
197
- }
198
- ]
199
  }
200
  )
201
  elif self.config.name == "ee":
@@ -204,7 +192,7 @@ class Mobie(datasets.GeneratorBasedBuilder):
204
  {
205
  "id": datasets.Value("string"),
206
  "text": datasets.Value("string"),
207
- "entity_mentions": concept_mentions,
208
  "event_mentions": [
209
  {
210
  "id": datasets.Value("string"),
@@ -284,7 +272,7 @@ class Mobie(datasets.GeneratorBasedBuilder):
284
  ),
285
  ]
286
 
287
- def _generate_examples(self, filepath, split):
288
  """Yields examples."""
289
 
290
  if self.config.name == "ner":
@@ -307,11 +295,8 @@ class Mobie(datasets.GeneratorBasedBuilder):
307
 
308
  for doc in decode_stacked(raw):
309
  text = doc["text"]["string"]
310
-
311
- # entity_starts = []
312
- # for m in doc["conceptMentions"]["array"]:
313
- # entity_starts.append(m["span"]["start"])
314
- for s in doc["sentences"]["array"]:
315
  toks = []
316
  lbls = []
317
  sid = s["id"]
@@ -331,16 +316,17 @@ class Mobie(datasets.GeneratorBasedBuilder):
331
  doc = json.loads(line)
332
  doc = simplify_dict(doc)
333
  text = doc["text"]
334
- for sentence in doc["sentences"]:
 
335
  sentence_id = sentence["id"]
336
- sentence_start = sentence["span"]["start"]
337
  mobie_cms = sentence["conceptMentions"]
338
- concept_mentions = []
339
  for cm in mobie_cms:
340
  cm_start = cm["span"]["start"]
341
  cm_end = cm["span"]["end"]
342
  cm_text = text[cm_start:cm_end]
343
- concept_mentions.append({
344
  "id": cm["id"],
345
  "text": cm_text,
346
  "start": cm_start - sentence_start,
@@ -354,58 +340,72 @@ class Mobie(datasets.GeneratorBasedBuilder):
354
  ] if "refids" in cm and cm["refids"] else []
355
  })
356
  if self.config.name == "el":
 
357
  yield sentence_id, {
358
  "id": sentence_id,
359
  "text": text,
360
- "concept_mentions": concept_mentions
361
  }
362
  elif self.config.name == "re":
363
  mobie_rms = sentence["relationMentions"]
364
  if not mobie_rms:
365
  continue
366
- relation_mentions = []
367
- for rm in mobie_rms:
368
- # Find trigger in rm["args"]
369
- trigger = None
370
- for arg in rm["args"]:
371
- if arg["role"] == "trigger":
372
- trigger = arg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  break
374
- if trigger is None:
375
- continue
376
- trigger_start = trigger["conceptMention"]["span"]["start"]
377
- trigger_end = trigger["conceptMention"]["span"]["end"]
378
- trigger_text = text[trigger_start:trigger_end]
379
  for arg in rm["args"]:
380
- if arg["role"] == "trigger":
381
- continue
382
- argument_start = arg["conceptMention"]["span"]["start"]
383
- argument_end = arg["conceptMention"]["span"]["end"]
384
- argument_text = text[argument_start:argument_end]
385
- relation_mentions.append({
386
- "id": f"{sentence_id}-{example_idx}",
387
- "trigger": {
388
- "id": trigger["conceptMention"]["id"],
389
- "text": trigger_text,
390
- "start": trigger_start - sentence_start,
391
- "end": trigger_end - sentence_start
392
- },
393
- "argument": {
394
- "id": arg["conceptMention"]["id"],
395
- "text": argument_text,
396
- "start": argument_start - sentence_start,
397
- "end": argument_end - sentence_start
398
- },
399
- "type": arg["role"],
400
- "event_type": rm["name"]
401
- })
402
- yield f"{sentence_id}_{example_idx}", {
403
- "id": f"{sentence_id}_{example_idx}",
404
- "text": text,
405
- "concept_mentions": concept_mentions,
406
- "relation_mentions": relation_mentions
407
- }
408
- example_idx += 1
409
  elif self.config.name == "ee":
410
  mobie_rms = sentence["relationMentions"]
411
  if not mobie_rms:
@@ -452,7 +452,7 @@ class Mobie(datasets.GeneratorBasedBuilder):
452
  yield sentence_id, {
453
  "id": sentence_id,
454
  "text": text,
455
- "entity_mentions": concept_mentions,
456
  "event_mentions": event_mentions
457
  }
458
  else:
 
53
 
54
 
55
  def simplify_dict(d, remove_attribute=True):
56
+ """Simplify nested dictionary by removing unnecessary keys"""
57
  if isinstance(d, dict):
58
  new_dict = {}
59
  for k, v in d.items():
 
124
  "time",
125
  "trigger",
126
  ]
127
+ entity_mentions = [
128
  {
129
  "id": datasets.Value("string"),
130
  "text": datasets.Value("string"),
 
159
  {
160
  "id": datasets.Value("string"),
161
  "text": datasets.Value("string"),
162
+ "entity_mentions": entity_mentions
163
  }
164
  )
165
  elif self.config.name == "re":
166
  features = datasets.Features(
167
  {
168
  "id": datasets.Value("string"),
169
+ "tokens": datasets.Sequence(datasets.Value("string")),
170
+ "entities": datasets.Sequence([datasets.Value("int32")]),
171
+ "entity_roles": datasets.Sequence(datasets.features.ClassLabel(
172
+ names=[
173
+ "no_arg", "trigger", "location", "delay", "direction", "start_loc", "end_loc",
174
+ "start_date", "end_date", "cause", "jam_length", "route"
175
+ ]
176
+ )),
177
+ "entity_types": datasets.Sequence(datasets.features.ClassLabel(
178
+ names=labels
179
+ )),
180
+ "event_type": datasets.features.ClassLabel(
181
+ names=[
182
+ "O", "Accident", "CanceledRoute", "CanceledStop", "Delay", "Obstruction",
183
+ "RailReplacementService", "TrafficJam"
184
+ ]
185
+ ),
186
+ "entity_ids": datasets.Sequence(datasets.Value("string"))
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  }
188
  )
189
  elif self.config.name == "ee":
 
192
  {
193
  "id": datasets.Value("string"),
194
  "text": datasets.Value("string"),
195
+ "entity_mentions": entity_mentions,
196
  "event_mentions": [
197
  {
198
  "id": datasets.Value("string"),
 
272
  ),
273
  ]
274
 
275
+ def _generate_examples(self, filepath, split, sentence_level=False):
276
  """Yields examples."""
277
 
278
  if self.config.name == "ner":
 
295
 
296
  for doc in decode_stacked(raw):
297
  text = doc["text"]["string"]
298
+ iterable = doc["sentences"]["array"] if sentence_level else [doc]
299
+ for s in iterable:
 
 
 
300
  toks = []
301
  lbls = []
302
  sid = s["id"]
 
316
  doc = json.loads(line)
317
  doc = simplify_dict(doc)
318
  text = doc["text"]
319
+ iterable = doc["sentences"] if sentence_level else [doc]
320
+ for sentence in iterable:
321
  sentence_id = sentence["id"]
322
+ sentence_start = sentence["span"]["start"] if "span" in sentence else 0
323
  mobie_cms = sentence["conceptMentions"]
324
+ entity_mentions = []
325
  for cm in mobie_cms:
326
  cm_start = cm["span"]["start"]
327
  cm_end = cm["span"]["end"]
328
  cm_text = text[cm_start:cm_end]
329
+ entity_mentions.append({
330
  "id": cm["id"],
331
  "text": cm_text,
332
  "start": cm_start - sentence_start,
 
340
  ] if "refids" in cm and cm["refids"] else []
341
  })
342
  if self.config.name == "el":
343
+ # TODO use osm_id as entity id?
344
  yield sentence_id, {
345
  "id": sentence_id,
346
  "text": text,
347
+ "entity_mentions": entity_mentions
348
  }
349
  elif self.config.name == "re":
350
  mobie_rms = sentence["relationMentions"]
351
  if not mobie_rms:
352
  continue
353
+ tokens = [text[token["span"]["start"]:token["span"]["end"]] for token in sentence["tokens"]]
354
+ entities = []
355
+ entity_types = []
356
+ entity_ids = []
357
+ for cm in mobie_cms:
358
+ # Find token offsets for entity mentions
359
+ start = -1
360
+ end = -1
361
+ for idx, token in enumerate(sentence["tokens"]):
362
+ if token["span"]["start"] == cm["span"]["start"]:
363
+ start = idx
364
+ if token["span"]["end"] == cm["span"]["end"]:
365
+ end = idx
366
+ assert start != -1 and end != -1, f"Could not find token offsets for {cm['id']}"
367
+ entities.append([start, end])
368
+ entity_types.append(cm["type"])
369
+ found_osm_id = False
370
+ for refid in cm["refids"]:
371
+ if refid["key"] == "osm_id":
372
+ entity_ids.append(refid["value"])
373
+ found_osm_id = True
374
  break
375
+ if not found_osm_id:
376
+ entity_ids.append("NIL")
377
+ for rm in mobie_rms:
378
+ entity_roles = ["no_arg"] * len(entities)
 
379
  for arg in rm["args"]:
380
+ entity_role = arg["role"]
381
+ # Matching via ids does not work, need to match via position
382
+ # Find token offsets for entity mentions
383
+ start = -1
384
+ end = -1
385
+ cm = arg["conceptMention"]
386
+ for idx, token in enumerate(sentence["tokens"]):
387
+ if token["span"]["start"] == cm["span"]["start"]:
388
+ start = idx
389
+ if token["span"]["end"] == cm["span"]["end"]:
390
+ end = idx
391
+ assert start != -1 and end != -1, f"Could not find token offsets for {cm['id']}"
392
+ entity_idx = -1
393
+ for idx, entity in enumerate(entities):
394
+ if entity == [start, end]:
395
+ entity_idx = idx
396
+ break
397
+ assert entity_idx != -1, f"Could not find entity for {cm['id']}"
398
+ entity_roles[entity_idx] = entity_role
399
+ yield f"{sentence_id}_{example_idx}", {
400
+ "id": f"{sentence_id}_{example_idx}",
401
+ "tokens": tokens,
402
+ "entities": entities,
403
+ "entity_roles": entity_roles,
404
+ "entity_types": entity_types,
405
+ "event_type": rm["name"],
406
+ "entity_ids": entity_ids
407
+ }
408
+ example_idx += 1
409
  elif self.config.name == "ee":
410
  mobie_rms = sentence["relationMentions"]
411
  if not mobie_rms:
 
452
  yield sentence_id, {
453
  "id": sentence_id,
454
  "text": text,
455
+ "entity_mentions": entity_mentions,
456
  "event_mentions": event_mentions
457
  }
458
  else: