Update ppr based on git version d04fce3
Browse files- README.md +43 -0
- bigbiohub.py +592 -0
- ppr.py +391 -0
README.md
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
---
|
3 |
+
language:
|
4 |
+
- en
|
5 |
+
bigbio_language:
|
6 |
+
- English
|
7 |
+
license: unknown
|
8 |
+
multilinguality: monolingual
|
9 |
+
bigbio_license_shortname: UNKNOWN
|
10 |
+
pretty_name: PPR
|
11 |
+
homepage: https://github.com/DMCB-GIST/PPRcorpus
|
12 |
+
bigbio_pubmed: True
|
13 |
+
bigbio_public: True
|
14 |
+
bigbio_tasks:
|
15 |
+
- NAMED_ENTITY_RECOGNITION
|
16 |
+
- RELATION_EXTRACTION
|
17 |
+
---
|
18 |
+
|
19 |
+
|
20 |
+
# Dataset Card for PPR
|
21 |
+
|
22 |
+
## Dataset Description
|
23 |
+
|
24 |
+
- **Homepage:** https://github.com/DMCB-GIST/PPRcorpus
|
25 |
+
- **Pubmed:** True
|
26 |
+
- **Public:** True
|
27 |
+
- **Tasks:** NER,RE
|
28 |
+
|
29 |
+
The Plant-Phenotype corpus is a text corpus with human annotations of plants, phenotypes, and their relations on a corpus in 600 PubMed abstracts.
|
30 |
+
|
31 |
+
## Citation Information
|
32 |
+
|
33 |
+
```
|
34 |
+
@article{cho2022plant,
|
35 |
+
author = {Cho, Hyejin and Kim, Baeksoo and Choi, Wonjun and Lee, Doheon and Lee, Hyunju},
|
36 |
+
title = {Plant phenotype relationship corpus for biomedical relationships between plants and phenotypes},
|
37 |
+
journal = {Scientific Data},
|
38 |
+
volume = {9},
|
39 |
+
year = {2022},
|
40 |
+
publisher = {Nature Publishing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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import defaultdict
|
2 |
+
from dataclasses import dataclass
|
3 |
+
from enum import Enum
|
4 |
+
import logging
|
5 |
+
from pathlib import Path
|
6 |
+
from types import SimpleNamespace
|
7 |
+
from typing import TYPE_CHECKING, Dict, Iterable, List, Tuple
|
8 |
+
|
9 |
+
import datasets
|
10 |
+
|
11 |
+
if TYPE_CHECKING:
|
12 |
+
import bioc
|
13 |
+
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
|
17 |
+
BigBioValues = SimpleNamespace(NULL="<BB_NULL_STR>")
|
18 |
+
|
19 |
+
|
20 |
+
@dataclass
|
21 |
+
class BigBioConfig(datasets.BuilderConfig):
|
22 |
+
"""BuilderConfig for BigBio."""
|
23 |
+
|
24 |
+
name: str = None
|
25 |
+
version: datasets.Version = None
|
26 |
+
description: str = None
|
27 |
+
schema: str = None
|
28 |
+
subset_id: str = None
|
29 |
+
|
30 |
+
|
31 |
+
class Tasks(Enum):
|
32 |
+
NAMED_ENTITY_RECOGNITION = "NER"
|
33 |
+
NAMED_ENTITY_DISAMBIGUATION = "NED"
|
34 |
+
EVENT_EXTRACTION = "EE"
|
35 |
+
RELATION_EXTRACTION = "RE"
|
36 |
+
COREFERENCE_RESOLUTION = "COREF"
|
37 |
+
QUESTION_ANSWERING = "QA"
|
38 |
+
TEXTUAL_ENTAILMENT = "TE"
|
39 |
+
SEMANTIC_SIMILARITY = "STS"
|
40 |
+
TEXT_PAIRS_CLASSIFICATION = "TXT2CLASS"
|
41 |
+
PARAPHRASING = "PARA"
|
42 |
+
TRANSLATION = "TRANSL"
|
43 |
+
SUMMARIZATION = "SUM"
|
44 |
+
TEXT_CLASSIFICATION = "TXTCLASS"
|
45 |
+
|
46 |
+
|
47 |
+
entailment_features = datasets.Features(
|
48 |
+
{
|
49 |
+
"id": datasets.Value("string"),
|
50 |
+
"premise": datasets.Value("string"),
|
51 |
+
"hypothesis": datasets.Value("string"),
|
52 |
+
"label": datasets.Value("string"),
|
53 |
+
}
|
54 |
+
)
|
55 |
+
|
56 |
+
pairs_features = datasets.Features(
|
57 |
+
{
|
58 |
+
"id": datasets.Value("string"),
|
59 |
+
"document_id": datasets.Value("string"),
|
60 |
+
"text_1": datasets.Value("string"),
|
61 |
+
"text_2": datasets.Value("string"),
|
62 |
+
"label": datasets.Value("string"),
|
63 |
+
}
|
64 |
+
)
|
65 |
+
|
66 |
+
qa_features = datasets.Features(
|
67 |
+
{
|
68 |
+
"id": datasets.Value("string"),
|
69 |
+
"question_id": datasets.Value("string"),
|
70 |
+
"document_id": datasets.Value("string"),
|
71 |
+
"question": datasets.Value("string"),
|
72 |
+
"type": datasets.Value("string"),
|
73 |
+
"choices": [datasets.Value("string")],
|
74 |
+
"context": datasets.Value("string"),
|
75 |
+
"answer": datasets.Sequence(datasets.Value("string")),
|
76 |
+
}
|
77 |
+
)
|
78 |
+
|
79 |
+
text_features = datasets.Features(
|
80 |
+
{
|
81 |
+
"id": datasets.Value("string"),
|
82 |
+
"document_id": datasets.Value("string"),
|
83 |
+
"text": datasets.Value("string"),
|
84 |
+
"labels": [datasets.Value("string")],
|
85 |
+
}
|
86 |
+
)
|
87 |
+
|
88 |
+
text2text_features = datasets.Features(
|
89 |
+
{
|
90 |
+
"id": datasets.Value("string"),
|
91 |
+
"document_id": datasets.Value("string"),
|
92 |
+
"text_1": datasets.Value("string"),
|
93 |
+
"text_2": datasets.Value("string"),
|
94 |
+
"text_1_name": datasets.Value("string"),
|
95 |
+
"text_2_name": datasets.Value("string"),
|
96 |
+
}
|
97 |
+
)
|
98 |
+
|
99 |
+
kb_features = datasets.Features(
|
100 |
+
{
|
101 |
+
"id": datasets.Value("string"),
|
102 |
+
"document_id": datasets.Value("string"),
|
103 |
+
"passages": [
|
104 |
+
{
|
105 |
+
"id": datasets.Value("string"),
|
106 |
+
"type": datasets.Value("string"),
|
107 |
+
"text": datasets.Sequence(datasets.Value("string")),
|
108 |
+
"offsets": datasets.Sequence([datasets.Value("int32")]),
|
109 |
+
}
|
110 |
+
],
|
111 |
+
"entities": [
|
112 |
+
{
|
113 |
+
"id": datasets.Value("string"),
|
114 |
+
"type": datasets.Value("string"),
|
115 |
+
"text": datasets.Sequence(datasets.Value("string")),
|
116 |
+
"offsets": datasets.Sequence([datasets.Value("int32")]),
|
117 |
+
"normalized": [
|
118 |
+
{
|
119 |
+
"db_name": datasets.Value("string"),
|
120 |
+
"db_id": datasets.Value("string"),
|
121 |
+
}
|
122 |
+
],
|
123 |
+
}
|
124 |
+
],
|
125 |
+
"events": [
|
126 |
+
{
|
127 |
+
"id": datasets.Value("string"),
|
128 |
+
"type": datasets.Value("string"),
|
129 |
+
# refers to the text_bound_annotation of the trigger
|
130 |
+
"trigger": {
|
131 |
+
"text": datasets.Sequence(datasets.Value("string")),
|
132 |
+
"offsets": datasets.Sequence([datasets.Value("int32")]),
|
133 |
+
},
|
134 |
+
"arguments": [
|
135 |
+
{
|
136 |
+
"role": datasets.Value("string"),
|
137 |
+
"ref_id": datasets.Value("string"),
|
138 |
+
}
|
139 |
+
],
|
140 |
+
}
|
141 |
+
],
|
142 |
+
"coreferences": [
|
143 |
+
{
|
144 |
+
"id": datasets.Value("string"),
|
145 |
+
"entity_ids": datasets.Sequence(datasets.Value("string")),
|
146 |
+
}
|
147 |
+
],
|
148 |
+
"relations": [
|
149 |
+
{
|
150 |
+
"id": datasets.Value("string"),
|
151 |
+
"type": datasets.Value("string"),
|
152 |
+
"arg1_id": datasets.Value("string"),
|
153 |
+
"arg2_id": datasets.Value("string"),
|
154 |
+
"normalized": [
|
155 |
+
{
|
156 |
+
"db_name": datasets.Value("string"),
|
157 |
+
"db_id": datasets.Value("string"),
|
158 |
+
}
|
159 |
+
],
|
160 |
+
}
|
161 |
+
],
|
162 |
+
}
|
163 |
+
)
|
164 |
+
|
165 |
+
|
166 |
+
TASK_TO_SCHEMA = {
|
167 |
+
Tasks.NAMED_ENTITY_RECOGNITION.name: "KB",
|
168 |
+
Tasks.NAMED_ENTITY_DISAMBIGUATION.name: "KB",
|
169 |
+
Tasks.EVENT_EXTRACTION.name: "KB",
|
170 |
+
Tasks.RELATION_EXTRACTION.name: "KB",
|
171 |
+
Tasks.COREFERENCE_RESOLUTION.name: "KB",
|
172 |
+
Tasks.QUESTION_ANSWERING.name: "QA",
|
173 |
+
Tasks.TEXTUAL_ENTAILMENT.name: "TE",
|
174 |
+
Tasks.SEMANTIC_SIMILARITY.name: "PAIRS",
|
175 |
+
Tasks.TEXT_PAIRS_CLASSIFICATION.name: "PAIRS",
|
176 |
+
Tasks.PARAPHRASING.name: "T2T",
|
177 |
+
Tasks.TRANSLATION.name: "T2T",
|
178 |
+
Tasks.SUMMARIZATION.name: "T2T",
|
179 |
+
Tasks.TEXT_CLASSIFICATION.name: "TEXT",
|
180 |
+
}
|
181 |
+
|
182 |
+
SCHEMA_TO_TASKS = defaultdict(set)
|
183 |
+
for task, schema in TASK_TO_SCHEMA.items():
|
184 |
+
SCHEMA_TO_TASKS[schema].add(task)
|
185 |
+
SCHEMA_TO_TASKS = dict(SCHEMA_TO_TASKS)
|
186 |
+
|
187 |
+
VALID_TASKS = set(TASK_TO_SCHEMA.keys())
|
188 |
+
VALID_SCHEMAS = set(TASK_TO_SCHEMA.values())
|
189 |
+
|
190 |
+
SCHEMA_TO_FEATURES = {
|
191 |
+
"KB": kb_features,
|
192 |
+
"QA": qa_features,
|
193 |
+
"TE": entailment_features,
|
194 |
+
"T2T": text2text_features,
|
195 |
+
"TEXT": text_features,
|
196 |
+
"PAIRS": pairs_features,
|
197 |
+
}
|
198 |
+
|
199 |
+
|
200 |
+
def get_texts_and_offsets_from_bioc_ann(ann: "bioc.BioCAnnotation") -> Tuple:
|
201 |
+
|
202 |
+
offsets = [(loc.offset, loc.offset + loc.length) for loc in ann.locations]
|
203 |
+
|
204 |
+
text = ann.text
|
205 |
+
|
206 |
+
if len(offsets) > 1:
|
207 |
+
i = 0
|
208 |
+
texts = []
|
209 |
+
for start, end in offsets:
|
210 |
+
chunk_len = end - start
|
211 |
+
texts.append(text[i : chunk_len + i])
|
212 |
+
i += chunk_len
|
213 |
+
while i < len(text) and text[i] == " ":
|
214 |
+
i += 1
|
215 |
+
else:
|
216 |
+
texts = [text]
|
217 |
+
|
218 |
+
return offsets, texts
|
219 |
+
|
220 |
+
|
221 |
+
def remove_prefix(a: str, prefix: str) -> str:
|
222 |
+
if a.startswith(prefix):
|
223 |
+
a = a[len(prefix) :]
|
224 |
+
return a
|
225 |
+
|
226 |
+
|
227 |
+
def parse_brat_file(
|
228 |
+
txt_file: Path,
|
229 |
+
annotation_file_suffixes: List[str] = None,
|
230 |
+
parse_notes: bool = False,
|
231 |
+
) -> Dict:
|
232 |
+
"""
|
233 |
+
Parse a brat file into the schema defined below.
|
234 |
+
`txt_file` should be the path to the brat '.txt' file you want to parse, e.g. 'data/1234.txt'
|
235 |
+
Assumes that the annotations are contained in one or more of the corresponding '.a1', '.a2' or '.ann' files,
|
236 |
+
e.g. 'data/1234.ann' or 'data/1234.a1' and 'data/1234.a2'.
|
237 |
+
Will include annotator notes, when `parse_notes == True`.
|
238 |
+
brat_features = datasets.Features(
|
239 |
+
{
|
240 |
+
"id": datasets.Value("string"),
|
241 |
+
"document_id": datasets.Value("string"),
|
242 |
+
"text": datasets.Value("string"),
|
243 |
+
"text_bound_annotations": [ # T line in brat, e.g. type or event trigger
|
244 |
+
{
|
245 |
+
"offsets": datasets.Sequence([datasets.Value("int32")]),
|
246 |
+
"text": datasets.Sequence(datasets.Value("string")),
|
247 |
+
"type": datasets.Value("string"),
|
248 |
+
"id": datasets.Value("string"),
|
249 |
+
}
|
250 |
+
],
|
251 |
+
"events": [ # E line in brat
|
252 |
+
{
|
253 |
+
"trigger": datasets.Value(
|
254 |
+
"string"
|
255 |
+
), # refers to the text_bound_annotation of the trigger,
|
256 |
+
"id": datasets.Value("string"),
|
257 |
+
"type": datasets.Value("string"),
|
258 |
+
"arguments": datasets.Sequence(
|
259 |
+
{
|
260 |
+
"role": datasets.Value("string"),
|
261 |
+
"ref_id": datasets.Value("string"),
|
262 |
+
}
|
263 |
+
),
|
264 |
+
}
|
265 |
+
],
|
266 |
+
"relations": [ # R line in brat
|
267 |
+
{
|
268 |
+
"id": datasets.Value("string"),
|
269 |
+
"head": {
|
270 |
+
"ref_id": datasets.Value("string"),
|
271 |
+
"role": datasets.Value("string"),
|
272 |
+
},
|
273 |
+
"tail": {
|
274 |
+
"ref_id": datasets.Value("string"),
|
275 |
+
"role": datasets.Value("string"),
|
276 |
+
},
|
277 |
+
"type": datasets.Value("string"),
|
278 |
+
}
|
279 |
+
],
|
280 |
+
"equivalences": [ # Equiv line in brat
|
281 |
+
{
|
282 |
+
"id": datasets.Value("string"),
|
283 |
+
"ref_ids": datasets.Sequence(datasets.Value("string")),
|
284 |
+
}
|
285 |
+
],
|
286 |
+
"attributes": [ # M or A lines in brat
|
287 |
+
{
|
288 |
+
"id": datasets.Value("string"),
|
289 |
+
"type": datasets.Value("string"),
|
290 |
+
"ref_id": datasets.Value("string"),
|
291 |
+
"value": datasets.Value("string"),
|
292 |
+
}
|
293 |
+
],
|
294 |
+
"normalizations": [ # N lines in brat
|
295 |
+
{
|
296 |
+
"id": datasets.Value("string"),
|
297 |
+
"type": datasets.Value("string"),
|
298 |
+
"ref_id": datasets.Value("string"),
|
299 |
+
"resource_name": datasets.Value(
|
300 |
+
"string"
|
301 |
+
), # Name of the resource, e.g. "Wikipedia"
|
302 |
+
"cuid": datasets.Value(
|
303 |
+
"string"
|
304 |
+
), # ID in the resource, e.g. 534366
|
305 |
+
"text": datasets.Value(
|
306 |
+
"string"
|
307 |
+
), # Human readable description/name of the entity, e.g. "Barack Obama"
|
308 |
+
}
|
309 |
+
],
|
310 |
+
### OPTIONAL: Only included when `parse_notes == True`
|
311 |
+
"notes": [ # # lines in brat
|
312 |
+
{
|
313 |
+
"id": datasets.Value("string"),
|
314 |
+
"type": datasets.Value("string"),
|
315 |
+
"ref_id": datasets.Value("string"),
|
316 |
+
"text": datasets.Value("string"),
|
317 |
+
}
|
318 |
+
],
|
319 |
+
},
|
320 |
+
)
|
321 |
+
"""
|
322 |
+
|
323 |
+
example = {}
|
324 |
+
example["document_id"] = txt_file.with_suffix("").name
|
325 |
+
with txt_file.open() as f:
|
326 |
+
example["text"] = f.read()
|
327 |
+
|
328 |
+
# If no specific suffixes of the to-be-read annotation files are given - take standard suffixes
|
329 |
+
# for event extraction
|
330 |
+
if annotation_file_suffixes is None:
|
331 |
+
annotation_file_suffixes = [".a1", ".a2", ".ann"]
|
332 |
+
|
333 |
+
if len(annotation_file_suffixes) == 0:
|
334 |
+
raise AssertionError(
|
335 |
+
"At least one suffix for the to-be-read annotation files should be given!"
|
336 |
+
)
|
337 |
+
|
338 |
+
ann_lines = []
|
339 |
+
for suffix in annotation_file_suffixes:
|
340 |
+
annotation_file = txt_file.with_suffix(suffix)
|
341 |
+
try:
|
342 |
+
with annotation_file.open() as f:
|
343 |
+
ann_lines.extend(f.readlines())
|
344 |
+
except Exception:
|
345 |
+
continue
|
346 |
+
|
347 |
+
example["text_bound_annotations"] = []
|
348 |
+
example["events"] = []
|
349 |
+
example["relations"] = []
|
350 |
+
example["equivalences"] = []
|
351 |
+
example["attributes"] = []
|
352 |
+
example["normalizations"] = []
|
353 |
+
|
354 |
+
if parse_notes:
|
355 |
+
example["notes"] = []
|
356 |
+
|
357 |
+
for line in ann_lines:
|
358 |
+
line = line.strip()
|
359 |
+
if not line:
|
360 |
+
continue
|
361 |
+
|
362 |
+
if line.startswith("T"): # Text bound
|
363 |
+
ann = {}
|
364 |
+
fields = line.split("\t")
|
365 |
+
|
366 |
+
ann["id"] = fields[0]
|
367 |
+
ann["type"] = fields[1].split()[0]
|
368 |
+
ann["offsets"] = []
|
369 |
+
span_str = remove_prefix(fields[1], (ann["type"] + " "))
|
370 |
+
text = fields[2]
|
371 |
+
for span in span_str.split(";"):
|
372 |
+
start, end = span.split()
|
373 |
+
ann["offsets"].append([int(start), int(end)])
|
374 |
+
|
375 |
+
# Heuristically split text of discontiguous entities into chunks
|
376 |
+
ann["text"] = []
|
377 |
+
if len(ann["offsets"]) > 1:
|
378 |
+
i = 0
|
379 |
+
for start, end in ann["offsets"]:
|
380 |
+
chunk_len = end - start
|
381 |
+
ann["text"].append(text[i : chunk_len + i])
|
382 |
+
i += chunk_len
|
383 |
+
while i < len(text) and text[i] == " ":
|
384 |
+
i += 1
|
385 |
+
else:
|
386 |
+
ann["text"] = [text]
|
387 |
+
|
388 |
+
example["text_bound_annotations"].append(ann)
|
389 |
+
|
390 |
+
elif line.startswith("E"):
|
391 |
+
ann = {}
|
392 |
+
fields = line.split("\t")
|
393 |
+
|
394 |
+
ann["id"] = fields[0]
|
395 |
+
|
396 |
+
ann["type"], ann["trigger"] = fields[1].split()[0].split(":")
|
397 |
+
|
398 |
+
ann["arguments"] = []
|
399 |
+
for role_ref_id in fields[1].split()[1:]:
|
400 |
+
argument = {
|
401 |
+
"role": (role_ref_id.split(":"))[0],
|
402 |
+
"ref_id": (role_ref_id.split(":"))[1],
|
403 |
+
}
|
404 |
+
ann["arguments"].append(argument)
|
405 |
+
|
406 |
+
example["events"].append(ann)
|
407 |
+
|
408 |
+
elif line.startswith("R"):
|
409 |
+
ann = {}
|
410 |
+
fields = line.split("\t")
|
411 |
+
|
412 |
+
ann["id"] = fields[0]
|
413 |
+
ann["type"] = fields[1].split()[0]
|
414 |
+
|
415 |
+
ann["head"] = {
|
416 |
+
"role": fields[1].split()[1].split(":")[0],
|
417 |
+
"ref_id": fields[1].split()[1].split(":")[1],
|
418 |
+
}
|
419 |
+
ann["tail"] = {
|
420 |
+
"role": fields[1].split()[2].split(":")[0],
|
421 |
+
"ref_id": fields[1].split()[2].split(":")[1],
|
422 |
+
}
|
423 |
+
|
424 |
+
example["relations"].append(ann)
|
425 |
+
|
426 |
+
# '*' seems to be the legacy way to mark equivalences,
|
427 |
+
# but I couldn't find any info on the current way
|
428 |
+
# this might have to be adapted dependent on the brat version
|
429 |
+
# of the annotation
|
430 |
+
elif line.startswith("*"):
|
431 |
+
ann = {}
|
432 |
+
fields = line.split("\t")
|
433 |
+
|
434 |
+
ann["id"] = fields[0]
|
435 |
+
ann["ref_ids"] = fields[1].split()[1:]
|
436 |
+
|
437 |
+
example["equivalences"].append(ann)
|
438 |
+
|
439 |
+
elif line.startswith("A") or line.startswith("M"):
|
440 |
+
ann = {}
|
441 |
+
fields = line.split("\t")
|
442 |
+
|
443 |
+
ann["id"] = fields[0]
|
444 |
+
|
445 |
+
info = fields[1].split()
|
446 |
+
ann["type"] = info[0]
|
447 |
+
ann["ref_id"] = info[1]
|
448 |
+
|
449 |
+
if len(info) > 2:
|
450 |
+
ann["value"] = info[2]
|
451 |
+
else:
|
452 |
+
ann["value"] = ""
|
453 |
+
|
454 |
+
example["attributes"].append(ann)
|
455 |
+
|
456 |
+
elif line.startswith("N"):
|
457 |
+
ann = {}
|
458 |
+
fields = line.split("\t")
|
459 |
+
|
460 |
+
ann["id"] = fields[0]
|
461 |
+
ann["text"] = fields[2]
|
462 |
+
|
463 |
+
info = fields[1].split()
|
464 |
+
|
465 |
+
ann["type"] = info[0]
|
466 |
+
ann["ref_id"] = info[1]
|
467 |
+
ann["resource_name"] = info[2].split(":")[0]
|
468 |
+
ann["cuid"] = info[2].split(":")[1]
|
469 |
+
example["normalizations"].append(ann)
|
470 |
+
|
471 |
+
elif parse_notes and line.startswith("#"):
|
472 |
+
ann = {}
|
473 |
+
fields = line.split("\t")
|
474 |
+
|
475 |
+
ann["id"] = fields[0]
|
476 |
+
ann["text"] = fields[2] if len(fields) == 3 else BigBioValues.NULL
|
477 |
+
|
478 |
+
info = fields[1].split()
|
479 |
+
|
480 |
+
ann["type"] = info[0]
|
481 |
+
ann["ref_id"] = info[1]
|
482 |
+
example["notes"].append(ann)
|
483 |
+
|
484 |
+
return example
|
485 |
+
|
486 |
+
|
487 |
+
def brat_parse_to_bigbio_kb(brat_parse: Dict) -> Dict:
|
488 |
+
"""
|
489 |
+
Transform a brat parse (conforming to the standard brat schema) obtained with
|
490 |
+
`parse_brat_file` into a dictionary conforming to the `bigbio-kb` schema (as defined in ../schemas/kb.py)
|
491 |
+
:param brat_parse:
|
492 |
+
"""
|
493 |
+
|
494 |
+
unified_example = {}
|
495 |
+
|
496 |
+
# Prefix all ids with document id to ensure global uniqueness,
|
497 |
+
# because brat ids are only unique within their document
|
498 |
+
id_prefix = brat_parse["document_id"] + "_"
|
499 |
+
|
500 |
+
# identical
|
501 |
+
unified_example["document_id"] = brat_parse["document_id"]
|
502 |
+
unified_example["passages"] = [
|
503 |
+
{
|
504 |
+
"id": id_prefix + "_text",
|
505 |
+
"type": "abstract",
|
506 |
+
"text": [brat_parse["text"]],
|
507 |
+
"offsets": [[0, len(brat_parse["text"])]],
|
508 |
+
}
|
509 |
+
]
|
510 |
+
|
511 |
+
# get normalizations
|
512 |
+
ref_id_to_normalizations = defaultdict(list)
|
513 |
+
for normalization in brat_parse["normalizations"]:
|
514 |
+
ref_id_to_normalizations[normalization["ref_id"]].append(
|
515 |
+
{
|
516 |
+
"db_name": normalization["resource_name"],
|
517 |
+
"db_id": normalization["cuid"],
|
518 |
+
}
|
519 |
+
)
|
520 |
+
|
521 |
+
# separate entities and event triggers
|
522 |
+
unified_example["events"] = []
|
523 |
+
non_event_ann = brat_parse["text_bound_annotations"].copy()
|
524 |
+
for event in brat_parse["events"]:
|
525 |
+
event = event.copy()
|
526 |
+
event["id"] = id_prefix + event["id"]
|
527 |
+
trigger = next(
|
528 |
+
tr
|
529 |
+
for tr in brat_parse["text_bound_annotations"]
|
530 |
+
if tr["id"] == event["trigger"]
|
531 |
+
)
|
532 |
+
if trigger in non_event_ann:
|
533 |
+
non_event_ann.remove(trigger)
|
534 |
+
event["trigger"] = {
|
535 |
+
"text": trigger["text"].copy(),
|
536 |
+
"offsets": trigger["offsets"].copy(),
|
537 |
+
}
|
538 |
+
for argument in event["arguments"]:
|
539 |
+
argument["ref_id"] = id_prefix + argument["ref_id"]
|
540 |
+
|
541 |
+
unified_example["events"].append(event)
|
542 |
+
|
543 |
+
unified_example["entities"] = []
|
544 |
+
anno_ids = [ref_id["id"] for ref_id in non_event_ann]
|
545 |
+
for ann in non_event_ann:
|
546 |
+
entity_ann = ann.copy()
|
547 |
+
entity_ann["id"] = id_prefix + entity_ann["id"]
|
548 |
+
entity_ann["normalized"] = ref_id_to_normalizations[ann["id"]]
|
549 |
+
unified_example["entities"].append(entity_ann)
|
550 |
+
|
551 |
+
# massage relations
|
552 |
+
unified_example["relations"] = []
|
553 |
+
skipped_relations = set()
|
554 |
+
for ann in brat_parse["relations"]:
|
555 |
+
if (
|
556 |
+
ann["head"]["ref_id"] not in anno_ids
|
557 |
+
or ann["tail"]["ref_id"] not in anno_ids
|
558 |
+
):
|
559 |
+
skipped_relations.add(ann["id"])
|
560 |
+
continue
|
561 |
+
unified_example["relations"].append(
|
562 |
+
{
|
563 |
+
"arg1_id": id_prefix + ann["head"]["ref_id"],
|
564 |
+
"arg2_id": id_prefix + ann["tail"]["ref_id"],
|
565 |
+
"id": id_prefix + ann["id"],
|
566 |
+
"type": ann["type"],
|
567 |
+
"normalized": [],
|
568 |
+
}
|
569 |
+
)
|
570 |
+
if len(skipped_relations) > 0:
|
571 |
+
example_id = brat_parse["document_id"]
|
572 |
+
logger.info(
|
573 |
+
f"Example:{example_id}: The `bigbio_kb` schema allows `relations` only between entities."
|
574 |
+
f" Skip (for now): "
|
575 |
+
f"{list(skipped_relations)}"
|
576 |
+
)
|
577 |
+
|
578 |
+
# get coreferences
|
579 |
+
unified_example["coreferences"] = []
|
580 |
+
for i, ann in enumerate(brat_parse["equivalences"], start=1):
|
581 |
+
is_entity_cluster = True
|
582 |
+
for ref_id in ann["ref_ids"]:
|
583 |
+
if not ref_id.startswith("T"): # not textbound -> no entity
|
584 |
+
is_entity_cluster = False
|
585 |
+
elif ref_id not in anno_ids: # event trigger -> no entity
|
586 |
+
is_entity_cluster = False
|
587 |
+
if is_entity_cluster:
|
588 |
+
entity_ids = [id_prefix + i for i in ann["ref_ids"]]
|
589 |
+
unified_example["coreferences"].append(
|
590 |
+
{"id": id_prefix + str(i), "entity_ids": entity_ids}
|
591 |
+
)
|
592 |
+
return unified_example
|
ppr.py
ADDED
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
|
16 |
+
import itertools as it
|
17 |
+
from typing import Dict, Generator, List, Tuple
|
18 |
+
|
19 |
+
import datasets
|
20 |
+
|
21 |
+
from .bigbiohub import BigBioConfig, Tasks, kb_features
|
22 |
+
|
23 |
+
_LANGUAGES = ["English"]
|
24 |
+
_PUBMED = True
|
25 |
+
_LOCAL = False
|
26 |
+
|
27 |
+
_CITATION = """\
|
28 |
+
@article{cho2022plant,
|
29 |
+
author = {Cho, Hyejin and Kim, Baeksoo and Choi, Wonjun and Lee, Doheon and Lee, Hyunju},
|
30 |
+
title = {Plant phenotype relationship corpus for biomedical relationships between plants and phenotypes},
|
31 |
+
journal = {Scientific Data},
|
32 |
+
volume = {9},
|
33 |
+
year = {2022},
|
34 |
+
publisher = {Nature Publishing Group},
|
35 |
+
doi = {https://doi.org/10.1038/s41597-022-01350-1},
|
36 |
+
}
|
37 |
+
"""
|
38 |
+
|
39 |
+
_DATASETNAME = "ppr"
|
40 |
+
_DISPLAYNAME = "Plant-Phenotype-Relations"
|
41 |
+
|
42 |
+
_DESCRIPTION = """\
|
43 |
+
The Plant-Phenotype corpus is a text corpus with human annotations of plants, phenotypes, and their relations on a \
|
44 |
+
corpus in 600 PubMed abstracts.
|
45 |
+
"""
|
46 |
+
|
47 |
+
_HOMEPAGE = "https://github.com/DMCB-GIST/PPRcorpus"
|
48 |
+
|
49 |
+
_LICENSE = "UNKNOWN"
|
50 |
+
|
51 |
+
_URLS = {
|
52 |
+
_DATASETNAME: [
|
53 |
+
"https://raw.githubusercontent.com/davidkartchner/PPRcorpus/main/corpus/PPR_train_corpus.txt",
|
54 |
+
"https://raw.githubusercontent.com/davidkartchner/PPRcorpus/main/corpus/PPR_dev_corpus.txt",
|
55 |
+
"https://raw.githubusercontent.com/davidkartchner/PPRcorpus/main/corpus/PPR_test_corpus.txt",
|
56 |
+
],
|
57 |
+
}
|
58 |
+
|
59 |
+
_SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
|
60 |
+
|
61 |
+
_SOURCE_VERSION = "1.0.0"
|
62 |
+
_BIGBIO_VERSION = "1.0.0"
|
63 |
+
|
64 |
+
|
65 |
+
class PlantPhenotypeDataset(datasets.GeneratorBasedBuilder):
|
66 |
+
"""Plant-Phenotype is dataset for NER and RE of plants and their induced phenotypes"""
|
67 |
+
|
68 |
+
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
|
69 |
+
BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
|
70 |
+
|
71 |
+
BUILDER_CONFIGS = [
|
72 |
+
BigBioConfig(
|
73 |
+
name="ppr_source",
|
74 |
+
version=SOURCE_VERSION,
|
75 |
+
description="Plant Phenotype Relations source schema",
|
76 |
+
schema="source",
|
77 |
+
subset_id="plant_phenotype",
|
78 |
+
),
|
79 |
+
BigBioConfig(
|
80 |
+
name="ppr_bigbio_kb",
|
81 |
+
version=BIGBIO_VERSION,
|
82 |
+
description="Plant Phenotype Relations BigBio schema",
|
83 |
+
schema="bigbio_kb",
|
84 |
+
subset_id="plant_phenotype",
|
85 |
+
),
|
86 |
+
]
|
87 |
+
|
88 |
+
DEFAULT_CONFIG_NAME = "ppr_source"
|
89 |
+
|
90 |
+
def _info(self) -> datasets.DatasetInfo:
|
91 |
+
if self.config.schema == "source":
|
92 |
+
|
93 |
+
features = datasets.Features(
|
94 |
+
{
|
95 |
+
"passage_id": datasets.Value("string"),
|
96 |
+
"pmid": datasets.Value("string"),
|
97 |
+
"section": datasets.Value("int32"),
|
98 |
+
"text": datasets.Value("string"),
|
99 |
+
"entities": [
|
100 |
+
{
|
101 |
+
"offsets": datasets.Sequence(datasets.Value("int32")),
|
102 |
+
"text": datasets.Value("string"),
|
103 |
+
"type": datasets.Value("string"),
|
104 |
+
}
|
105 |
+
],
|
106 |
+
"relations": [
|
107 |
+
{
|
108 |
+
"relation_type": datasets.Value("string"),
|
109 |
+
"entity1_offsets": datasets.Sequence(datasets.Value("int32")),
|
110 |
+
"entity1_text": datasets.Value("string"),
|
111 |
+
"entity1_type": datasets.Value("string"),
|
112 |
+
"entity2_offsets": datasets.Sequence(datasets.Value("int32")),
|
113 |
+
"entity2_text": datasets.Value("string"),
|
114 |
+
"entity2_type": datasets.Value("string"),
|
115 |
+
}
|
116 |
+
],
|
117 |
+
}
|
118 |
+
)
|
119 |
+
|
120 |
+
elif self.config.schema == "bigbio_kb":
|
121 |
+
features = kb_features
|
122 |
+
else:
|
123 |
+
raise NotImplementedError(f"Schema {self.config.schema} not supported")
|
124 |
+
|
125 |
+
return datasets.DatasetInfo(
|
126 |
+
description=_DESCRIPTION,
|
127 |
+
features=features,
|
128 |
+
homepage=_HOMEPAGE,
|
129 |
+
license=_LICENSE,
|
130 |
+
citation=_CITATION,
|
131 |
+
)
|
132 |
+
|
133 |
+
def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
|
134 |
+
"""Returns SplitGenerators."""
|
135 |
+
|
136 |
+
urls = _URLS[_DATASETNAME]
|
137 |
+
train, dev, test = dl_manager.download_and_extract(urls)
|
138 |
+
|
139 |
+
return [
|
140 |
+
datasets.SplitGenerator(
|
141 |
+
name=datasets.Split.TRAIN,
|
142 |
+
gen_kwargs={
|
143 |
+
"filepath": train,
|
144 |
+
},
|
145 |
+
),
|
146 |
+
datasets.SplitGenerator(
|
147 |
+
name=datasets.Split.TEST,
|
148 |
+
gen_kwargs={
|
149 |
+
"filepath": test,
|
150 |
+
},
|
151 |
+
),
|
152 |
+
datasets.SplitGenerator(
|
153 |
+
name=datasets.Split.VALIDATION,
|
154 |
+
gen_kwargs={
|
155 |
+
"filepath": dev,
|
156 |
+
},
|
157 |
+
),
|
158 |
+
]
|
159 |
+
|
160 |
+
def _generate_examples(
|
161 |
+
self,
|
162 |
+
filepath,
|
163 |
+
) -> Tuple[int, Dict]:
|
164 |
+
"""Yields examples as (key, example) tuples."""
|
165 |
+
|
166 |
+
with open(filepath, "r") as f:
|
167 |
+
chunks = f.read().strip().split("\n\n")
|
168 |
+
|
169 |
+
if self.config.schema == "source":
|
170 |
+
for id_, doc in self._generate_source_examples(chunks):
|
171 |
+
yield id_, doc
|
172 |
+
|
173 |
+
elif self.config.schema == "bigbio_kb":
|
174 |
+
for id_, doc in self._generate_bigbio_kb_examples(chunks):
|
175 |
+
yield id_, doc
|
176 |
+
|
177 |
+
def _generate_whole_documents(self, annotation_chunks: List[str]) -> Generator[Dict, None, None]:
|
178 |
+
"""Aggregate individual sentence annotations into whole abstracts.
|
179 |
+
|
180 |
+
Args:
|
181 |
+
annotation_chunks (List[str]): List of annotation chunks, i.e., a sentence with its annotations.
|
182 |
+
For example:
|
183 |
+
10072339_4 OBJECTIVE: A patient with possible airborne facial dermatitis to potato is described.
|
184 |
+
10072339 44 61 facial dermatitis Negative_phenotype
|
185 |
+
10072339 65 71 potato Plant
|
186 |
+
|
187 |
+
Returns:
|
188 |
+
Generator producing a dictionary containing the pmid of an article and all document chunks.
|
189 |
+
"""
|
190 |
+
prev_pmid = None
|
191 |
+
pmid = ""
|
192 |
+
doc_chunks = []
|
193 |
+
|
194 |
+
for chunk in annotation_chunks:
|
195 |
+
lines = chunk.split("\n")
|
196 |
+
|
197 |
+
# The first line is the sentence (format: <pmid>_<num>\t<sentence-text>)
|
198 |
+
passage_info, passage_text = lines[0].split("\t")
|
199 |
+
|
200 |
+
# Then annotations in Pubtator format
|
201 |
+
annotations = [line.split("\t") for line in lines[1:]]
|
202 |
+
|
203 |
+
# Get info on passage
|
204 |
+
pmid, section = passage_info.split("_")
|
205 |
+
if prev_pmid is None:
|
206 |
+
prev_pmid = pmid
|
207 |
+
|
208 |
+
elif prev_pmid != pmid:
|
209 |
+
yield {"pmid": prev_pmid, "doc_chunks": doc_chunks}
|
210 |
+
|
211 |
+
# Reset everything for next PMID
|
212 |
+
prev_pmid = pmid
|
213 |
+
doc_chunks = []
|
214 |
+
|
215 |
+
doc_chunks.append(
|
216 |
+
{
|
217 |
+
"passage": passage_text,
|
218 |
+
"annotations": annotations,
|
219 |
+
"sentence_id": passage_info,
|
220 |
+
}
|
221 |
+
)
|
222 |
+
|
223 |
+
# Take care of last document
|
224 |
+
yield {"pmid": pmid, "doc_chunks": doc_chunks}
|
225 |
+
|
226 |
+
def _generate_source_examples(self, annotation_chunks: List[str]) -> Generator[Tuple[str, Dict], None, None]:
|
227 |
+
"""Generate examples in format of source schema
|
228 |
+
|
229 |
+
Args:
|
230 |
+
annotation_chunks (List[str]): List of annotation chunks.
|
231 |
+
|
232 |
+
Returns:
|
233 |
+
Generator of instance tuples (<key>, <instance-dict>)
|
234 |
+
"""
|
235 |
+
for chunk in annotation_chunks:
|
236 |
+
lines = chunk.split("\n")
|
237 |
+
|
238 |
+
passage_id, passage_text = lines[0].split("\t")
|
239 |
+
annotations = [line.split("\t") for line in lines[1:]]
|
240 |
+
|
241 |
+
# Get info on passage
|
242 |
+
pmid, section = passage_id.split("_")
|
243 |
+
section = int(section)
|
244 |
+
|
245 |
+
# Grab entities and relations
|
246 |
+
entities = []
|
247 |
+
relations = []
|
248 |
+
for annotation in annotations:
|
249 |
+
if len(annotation) == 5:
|
250 |
+
# It's an entity annotation
|
251 |
+
entities.append(
|
252 |
+
{
|
253 |
+
"offsets": (int(annotation[1]), int(annotation[2])),
|
254 |
+
"text": annotation[3],
|
255 |
+
"type": annotation[4],
|
256 |
+
}
|
257 |
+
)
|
258 |
+
|
259 |
+
elif len(annotation) == 10:
|
260 |
+
# Relation annotation
|
261 |
+
relations.append(
|
262 |
+
{
|
263 |
+
"relation_type": annotation[1],
|
264 |
+
"entity1_offsets": (int(annotation[2]), int(annotation[3])),
|
265 |
+
"entity1_text": annotation[4],
|
266 |
+
"entity1_type": annotation[5],
|
267 |
+
"entity2_offsets": (int(annotation[6]), int(annotation[7])),
|
268 |
+
"entity2_text": annotation[8],
|
269 |
+
"entity2_type": annotation[9],
|
270 |
+
}
|
271 |
+
)
|
272 |
+
else:
|
273 |
+
# This is a special case that occurs for a single data point
|
274 |
+
relations.append(
|
275 |
+
{
|
276 |
+
"relation_type": annotation[1],
|
277 |
+
"entity1_offsets": (int(annotation[2]), int(annotation[3])),
|
278 |
+
"entity1_text": annotation[4],
|
279 |
+
"entity1_type": annotation[5],
|
280 |
+
"entity2_offsets": (int(annotation[8]), int(annotation[9])),
|
281 |
+
"entity2_text": annotation[10],
|
282 |
+
"entity2_type": annotation[11],
|
283 |
+
}
|
284 |
+
)
|
285 |
+
|
286 |
+
# Consolidate into document
|
287 |
+
document = {
|
288 |
+
"passage_id": passage_id,
|
289 |
+
"pmid": pmid,
|
290 |
+
"section": section,
|
291 |
+
"text": passage_text,
|
292 |
+
"entities": entities,
|
293 |
+
"relations": relations,
|
294 |
+
}
|
295 |
+
|
296 |
+
yield passage_id, document
|
297 |
+
|
298 |
+
def _generate_bigbio_kb_examples(self, annotation_chunks: List[str]):
|
299 |
+
"""Generator for training examples in bigbio_kb schema format.
|
300 |
+
|
301 |
+
Args:
|
302 |
+
annotation_chunks (List[str]): List of annotation chunks.
|
303 |
+
|
304 |
+
Returns:
|
305 |
+
Generator of instance tuples (<key>, <instance-dict>)
|
306 |
+
"""
|
307 |
+
uid = it.count(1)
|
308 |
+
for document in self._generate_whole_documents(annotation_chunks):
|
309 |
+
pmid = document["pmid"]
|
310 |
+
offset_delta = 0
|
311 |
+
id_ = str(next(uid))
|
312 |
+
|
313 |
+
passages = []
|
314 |
+
entities = []
|
315 |
+
relations = []
|
316 |
+
|
317 |
+
# Iterate through each section of the article
|
318 |
+
for text_section in document["doc_chunks"]:
|
319 |
+
# Extract passages
|
320 |
+
passage = text_section["passage"]
|
321 |
+
passages.append(
|
322 |
+
{
|
323 |
+
"id": str(next(uid)),
|
324 |
+
"text": [passage],
|
325 |
+
"type": "sentence",
|
326 |
+
"offsets": [(offset_delta, offset_delta + len(passage))],
|
327 |
+
}
|
328 |
+
)
|
329 |
+
|
330 |
+
# Extract entities
|
331 |
+
entities_sublist = []
|
332 |
+
for annotation in text_section["annotations"]:
|
333 |
+
if len(annotation) == 5:
|
334 |
+
entities_sublist.append(
|
335 |
+
{
|
336 |
+
"id": str(next(uid)),
|
337 |
+
"type": annotation[4],
|
338 |
+
"text": [annotation[3]],
|
339 |
+
"offsets": [(int(annotation[1]) + offset_delta, int(annotation[2]) + offset_delta)],
|
340 |
+
"normalized": [],
|
341 |
+
}
|
342 |
+
)
|
343 |
+
|
344 |
+
# Create mapping of offsets to entity_id
|
345 |
+
ent2id = {tuple(x["offsets"]): x["id"] for x in entities_sublist}
|
346 |
+
entities.extend(entities_sublist)
|
347 |
+
|
348 |
+
# Extract relations
|
349 |
+
for annotation in text_section["annotations"]:
|
350 |
+
if len(annotation) == 10:
|
351 |
+
e1_offsets = [(int(annotation[2]) + offset_delta, int(annotation[3]) + offset_delta)]
|
352 |
+
e2_offsets = [(int(annotation[6]) + offset_delta, int(annotation[7]) + offset_delta)]
|
353 |
+
relations.append(
|
354 |
+
{
|
355 |
+
"id": str(next(uid)),
|
356 |
+
"type": annotation[1],
|
357 |
+
"arg1_id": ent2id[tuple(e1_offsets)],
|
358 |
+
"arg2_id": ent2id[tuple(e2_offsets)],
|
359 |
+
"normalized": [],
|
360 |
+
}
|
361 |
+
)
|
362 |
+
|
363 |
+
# Special case for a single annotation
|
364 |
+
elif len(annotation) > 10:
|
365 |
+
print(annotation)
|
366 |
+
print(passage)
|
367 |
+
e1_offsets = [(int(annotation[2]) + offset_delta, int(annotation[3]) + offset_delta)]
|
368 |
+
e2_offsets = [(int(annotation[8]) + offset_delta, int(annotation[9]) + offset_delta)]
|
369 |
+
relations.append(
|
370 |
+
{
|
371 |
+
"id": str(next(uid)),
|
372 |
+
"type": annotation[1],
|
373 |
+
"arg1_id": ent2id[tuple(e1_offsets)],
|
374 |
+
"arg2_id": ent2id[tuple(e2_offsets)],
|
375 |
+
"normalized": [],
|
376 |
+
}
|
377 |
+
)
|
378 |
+
|
379 |
+
offset_delta += len(passage) + 1
|
380 |
+
|
381 |
+
doc = {
|
382 |
+
"id": id_,
|
383 |
+
"document_id": pmid,
|
384 |
+
"passages": passages,
|
385 |
+
"entities": entities,
|
386 |
+
"relations": relations,
|
387 |
+
"events": [],
|
388 |
+
"coreferences": [],
|
389 |
+
}
|
390 |
+
|
391 |
+
yield id_, doc
|