Datasets:
Delete
#16
by
ShikharLLM
- opened
pubmed.py
DELETED
@@ -1,384 +0,0 @@
|
|
1 |
-
# coding=utf-8
|
2 |
-
# Copyright 2020 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 |
-
"""MEDLINE/PubMed data."""
|
16 |
-
|
17 |
-
|
18 |
-
import copy
|
19 |
-
import gzip
|
20 |
-
import xml.etree.ElementTree as ET
|
21 |
-
|
22 |
-
import datasets
|
23 |
-
|
24 |
-
|
25 |
-
logger = datasets.logging.get_logger(__name__)
|
26 |
-
|
27 |
-
|
28 |
-
_CITATION = """\
|
29 |
-
Courtesy of the U.S. National Library of Medicine.
|
30 |
-
"""
|
31 |
-
|
32 |
-
_DESCRIPTION = """\
|
33 |
-
NLM produces a baseline set of MEDLINE/PubMed citation records in XML format for download on an annual basis. The annual baseline is released in December of each year. Each day, NLM produces update files that include new, revised and deleted citations. See our documentation page for more information.
|
34 |
-
"""
|
35 |
-
|
36 |
-
_HOMEPAGE = "https://www.nlm.nih.gov/databases/download/pubmed_medline.html"
|
37 |
-
|
38 |
-
_LICENSE = ""
|
39 |
-
|
40 |
-
_URLs = [f"https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed24n{i:04d}.xml.gz" for i in range(1, 1220)]
|
41 |
-
|
42 |
-
|
43 |
-
# Copyright Ferry Boender, released under the MIT license.
|
44 |
-
# Modified by @Narsil to handle more oddities
|
45 |
-
def deepupdate(target, src):
|
46 |
-
"""Deep update target dict with src
|
47 |
-
For each k,v in src: if k doesn't exist in target, it is deep copied from
|
48 |
-
src to target. Otherwise, if v is a list, target[k] is extended with
|
49 |
-
src[k]. If v is a set, target[k] is updated with v, If v is a dict,
|
50 |
-
recursively deep-update it.
|
51 |
-
|
52 |
-
Examples:
|
53 |
-
>>> t = {'name': 'Ferry', 'hobbies': ['programming', 'sci-fi']}
|
54 |
-
>>> deepupdate(t, {'hobbies': ['gaming']})
|
55 |
-
>>> print(t)
|
56 |
-
{'name': 'Ferry', 'hobbies': ['programming', 'sci-fi', 'gaming']}
|
57 |
-
"""
|
58 |
-
for k, v in src.items():
|
59 |
-
if k in target and isinstance(target[k], int) and isinstance(v, str):
|
60 |
-
try:
|
61 |
-
v = int(v)
|
62 |
-
except Exception:
|
63 |
-
pass
|
64 |
-
if k in target and type(target[k]) != type(v):
|
65 |
-
logger.warning(f"Ignoring field {k} it's a {type(v)} and we expect a {type(target[k])}")
|
66 |
-
continue
|
67 |
-
|
68 |
-
if type(v) == list:
|
69 |
-
if k not in target:
|
70 |
-
target[k] = copy.deepcopy(v)
|
71 |
-
elif isinstance(target[k], list):
|
72 |
-
target[k].extend(v)
|
73 |
-
elif isinstance(target[k], str):
|
74 |
-
# Very special case to handle `AbstractText` which sometimes end up
|
75 |
-
# being a list.
|
76 |
-
new_v = " ".join(el for el in v if isinstance(el, str))
|
77 |
-
target[k] = new_v
|
78 |
-
else:
|
79 |
-
logger.warning(f"Ignoring field {k} it's a {type(v)} and we expect a {type(target[k])}")
|
80 |
-
elif type(v) == dict:
|
81 |
-
if k not in target:
|
82 |
-
target[k] = copy.deepcopy(v)
|
83 |
-
elif isinstance(target[k], dict):
|
84 |
-
deepupdate(target[k], v)
|
85 |
-
else:
|
86 |
-
logger.warning(f"Ignoring field {k} it's a {type(v)} and we expect a {type(target[k])}")
|
87 |
-
elif type(v) == set:
|
88 |
-
if k not in target:
|
89 |
-
target[k] = v.copy()
|
90 |
-
elif isinstance(target[k], set):
|
91 |
-
target[k].update(v.copy())
|
92 |
-
else:
|
93 |
-
logger.warning(f"Ignoring field {k} it's a {type(v)} and we expect a {type(target[k])}")
|
94 |
-
else:
|
95 |
-
if isinstance(target[k], (list, tuple, dict)):
|
96 |
-
logger.warning(f"Ignoring field {k} it's a {type(v)} and we expect a {type(target[k])}")
|
97 |
-
continue
|
98 |
-
|
99 |
-
target[k] = copy.copy(v)
|
100 |
-
|
101 |
-
|
102 |
-
def default_date():
|
103 |
-
return {"Year": 0, "Month": 0, "Day": 0}
|
104 |
-
|
105 |
-
|
106 |
-
def default_inline_article():
|
107 |
-
return {
|
108 |
-
# 'Journal': Journal,
|
109 |
-
"Abstract": {"AbstractText": ""},
|
110 |
-
"ArticleTitle": "",
|
111 |
-
# 'Pagination': {'MedlinePgn': datasets.Value('string')},
|
112 |
-
"AuthorList": {"Author": []},
|
113 |
-
"Language": "",
|
114 |
-
"GrantList": {
|
115 |
-
"Grant": [],
|
116 |
-
},
|
117 |
-
"PublicationTypeList": {"PublicationType": []},
|
118 |
-
}
|
119 |
-
|
120 |
-
|
121 |
-
def default_article():
|
122 |
-
return {
|
123 |
-
"MedlineCitation": {
|
124 |
-
"PMID": 0,
|
125 |
-
"DateCompleted": default_date(),
|
126 |
-
"NumberOfReferences": 0,
|
127 |
-
"DateRevised": default_date(),
|
128 |
-
"Article": default_inline_article(),
|
129 |
-
"MedlineJournalInfo": {"Country": ""},
|
130 |
-
"ChemicalList": {"Chemical": []},
|
131 |
-
"CitationSubset": "",
|
132 |
-
"MeshHeadingList": {"MeshHeading": []},
|
133 |
-
},
|
134 |
-
"PubmedData": {
|
135 |
-
"ArticleIdList": [{"ArticleId": []}],
|
136 |
-
"PublicationStatus": "",
|
137 |
-
"History": {"PubMedPubDate": []},
|
138 |
-
"ReferenceList": [],
|
139 |
-
},
|
140 |
-
}
|
141 |
-
|
142 |
-
|
143 |
-
class Pubmed(datasets.GeneratorBasedBuilder):
|
144 |
-
"""Pubmed citations records"""
|
145 |
-
|
146 |
-
BUILDER_CONFIGS = [
|
147 |
-
datasets.BuilderConfig(name="2024", description="The 2024 annual record", version=datasets.Version("4.0.0")),
|
148 |
-
]
|
149 |
-
|
150 |
-
# FILLED automatically from features
|
151 |
-
SIMPLE_KEYS = {"PubmedArticleSet"}
|
152 |
-
LIST_KEYS = {"PubmedArticle"}
|
153 |
-
IGNORE_KEYS = set()
|
154 |
-
|
155 |
-
def fill_keys_from_features(self, features):
|
156 |
-
if isinstance(features, dict):
|
157 |
-
for key, value in features.items():
|
158 |
-
if isinstance(value, datasets.Sequence):
|
159 |
-
self.LIST_KEYS.add(key)
|
160 |
-
self.fill_keys_from_features(value.feature)
|
161 |
-
else:
|
162 |
-
self.SIMPLE_KEYS.add(key)
|
163 |
-
self.fill_keys_from_features(value)
|
164 |
-
|
165 |
-
def xml_to_dictionnary(self, parentElement):
|
166 |
-
data = {}
|
167 |
-
if parentElement.tag in {"AbstractText", "ArticleTitle"}:
|
168 |
-
# XXX
|
169 |
-
# Very special case, it will contain html leading to having very odd structure
|
170 |
-
tag = parentElement.tag
|
171 |
-
string = ET.tostring(parentElement).decode("utf-8").strip()
|
172 |
-
inner_string = string[len(f"<{tag}>") : -len(f"</{tag}>")]
|
173 |
-
return {parentElement.tag: inner_string}
|
174 |
-
|
175 |
-
for child in list(parentElement):
|
176 |
-
child.text = child.text if (child.text is not None) else " "
|
177 |
-
key = child.tag
|
178 |
-
if len(child) == 0:
|
179 |
-
value = child.text.strip()
|
180 |
-
else:
|
181 |
-
value = self.xml_to_dictionnary(child)
|
182 |
-
if isinstance(value, dict) and set(value.keys()) == {key}:
|
183 |
-
value = value[key]
|
184 |
-
|
185 |
-
if key in data:
|
186 |
-
old_value = data[key]
|
187 |
-
if isinstance(old_value, dict):
|
188 |
-
data[key] = [old_value, value]
|
189 |
-
elif isinstance(old_value, list):
|
190 |
-
data[key].append(value)
|
191 |
-
elif key in self.LIST_KEYS:
|
192 |
-
data[key] = [value]
|
193 |
-
elif key in self.SIMPLE_KEYS:
|
194 |
-
data[key] = value
|
195 |
-
elif key in self.IGNORE_KEYS:
|
196 |
-
continue
|
197 |
-
else:
|
198 |
-
logger.info(f"Ignoring key {key} from {parentElement.tag}")
|
199 |
-
self.IGNORE_KEYS.add(key)
|
200 |
-
|
201 |
-
# Filling defaults
|
202 |
-
if parentElement.tag == "MeshHeading" and "QualifierName" not in data:
|
203 |
-
data["QualifierName"] = ""
|
204 |
-
elif parentElement.tag == "Author":
|
205 |
-
if "ForeName" not in data:
|
206 |
-
data["ForeName"] = ""
|
207 |
-
if "Initials" not in data:
|
208 |
-
data["Initials"] = ""
|
209 |
-
if "LastName" not in data:
|
210 |
-
data["LastName"] = ""
|
211 |
-
if "CollectiveName" not in data:
|
212 |
-
data["CollectiveName"] = ""
|
213 |
-
elif parentElement.tag == "JournalIssue":
|
214 |
-
if "Volume" not in data:
|
215 |
-
data["Volume"] = ""
|
216 |
-
if "Issue" not in data:
|
217 |
-
data["Issue"] = ""
|
218 |
-
elif parentElement.tag == "Grant" and "GrantID" not in data:
|
219 |
-
data["GrantID"] = ""
|
220 |
-
|
221 |
-
return {parentElement.tag: data}
|
222 |
-
|
223 |
-
def _info(self):
|
224 |
-
Date = {
|
225 |
-
"Year": datasets.Value("int32"),
|
226 |
-
"Month": datasets.Value("int32"),
|
227 |
-
"Day": datasets.Value("int32"),
|
228 |
-
}
|
229 |
-
|
230 |
-
MeshHeading = {"DescriptorName": datasets.Value("string"), "QualifierName": datasets.Value("string")}
|
231 |
-
|
232 |
-
MedlineJournalInfo = {
|
233 |
-
"Country": datasets.Value("string"),
|
234 |
-
# Too inconsistent
|
235 |
-
# 'MedlineTA': datasets.Value('string'),
|
236 |
-
# 'NlmUniqueID': datasets.Value('string'),
|
237 |
-
# 'ISSNLinking': datasets.Value('string'),
|
238 |
-
}
|
239 |
-
Chemical = {
|
240 |
-
"RegistryNumber": datasets.Value("string"),
|
241 |
-
"NameOfSubstance": datasets.Value("string"),
|
242 |
-
}
|
243 |
-
# Too inconsistent in the data to be used
|
244 |
-
# Journal = {
|
245 |
-
# 'ISSN': datasets.Value('string'),
|
246 |
-
# 'JournalIssue': {
|
247 |
-
# 'Volume': datasets.Value('string'),
|
248 |
-
# 'Issue': datasets.Value('string'),
|
249 |
-
# },
|
250 |
-
# # 'PubDate': Date,
|
251 |
-
# 'Title': datasets.Value('string'),
|
252 |
-
# 'ISOAbbreviation': datasets.Value('string')
|
253 |
-
# }
|
254 |
-
Author = {
|
255 |
-
"LastName": datasets.Value("string"),
|
256 |
-
"ForeName": datasets.Value("string"),
|
257 |
-
"Initials": datasets.Value("string"),
|
258 |
-
"CollectiveName": datasets.Value("string"),
|
259 |
-
}
|
260 |
-
Reference = {
|
261 |
-
"Citation": datasets.Value("string"),
|
262 |
-
"CitationId": datasets.Value("int32"),
|
263 |
-
}
|
264 |
-
Grant = {
|
265 |
-
"GrantID": datasets.Value("string"),
|
266 |
-
"Agency": datasets.Value("string"),
|
267 |
-
"Country": datasets.Value("string"),
|
268 |
-
}
|
269 |
-
Article = {
|
270 |
-
# 'Journal': Journal,
|
271 |
-
"Abstract": {"AbstractText": datasets.Value("string")},
|
272 |
-
"ArticleTitle": datasets.Value("string"),
|
273 |
-
# Too inconistent
|
274 |
-
# 'Pagination': {'MedlinePgn': datasets.Value('string')},
|
275 |
-
"AuthorList": {"Author": datasets.Sequence(Author)},
|
276 |
-
"Language": datasets.Value("string"),
|
277 |
-
"GrantList": {
|
278 |
-
"Grant": datasets.Sequence(Grant),
|
279 |
-
},
|
280 |
-
"PublicationTypeList": {"PublicationType": datasets.Sequence(datasets.Value("string"))},
|
281 |
-
}
|
282 |
-
features = datasets.Features(
|
283 |
-
{
|
284 |
-
"MedlineCitation": {
|
285 |
-
"PMID": datasets.Value("int32"),
|
286 |
-
"DateCompleted": Date,
|
287 |
-
"NumberOfReferences": datasets.Value("int32"),
|
288 |
-
"DateRevised": Date,
|
289 |
-
"Article": Article,
|
290 |
-
"MedlineJournalInfo": MedlineJournalInfo,
|
291 |
-
"ChemicalList": {"Chemical": datasets.Sequence(Chemical)},
|
292 |
-
"CitationSubset": datasets.Value("string"),
|
293 |
-
"MeshHeadingList": {
|
294 |
-
"MeshHeading": datasets.Sequence(MeshHeading),
|
295 |
-
},
|
296 |
-
},
|
297 |
-
"PubmedData": {
|
298 |
-
"ArticleIdList": datasets.Sequence({"ArticleId": datasets.Sequence(datasets.Value("string"))}),
|
299 |
-
"PublicationStatus": datasets.Value("string"),
|
300 |
-
"History": {"PubMedPubDate": datasets.Sequence(Date)},
|
301 |
-
"ReferenceList": datasets.Sequence(Reference),
|
302 |
-
},
|
303 |
-
}
|
304 |
-
)
|
305 |
-
self.fill_keys_from_features(features)
|
306 |
-
return datasets.DatasetInfo(
|
307 |
-
description=_DESCRIPTION,
|
308 |
-
features=features,
|
309 |
-
homepage=_HOMEPAGE,
|
310 |
-
license=_LICENSE,
|
311 |
-
citation=_CITATION,
|
312 |
-
)
|
313 |
-
|
314 |
-
def _split_generators(self, dl_manager):
|
315 |
-
"""Returns SplitGenerators."""
|
316 |
-
dl_dir = dl_manager.download(_URLs)
|
317 |
-
return [
|
318 |
-
datasets.SplitGenerator(
|
319 |
-
name=datasets.Split.TRAIN,
|
320 |
-
gen_kwargs={"filenames": dl_dir},
|
321 |
-
),
|
322 |
-
]
|
323 |
-
|
324 |
-
def update_citation(self, article):
|
325 |
-
"""
|
326 |
-
ArticleId and ArticleIdList are already used field name so we rewrite and
|
327 |
-
flatten those as {Citation, CitationId}.
|
328 |
-
"""
|
329 |
-
citations = []
|
330 |
-
try:
|
331 |
-
list_ = article["PubmedData"]["ReferenceList"]
|
332 |
-
except Exception:
|
333 |
-
return
|
334 |
-
|
335 |
-
for ref in list_:
|
336 |
-
if "Reference" not in ref:
|
337 |
-
continue
|
338 |
-
for re in ref["Reference"]:
|
339 |
-
if "Citation" not in re:
|
340 |
-
continue
|
341 |
-
citation = re["Citation"]
|
342 |
-
if "ArticleIdList" not in re:
|
343 |
-
continue
|
344 |
-
for r in re["ArticleIdList"]:
|
345 |
-
if "ArticleId" not in r:
|
346 |
-
continue
|
347 |
-
for rr in r["ArticleId"]:
|
348 |
-
try:
|
349 |
-
citation = {"Citation": citation, "CitationId": int(rr)}
|
350 |
-
except Exception:
|
351 |
-
continue
|
352 |
-
citations.append(citation)
|
353 |
-
article["PubmedData"]["ReferenceList"] = citations
|
354 |
-
|
355 |
-
def _generate_examples(self, filenames):
|
356 |
-
"""Yields examples."""
|
357 |
-
id_ = 0
|
358 |
-
for filename in filenames:
|
359 |
-
with gzip.open(filename) as f:
|
360 |
-
try:
|
361 |
-
tree = ET.parse(f)
|
362 |
-
root = tree.getroot()
|
363 |
-
xmldict = self.xml_to_dictionnary(root)
|
364 |
-
except ET.ParseError:
|
365 |
-
logger.warning(f"Ignoring file {filename}, it is malformed")
|
366 |
-
continue
|
367 |
-
|
368 |
-
for article in xmldict["PubmedArticleSet"]["PubmedArticle"]:
|
369 |
-
self.update_citation(article)
|
370 |
-
new_article = default_article()
|
371 |
-
|
372 |
-
try:
|
373 |
-
deepupdate(new_article, article)
|
374 |
-
except Exception:
|
375 |
-
logger.warning(f"Ignoring article {article}, it is malformed")
|
376 |
-
continue
|
377 |
-
|
378 |
-
try:
|
379 |
-
_ = self.info.features.encode_example(new_article)
|
380 |
-
except Exception as e:
|
381 |
-
logger.warning(f"Ignore example because {e}")
|
382 |
-
continue
|
383 |
-
yield id_, new_article
|
384 |
-
id_ += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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