testdataset / testdataset.py
thomasyu888's picture
Update testdataset.py
12ff1d7
# coding=utf-8
# Copyright 2022 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 implementation specifies a custom synapse download function that allows
users to leverage the HF datasets API to download files through the Synapse API given
Synapse authentication
"""
import csv
import os
from dataclasses import dataclass
from typing import Dict, List, Tuple
import datasets
_LANGUAGES = ["English"]
_PUBMED = False
_LOCAL = True
_DATASETNAME = "testdataset"
_DISPLAYNAME = "TESTDATASET"
_DESCRIPTION = """\
Test Dataset
"""
_CITATION = ""
_HOMEPAGE = "https://www.synapse.org/#!Synapse:syn51520471"
_LICENSE = "other"
_URLS = {}
_SOURCE_VERSION = "1.0.0"
_BIGBIO_VERSION = "1.0.0"
# This must be a synapse id of a synapse folder or project
_SYN_ID = "syn51520473"
# @dataclass
# class BigBioConfig(datasets.BuilderConfig):
# """BuilderConfig for BigBio."""
# name: str = None
# version: datasets.Version = None
# description: str = None
# schema: str = None
# subset_id: str = None
def download_from_synapse(syn_id: str, path: str):
"""Download files from a Synapse folder or project containing test, train, dev csv files
Args:
syn_id: Synapse Id of a folder or project
path: path to download files
"""
try:
import synapseclient
import synapseutils
except ModuleNotFoundError as e:
raise ModuleNotFoundError("synapseclient must be installed. pip install synapseclient")
try:
syn = synapseclient.login()
except Exception:
raise Exception("Please create a Synapse personal access token and either set up ~/.synapseConfig or `export SYNAPSE_AUTH_TOKEN=<PAT>`")
synapseutils.syncFromSynapse(syn, syn_id, path=path)
# syn.get(entity=syn_id, downloadLocation=path)
class TestDataset(datasets.GeneratorBasedBuilder):
"""Test Dataset"""
SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
# BIGBIO_VERSION = datasets.Version(_BIGBIO_VERSION)
# TODO: Add in builder configs
# BUILDER_CONFIGS = [
# BigBioConfig(
# name="default",
# version=SOURCE_VERSION,
# description="test dataset source schema",
# schema="source",
# subset_id="testdataset",
# ),
# BigBioConfig(
# name="testdataset_te",
# version=BIGBIO_VERSION,
# description="test dataset BigBio schema",
# schema="testdataset_te",
# subset_id="testdataset",
# ),
# ]
DEFAULT_CONFIG_NAME = "testdataset_source"
def _info(self) -> datasets.DatasetInfo:
# TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
features = datasets.Features(
{
"id": datasets.Value("string"),
"package_name": datasets.Value("string"),
"review": datasets.Value("string"),
"date": datasets.Value("string"),
"star": datasets.Value("string"),
"version_id": datasets.Value("string")
}
)
return datasets.DatasetInfo(
# This is the description that will appear on the datasets page.
description=_DESCRIPTION,
# This defines the different columns of the dataset and their types
features=features,
# Here we define them above because they are different between the two configurations
# If there's a common (input, target) tuple from the features, uncomment supervised_keys line below and
# specify them. They'll be used if as_supervised=True in builder.as_dataset.
# supervised_keys=("sentence", "label"),
# Homepage of the dataset for documentation
homepage=_HOMEPAGE,
# License for the dataset if available
license=str(_LICENSE),
citation=_CITATION,
)
def _split_generators(self, dl_manager) -> List[datasets.SplitGenerator]:
# TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
# If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
# This is where we can call the custom download function for Synapse
# https://huggingface.co/docs/datasets/v2.12.0/en/package_reference/builder_classes#datasets.DownloadManager.download_custom
data_dir = dl_manager.download_custom(_SYN_ID, download_from_synapse)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
# These kwargs will be passed to _generate_examples
gen_kwargs={
"filepath": os.path.join(data_dir, "train.csv"),
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepath": os.path.join(data_dir, "test.csv"),
"split": "test",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"filepath": os.path.join(data_dir, "dev.csv"),
"split": "dev",
},
),
]
def _generate_examples(self, filepath, split: str) -> Tuple[int, Dict]:
# TODO: This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
# The `row['id']` is for legacy reasons (tfds) and is not important in itself, but must be unique for each example.
with open(filepath, "r") as f:
test = csv.DictReader(f)
for row in test:
yield row['id'], row