Datasets:

Languages:
English
License:
gabrielaltay commited on
Commit
fc646bf
·
1 Parent(s): 282b7ef

upload hubscripts/n2c2_2006_deid_hub.py to hub from bigbio repo

Browse files
Files changed (1) hide show
  1. n2c2_2006_deid.py +362 -0
n2c2_2006_deid.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
18
+ A dataset loader for the n2c2 2006 de-identification dataset.
19
+
20
+ https://portal.dbmi.hms.harvard.edu/projects/n2c2-nlp/
21
+
22
+ The dataset consists of two archive files,
23
+
24
+ * deid_surrogate_train_all_version2.zip
25
+ * deid_surrogate_test_all_groundtruth_version2.zip
26
+
27
+ The individual data files (inside the zip archives) come in just 1 type:
28
+
29
+ * xml (*.xml files): contains the id and text of the patient records,
30
+ and the corresponding tags for each one of the Patient Health information (PHI)
31
+ categories: Patients, Doctors, Hospitals, IDs, Dates, Locations, Phone Numbers, and Ages
32
+
33
+
34
+ The files comprising this dataset must be on the users local machine
35
+ in a single directory that is passed to `datasets.load_datset` via
36
+ the `data_dir` kwarg. This loader script will read the archive files
37
+ directly (i.e. the user should not uncompress, untar or unzip any of
38
+ the files). For example, if the following directory structure exists
39
+ on the users local machine,
40
+
41
+
42
+ n2c2_2006_deid
43
+ ├── deid_surrogate_train_all_version2.zip
44
+ ├── deid_surrogate_test_all_groundtruth_version2.zip
45
+
46
+
47
+ Data Access
48
+
49
+ from https://www.i2b2.org/NLP/DataSets/Main.php
50
+
51
+ "As always, you must register AND submit a DUA for access. If you previously
52
+ accessed the data sets here on i2b2.org, you will need to set a new password
53
+ for your account on the Data Portal, but your original DUA will be retained."
54
+
55
+
56
+ """
57
+ import itertools as it
58
+ import os
59
+ import re
60
+ import xml.etree.ElementTree as et
61
+ import zipfile
62
+ from typing import Dict, List, Tuple
63
+
64
+ import datasets
65
+
66
+ from .bigbiohub import kb_features
67
+ from .bigbiohub import BigBioConfig
68
+ from .bigbiohub import Tasks
69
+
70
+ _DATASETNAME = "n2c2_2006"
71
+ _DISPLAYNAME = "n2c2 2006 De-identification"
72
+
73
+ # https://academic.oup.com/jamia/article/14/5/550/720189
74
+ _LANGUAGES = ['English']
75
+ _PUBMED = False
76
+ _LOCAL = True
77
+ _CITATION = """\
78
+ @article{uzuner2007evaluating,
79
+ author = {
80
+ Uzuner, Özlem and
81
+ Luo, Yuan and
82
+ Szolovits, Peter
83
+ },
84
+ title = {Evaluating the State-of-the-Art in Automatic De-identification},
85
+ journal = {Journal of the American Medical Informatics Association},
86
+ volume = {14},
87
+ number = {5},
88
+ pages = {550-563},
89
+ year = {2007},
90
+ month = {09},
91
+ url = {https://doi.org/10.1197/jamia.M2444},
92
+ doi = {10.1197/jamia.M2444},
93
+ eprint = {https://academic.oup.com/jamia/article-pdf/14/5/550/2136261/14-5-550.pdf}
94
+ }
95
+ """
96
+
97
+ _DESCRIPTION = """\
98
+ The data for the de-identification challenge came from Partners Healthcare and
99
+ included solely medical discharge summaries. We prepared the data for the
100
+ challengeby annotating and by replacing all authentic PHI with realistic
101
+ surrogates.
102
+
103
+ Given the above definitions, we marked the authentic PHI in the records in two stages.
104
+ In the first stage, we used an automatic system.31 In the second stage, we validated
105
+ the output of the automatic system manually. Three annotators, including undergraduate
106
+ and graduate students and a professor, serially made three manual passes over each record.
107
+ They marked and discussed the PHI tags they disagreed on and finalized these tags
108
+ after discussion.
109
+
110
+ The original dataset does not have spans for each entity. The spans are
111
+ computed in this loader and the final text that correspond with the
112
+ tags is preserved in the source format
113
+ """
114
+
115
+ _HOMEPAGE = "https://portal.dbmi.hms.harvard.edu/projects/n2c2-nlp/"
116
+
117
+ _LICENSE = 'Data User Agreement'
118
+
119
+ _SUPPORTED_TASKS = [Tasks.NAMED_ENTITY_RECOGNITION]
120
+
121
+ _SOURCE_VERSION = "1.0.0"
122
+ _BIGBIO_VERSION = "1.0.0"
123
+
124
+
125
+ class N2C22006DeidDataset(datasets.GeneratorBasedBuilder):
126
+ """n2c2 2006 smoking status identification task"""
127
+
128
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
129
+ BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
130
+
131
+ BUILDER_CONFIGS = [
132
+ BigBioConfig(
133
+ name="n2c2_2006_deid_source",
134
+ version=SOURCE_VERSION,
135
+ description="n2c2_2006 deid source schema",
136
+ schema="source",
137
+ subset_id="n2c2_2006_deid",
138
+ ),
139
+ BigBioConfig(
140
+ name="n2c2_2006_deid_bigbio_kb",
141
+ version=BIGBIO_VERSION,
142
+ description="n2c2_2006 Deid BigBio schema",
143
+ schema="bigbio_kb",
144
+ subset_id="n2c2_2006_deid",
145
+ ),
146
+ ]
147
+
148
+ DEFAULT_CONFIG_NAME = "n2c2_2006_deid_source"
149
+
150
+ def _info(self) -> datasets.DatasetInfo:
151
+
152
+ if self.config.schema == "source":
153
+ features = datasets.Features(
154
+ {
155
+ "record_id": datasets.Value("string"),
156
+ "text": datasets.Value("string"),
157
+ "phi": datasets.Sequence(datasets.Value("string")),
158
+ }
159
+ )
160
+
161
+ elif self.config.schema == "bigbio_kb":
162
+ features = kb_features
163
+
164
+ return datasets.DatasetInfo(
165
+ description=_DESCRIPTION,
166
+ features=features,
167
+ homepage=_HOMEPAGE,
168
+ license=str(_LICENSE),
169
+ citation=_CITATION,
170
+ )
171
+
172
+ def _split_generators(
173
+ self, dl_manager: datasets.DownloadManager
174
+ ) -> List[datasets.SplitGenerator]:
175
+ """Returns SplitGenerators."""
176
+
177
+ if self.config.data_dir is None:
178
+ raise ValueError(
179
+ "This is a local dataset. Please pass the data_dir kwarg to load_dataset."
180
+ )
181
+ else:
182
+ data_dir = self.config.data_dir
183
+
184
+ return [
185
+ datasets.SplitGenerator(
186
+ name=datasets.Split.TRAIN,
187
+ gen_kwargs={
188
+ "data_dir": data_dir,
189
+ "corpus_fname": "deid_surrogate_train_all_version2.zip",
190
+ },
191
+ ),
192
+ datasets.SplitGenerator(
193
+ name=datasets.Split.TEST,
194
+ gen_kwargs={
195
+ "data_dir": data_dir,
196
+ "corpus_fname": "deid_surrogate_test_all_groundtruth_version2.zip",
197
+ },
198
+ ),
199
+ ]
200
+
201
+ def _generate_examples(self, data_dir: str, corpus_fname: str) -> Tuple[int, Dict]:
202
+ """Yields examples as (key, example) tuples."""
203
+
204
+ fpath = os.path.join(data_dir, corpus_fname)
205
+ # samples = _read_zip(path)
206
+ if self.config.schema == "source":
207
+ for document in self._generate_parsed_documents(fpath):
208
+ yield document["record_id"], document
209
+
210
+ elif self.config.schema == "bigbio_kb":
211
+ uid = it.count(0)
212
+ for document in self._generate_parsed_documents(fpath):
213
+ document["id"] = next(uid)
214
+ document["document_id"] = document.pop("record_id")
215
+ entity_list = document.pop("phi")
216
+ full_text = document.pop("text")
217
+ entities_ = []
218
+ for entity in entity_list:
219
+ entities_.append(
220
+ {
221
+ "id": next(uid),
222
+ "type": entity["type"],
223
+ "text": entity["text"],
224
+ "offsets": entity["offsets"],
225
+ "normalized": entity["normalized"],
226
+ }
227
+ )
228
+ document["entities"] = entities_
229
+
230
+ document["passages"] = [
231
+ {
232
+ "id": next(uid),
233
+ "type": "full_text",
234
+ "text": [full_text],
235
+ "offsets": [[0, len(full_text)]],
236
+ },
237
+ ]
238
+
239
+ # additional fields required that can be empty
240
+ document["relations"] = []
241
+ document["events"] = []
242
+ document["coreferences"] = []
243
+ yield document["document_id"], document
244
+
245
+ def _generate_parsed_documents(self, file_path):
246
+ _, filename = os.path.split(file_path)
247
+ zipped = zipfile.ZipFile(file_path, "r")
248
+ file = zipped.read(filename.split(".")[0] + ".xml")
249
+
250
+ # There is an issue with the train file. There is a bad tag in line 25722
251
+ if filename == "deid_surrogate_train_all_version2.zip":
252
+ bad_tag = """<PHI TYPE="DATE">25th of July<PHI TYPE="DOCTOR">""".encode(
253
+ "utf-8"
254
+ )
255
+ replacement_tag = """<PHI TYPE="DATE">25th of July</PHI>""".encode("utf-8")
256
+ file = file.replace(bad_tag, replacement_tag, 1)
257
+
258
+ root = et.fromstring(file)
259
+ documents = root.findall("./RECORD")
260
+ record_regex = r"<RECORD ID=|</RECORD>"
261
+ text_regex = r"<TEXT>|</TEXT>"
262
+ file_string = str(file)
263
+ record_matches = list(re.finditer(record_regex, file_string))
264
+ n_matches = len(record_matches)
265
+ if len(documents) != n_matches / 2:
266
+ raise ValueError(
267
+ """the records found thourgh regex are not the
268
+ same as the ones found using xmltree"""
269
+ )
270
+
271
+ # counter for the documents in xml
272
+ k = 0
273
+ for i in range(0, n_matches, 2):
274
+
275
+ # find beginning and end of a section
276
+ record_start = record_matches[i].span()[1]
277
+ record_end = record_matches[i + 1].span()[0]
278
+ record_section = file_string[record_start:record_end]
279
+
280
+ # find only the text section
281
+ text_matches = list(re.finditer(text_regex, record_section))
282
+ if len(text_matches) > 2:
283
+ raise ValueError("It should only be one match for text within a record")
284
+ text_start = text_matches[0].span()[1]
285
+ text_end = text_matches[1].span()[0]
286
+
287
+ # remove new line at the beginning and the end
288
+ full_text_with_tags = record_section[text_start:text_end].strip("\\n")
289
+ # Remove special characters
290
+ full_text_with_tags = self._remove_special_characters(full_text_with_tags)
291
+
292
+ # find all the PHI tags to process them one by one
293
+ document = documents[k]
294
+ phi_xml_tags = document.findall("./TEXT/PHI")
295
+ k += 1
296
+
297
+ entities, clean_text = self._extract_tags_text_spans(
298
+ full_text_with_tags=full_text_with_tags, phi_list=phi_xml_tags
299
+ )
300
+
301
+ document_dict = {
302
+ "record_id": document.attrib["ID"],
303
+ "text": clean_text,
304
+ "phi": entities,
305
+ }
306
+
307
+ yield document_dict
308
+
309
+ def _extract_tags_text_spans(
310
+ self, full_text_with_tags: str, phi_list: List[et.Element]
311
+ ) -> List[Dict]:
312
+ """
313
+ Method to extract all PHI tags from within the XML
314
+ Note: There are entities with the same text but different tags.
315
+ Example "Head" Type Doctor/Patient
316
+ Because of this the method needs to check first for it and then assumes the retrieval order
317
+ by the xml library and get the proper spans for each one
318
+ """
319
+
320
+ entities = []
321
+ for phi in phi_list:
322
+ entity_text = phi.text
323
+ entity_type = phi.attrib["TYPE"]
324
+ phi_regex = re.escape(f"""<PHI TYPE="{entity_type}">{entity_text}</PHI>""")
325
+ phi_match = re.search(phi_regex, full_text_with_tags)
326
+ if phi_match is None:
327
+ print(phi_regex)
328
+ raise ValueError(f"PHI tag {phi_regex} not found")
329
+
330
+ entity_start = phi_match.span()[0]
331
+ entity_end = entity_start + len(entity_text)
332
+
333
+ # Substitute in the original text to eliminate the current tag
334
+ # only replace the first occurrence
335
+ full_text_with_tags = re.sub(
336
+ pattern=phi_regex, repl=entity_text, string=full_text_with_tags, count=1
337
+ )
338
+
339
+ # check that the text within the span is the same as the entity text
340
+ if entity_text != full_text_with_tags[entity_start:entity_end]:
341
+ raise ValueError("Entity text does not have the correct span")
342
+
343
+ # save the entities
344
+ entities.append(
345
+ {
346
+ "text": [entity_text],
347
+ "type": entity_type,
348
+ "offsets": [[entity_start, entity_end]],
349
+ "normalized": [],
350
+ }
351
+ )
352
+
353
+ # clean the last remaining tag
354
+ clean_text = re.sub(r"\\n\[ report_end \]", "", full_text_with_tags)
355
+ return entities, clean_text
356
+
357
+ def _remove_special_characters(self, text: str) -> str:
358
+ result = text.replace("&gt;", ">")
359
+ result = result.replace("&lt;", "<")
360
+ result = result.replace("&quot;", '"')
361
+ result = result.replace("&apos;", "'")
362
+ return result