gabrielaltay commited on
Commit
408e34b
1 Parent(s): c221773

upload hubscripts/ddi_corpus_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. ddi_corpus.py +222 -0
ddi_corpus.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
17
+ The DDI corpus has been manually annotated with drugs and pharmacokinetics and
18
+ pharmacodynamics interactions. It contains 1025 documents from two different
19
+ sources: DrugBank database and MedLine.
20
+ """
21
+
22
+ import os
23
+ from pathlib import Path
24
+ from typing import Dict, List, Tuple
25
+
26
+ import datasets
27
+
28
+ from .bigbiohub import kb_features
29
+ from .bigbiohub import BigBioConfig
30
+ from .bigbiohub import Tasks
31
+
32
+ _LANGUAGES = ['English']
33
+ _PUBMED = True
34
+ _LOCAL = False
35
+ _CITATION = """\
36
+ @article{HERREROZAZO2013914,
37
+ title = {
38
+ The DDI corpus: An annotated corpus with pharmacological substances and
39
+ drug-drug interactions
40
+ },
41
+ author = {
42
+ María Herrero-Zazo and Isabel Segura-Bedmar and Paloma Martínez and Thierry
43
+ Declerck
44
+ },
45
+ year = 2013,
46
+ journal = {Journal of Biomedical Informatics},
47
+ volume = 46,
48
+ number = 5,
49
+ pages = {914--920},
50
+ doi = {https://doi.org/10.1016/j.jbi.2013.07.011},
51
+ issn = {1532-0464},
52
+ url = {https://www.sciencedirect.com/science/article/pii/S1532046413001123},
53
+ keywords = {Biomedical corpora, Drug interaction, Information extraction}
54
+ }
55
+
56
+ """
57
+
58
+ _DATASETNAME = "ddi_corpus"
59
+ _DISPLAYNAME = "DDI Corpus"
60
+
61
+ _DESCRIPTION = """\
62
+ The DDI corpus has been manually annotated with drugs and pharmacokinetics and \
63
+ pharmacodynamics interactions. It contains 1025 documents from two different \
64
+ sources: DrugBank database and MedLine.
65
+ """
66
+
67
+ _HOMEPAGE = "https://github.com/isegura/DDICorpus"
68
+
69
+ _LICENSE = 'Creative Commons Attribution Non Commercial 4.0 International'
70
+
71
+ _URLS = {
72
+ _DATASETNAME: "https://github.com/isegura/DDICorpus/raw/master/DDICorpus-2013(BRAT).zip",
73
+ }
74
+
75
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION, Tasks.RELATION_EXTRACTION]
76
+
77
+ _SOURCE_VERSION = "1.0.0"
78
+ _BIGBIO_VERSION = "1.0.0"
79
+
80
+
81
+ class DDICorpusDataset(datasets.GeneratorBasedBuilder):
82
+ """DDI Corpus"""
83
+
84
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
85
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
86
+
87
+ BUILDER_CONFIGS = [
88
+ BigBioConfig(
89
+ name="ddi_corpus_source",
90
+ version=SOURCE_VERSION,
91
+ description="DDI Corpus source schema",
92
+ schema="source",
93
+ subset_id="ddi_corpus",
94
+ ),
95
+ BigBioConfig(
96
+ name="ddi_corpus_bigbio_kb",
97
+ version=BIGBIO_VERSION,
98
+ description="DDI Corpus BigBio schema",
99
+ schema="bigbio_kb",
100
+ subset_id="ddi_corpus",
101
+ ),
102
+ ]
103
+
104
+ DEFAULT_CONFIG_NAME = "ddi_corpus_source"
105
+
106
+ def _info(self) -> datasets.DatasetInfo:
107
+
108
+ if self.config.schema == "source":
109
+ features = datasets.Features(
110
+ {
111
+ "document_id": datasets.Value("string"),
112
+ "text": datasets.Value("string"),
113
+ "entities": [
114
+ {
115
+ "offsets": datasets.Sequence(datasets.Value("int32")),
116
+ "text": datasets.Value("string"),
117
+ "type": datasets.Value("string"),
118
+ "id": datasets.Value("string"),
119
+ }
120
+ ],
121
+ "relations": [
122
+ {
123
+ "id": datasets.Value("string"),
124
+ "head": {
125
+ "ref_id": datasets.Value("string"),
126
+ "role": datasets.Value("string"),
127
+ },
128
+ "tail": {
129
+ "ref_id": datasets.Value("string"),
130
+ "role": datasets.Value("string"),
131
+ },
132
+ "type": datasets.Value("string"),
133
+ }
134
+ ],
135
+ }
136
+ )
137
+
138
+ elif self.config.schema == "bigbio_kb":
139
+ features = kb_features
140
+
141
+ return datasets.DatasetInfo(
142
+ description=_DESCRIPTION,
143
+ features=features,
144
+ homepage=_HOMEPAGE,
145
+ license=str(_LICENSE),
146
+ citation=_CITATION,
147
+ )
148
+
149
+ def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
150
+ urls = _URLS[_DATASETNAME]
151
+ data_dir = dl_manager.download_and_extract(urls)
152
+
153
+ standoff_dir = os.path.join(data_dir, "DDICorpusBrat")
154
+
155
+ return [
156
+ datasets.SplitGenerator(
157
+ name=datasets.Split.TRAIN,
158
+ gen_kwargs={
159
+ "filepath": os.path.join(standoff_dir, "Train"),
160
+ "split": "train",
161
+ },
162
+ ),
163
+ datasets.SplitGenerator(
164
+ name=datasets.Split.TEST,
165
+ gen_kwargs={
166
+ "filepath": os.path.join(standoff_dir, "Test"),
167
+ "split": "test",
168
+ },
169
+ ),
170
+ ]
171
+
172
+ def _generate_examples(self, filepath: str, split: str) -> Tuple[int, Dict]:
173
+ if self.config.schema == "source":
174
+ for subdir, _, files in os.walk(filepath):
175
+ for file in files:
176
+ # Ignore configuration files and annotation files - we just consider the brat text files
177
+ if not file.endswith(".txt"):
178
+ continue
179
+
180
+ brat_example = parsing.parse_brat_file(Path(subdir) / file)
181
+ source_example = self._to_source_example(brat_example)
182
+
183
+ yield source_example["document_id"], source_example
184
+
185
+ elif self.config.schema == "bigbio_kb":
186
+ for subdir, _, files in os.walk(filepath):
187
+ for file in files:
188
+ # Ignore configuration files and annotation files - we just consider the brat text files
189
+ if not file.endswith(".txt"):
190
+ continue
191
+
192
+ # Read brat annotations for the given text file and convert example to the BigBio-KB format
193
+ brat_example = parsing.parse_brat_file(Path(subdir) / file)
194
+ kb_example = parsing.brat_parse_to_bigbio_kb(brat_example)
195
+ kb_example["id"] = kb_example["document_id"]
196
+
197
+ yield kb_example["id"], kb_example
198
+
199
+ @staticmethod
200
+ def _to_source_example(brat_example: Dict) -> Dict:
201
+ source_example = {
202
+ "document_id": brat_example["document_id"],
203
+ "text": brat_example["text"],
204
+ "relations": brat_example["relations"],
205
+ }
206
+
207
+ source_example["entities"] = []
208
+ for entity_annotation in brat_example["text_bound_annotations"]:
209
+ entity_ann = entity_annotation.copy()
210
+
211
+ source_example["entities"].append(
212
+ {
213
+ # These are lists in the parsed output, so just take the first element to
214
+ # match the source schema.
215
+ "offsets": entity_annotation["offsets"][0],
216
+ "text": entity_ann["text"][0],
217
+ "type": entity_ann["type"],
218
+ "id": entity_ann["id"],
219
+ }
220
+ )
221
+
222
+ return source_example