# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This dataset script is based on pmc/open_access.py loading script. """PMC Open Access Subset of figures with captions""" from huggingface_hub import hf_hub_url import datetime import pandas as pd import numpy as np from itertools import compress, chain from collections import defaultdict import os import re from lxml import etree import unicodedata import html import json from PIL import Image import tarfile import datasets from datasets.tasks import LanguageModeling from PIL import ImageFile # Important for error: UserWarning: Corrupt EXIF data. Expecting to read 4 bytes but only got 0 import mimetypes ImageFile.LOAD_TRUNCATED_IMAGES = True # TODO: Add BibTeX citation # Find for instance the citation on arxiv or on the dataset repo/website _CITATION = "" _DESCRIPTION = """\ The PMC Open Access Subset includes more than 3.4 million journal articles and preprints that are made available under license terms that allow reuse. Not all articles in PMC are available for text mining and other reuse, many have copyright protection, however articles in the PMC Open Access Subset are made available under Creative Commons or similar licenses that generally allow more liberal redistribution and reuse than a traditional copyrighted work. The PMC Open Access Subset is one part of the PMC Article Datasets This version focus on associating the graphics of figures with their captions """ _HOMEPAGE = "https://www.ncbi.nlm.nih.gov/pmc/tools/openftlist/" # TODO: Add the licence for the dataset here if you can find it _LICENSE = """ https://www.ncbi.nlm.nih.gov/pmc/about/copyright/ Within the PMC Open Access Subset, there are three groupings: Commercial Use Allowed - CC0, CC BY, CC BY-SA, CC BY-ND licenses Non-Commercial Use Only - CC BY-NC, CC BY-NC-SA, CC BY-NC-ND licenses; and Other - no machine-readable Creative Commons license, no license, or a custom license. """ _URL_ROOT = "https://ftp.ncbi.nlm.nih.gov/pub/pmc/" _URL = _URL_ROOT+"oa_bulk/{subset}/xml/" _SUBSETS = { "commercial": "oa_comm", "non_commercial": "oa_noncomm", "other": "oa_other", } _BASELINE_DATE = "2023-12-18" begin_doc_rgx = re.compile("""0)] baseline_file_list_l.extend(dl_manager.download(baseline_file_list_urls)) #date_delta = datetime.date.today() - datetime.date.fromisoformat(_BASELINE_DATE) #incremental_dates = [ # (datetime.date.fromisoformat(_BASELINE_DATE) + datetime.timedelta(days=i + 1)).isoformat() # for i in range(date_delta.days) # ] #incremental_urls = [f"{url}{basename}incr.{date}.filelist.csv" for date in incremental_dates] #for url in incremental_urls: # try: # incremental_file_list_l.append(dl_manager.download(url)) # except FileNotFoundError: # Some increment don't exist # continue oa_package_list = pd.read_csv(baseline_package_list, index_col="Accession ID") oa_package_list = oa_package_list[["File"]] figure_archives = [] df_l = [] set_article = set() for l, baseline_file_list in enumerate(baseline_file_list_l): # incremental_file_list_l[::-1] + try: file_list = pd.read_csv(baseline_file_list, index_col="AccessionID") except FileNotFoundError: # File not found can happen here in stream mode continue file_list = file_list.join(oa_package_list).reset_index().set_index("Article File") file_list.File = file_list.File.fillna('') #mask = (~file_list.File.isin(set_article)) & (file_list.File!="") #file_list = file_list[mask] figure_url_l = list(_URL_ROOT + file_list.File) #[f"{_URL_ROOT}{figure_path}" for figure_path in file_list.File] #try figure_archives.append(dl_manager.download(figure_url_l)) #if l < len(incremental_file_list_l): # Only adding the incrementals to the list, the rest don't have overlap in pmid # set_article.union(file_list.File[slc_]) df_l.append(file_list) #except FileNotFoundError: # continue package_df = pd.concat(df_l).reset_index() figure_archives = list(chain(*figure_archives)) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "figure_archive_lists": self.archive_generator(dl_manager, figure_archives, "train"), "package_df": package_df[np.arange(len(package_df))%10 < 8], }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "figure_archive_lists": self.archive_generator(dl_manager, figure_archives, "test"), "package_df": package_df[np.arange(len(package_df))%10 == 8], }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "figure_archive_lists": self.archive_generator(dl_manager, figure_archives, "validation"), "package_df": package_df[np.arange(len(package_df))%10 == 9], }, ), ] def archive_generator(self, dl_manager, figure_archives, name): if name == "train": for k, archive in enumerate(figure_archives): if k%10 < 8: yield dl_manager.iter_archive(archive) elif name == "test": for k, archive in enumerate(figure_archives[8::10]): yield dl_manager.iter_archive(archive) elif name == "validation": for k, archive in enumerate(figure_archives[9::10]): yield dl_manager.iter_archive(archive) def _generate_examples(self, figure_archive_lists, package_df): #Loading the file listing folders of individual PMC Article package (with medias and graphics) for i, figure_archive in enumerate(figure_archive_lists): data = package_df.iloc[i] f_d = defaultdict(lambda: {}) file_xml = None try: for path, file in figure_archive: bn, ext = os.path.splitext(os.path.basename(path)) if ext in [".nxml", ".xml"]: content = file.read() try: text = content.decode("utf-8").strip() except UnicodeDecodeError as e: text = content.decode("latin-1").strip() text = clean_raw(text) article_tree = etree.ElementTree(etree.fromstring(text)) figure_captions, graphic_names = extract_captions(article_tree) break for path, file in figure_archive: bn, ext = os.path.splitext(os.path.basename(path)) if ext in IMAGE_EXT and bn in graphic_names: f_d[ext][bn] = Image.open(file, mode="r") image_d = {} for ext in [".tif", ".jpg", ".png", ".gif"]: for bn, image in f_d[ext].items(): if bn not in image_d.keys(): image_d[bn] = image for j, (caption, graph_name) in enumerate(zip(figure_captions, graphic_names)): if graph_name in image_d.keys(): yield (f"{data['AccessionID']}_{str(j+1)}", {"figure": image_d[graph_name], "caption":caption, "pmid": data["PMID"], "accession_id": data['AccessionID'], "figure_idx": j+1, "figure_fn": graph_name, "license": data["License"], "last_updated": data["LastUpdated (YYYY-MM-DD HH:MM:SS)"], "retracted": data["Retracted"], "citation": data["Article Citation"]}) except: # (etree.XMLSyntaxError, tarfile.ReadError) In some files, xml is broken, and tarfile readerror may happen continue