File size: 6,503 Bytes
97afcd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12ff1d7
 
 
97afcd5
 
9266c56
97afcd5
989a2eb
97afcd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8f27d6
97afcd5
12ff1d7
97afcd5
b8f27d6
97afcd5
 
 
 
 
 
12ff1d7
ad82678
97afcd5
12ff1d7
 
 
989a2eb
12ff1d7
 
 
 
 
989a2eb
 
12ff1d7
5c2759b
 
 
 
 
 
 
 
 
 
 
12ff1d7
 
 
 
 
 
5c2759b
 
 
 
2333daa
12ff1d7
97afcd5
 
12ff1d7
97afcd5
12ff1d7
8d2c030
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97afcd5
83b8603
97afcd5
 
12ff1d7
14f404d
 
4c55267
 
 
 
 
 
14f404d
 
97afcd5
 
12ff1d7
97afcd5
12ff1d7
97afcd5
12ff1d7
 
 
 
 
97afcd5
12ff1d7
97afcd5
 
 
 
 
12ff1d7
 
 
2ec3211
12ff1d7
5c2759b
97afcd5
 
 
12ff1d7
97afcd5
9266c56
97afcd5
 
 
 
 
 
9266c56
97afcd5
 
 
 
 
 
9266c56
97afcd5
 
 
 
 
2664600
12ff1d7
 
2664600
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# 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