File size: 6,883 Bytes
7e57faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd7c1f2
966942a
7e57faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f9b4f
7e57faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78df896
7e57faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33f9b4f
7e57faa
 
 
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
# 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.
"""TODO: Add a description here."""


import csv
import json
import os

import datasets
import pickle 
from pathlib import Path

# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """
@inproceedings{
dahal2022scotch,
title={Scotch: A Semantic Code Search Engine for {IDE}s},
author={Samip Dahal and Adyasha Maharana and Mohit Bansal},
booktitle={Deep Learning for Code Workshop},
year={2022},
url={https://openreview.net/forum?id=rSxfCiOZk-c}
}
"""

# TODO: Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
Scotch is a dataset of about 19 million functions collected from open-source repositiories from GitHub with permissive licenses. Each function has its corresponding code context and about 4 million functions have corresponding docstrings. The dataset includes functions written in programming languages Python, Java, Javascript, and Go."""

# TODO: Add a link to an official homepage for the dataset here
_HOMEPAGE = "https://github.com/sdpmas/Scotch"

# TODO: Add the licence for the dataset here if you can find it
_LICENSE = "The MIT License"

# TODO: Add link to the official dataset URLs here
# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
languages=['python','javascript','java','go']
language_map={'python':'py','javascript':'js','go':'go','java':'java'}
_URLs = {lang:f'https://scotchdata.s3.amazonaws.com/{lang}.tar.gz' for lang in languages}
_URLs['all']=_URLs.copy()


# TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
class ScotchDataset(datasets.GeneratorBasedBuilder):
    VERSION = datasets.Version("1.0.0")
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="all", version=VERSION, description="All available data with docstrings"),
        datasets.BuilderConfig(name="python", version=VERSION, description="Python data"),
        datasets.BuilderConfig(name="javascript", version=VERSION, description="Javascript data"),
        datasets.BuilderConfig(name="java", version=VERSION, description="Java data"),
        datasets.BuilderConfig(name="go", version=VERSION, description="Go data"),
    ]

    DEFAULT_CONFIG_NAME = "all"

    def _info(self):
        # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
        
        features = datasets.Features(
            {
                "repository_name": datasets.Value("string"),
                "function_path": datasets.Value("string"),
                "function_identifier": datasets.Value("string"),
                "language": datasets.Value("string"),
                "function": datasets.Value("string"),
                "docstring": datasets.Value("string"),
                "function_url": datasets.Value("string"),
                "context":datasets.Value("string"),
                "license":datasets.Value("string"),
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,  # Here we define them above because they are different between the two configurations
            supervised_keys=None,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        my_urls = _URLs[self.config.name]
        if isinstance(my_urls, str):
            my_urls = {self.config.name:my_urls}
        data_dir = [os.path.join(lang_dir,lang) for lang,lang_dir in dl_manager.download_and_extract(my_urls).items()]
        
        # splitpaths={split:[os.path.join(lang_dir,f'{split}.bin') for lang_dir in data_dir] for split in ['train','valid','test']}
        splitpaths={}
        for split in ['train','valid','test']:
            for lang_dir in data_dir:
                # Path glob .bin files
                lang_split_files=sorted(Path(os.path.join(lang_dir,split)).glob('*.bin'))
                if not split in splitpaths:
                    splitpaths[split]=lang_split_files
                else:
                    splitpaths[split].extend(lang_split_files)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": splitpaths['train'],
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": splitpaths['test'],
                    "split": "test"
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                # These kwargs will be passed to _generate_examples
                gen_kwargs={
                    "filepath": splitpaths['valid'],
                    "split": "valid",
                },
            ),
        ]

    def _generate_examples(
        self, filepath,split  # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
    ):
        """ Yields examples as (key, example) tuples. """
        count=-1
        for i,filepath in enumerate(filepath):
            loaded_f=pickle.load(open(filepath,'rb'))
            for j, func in enumerate(loaded_f):
                count+=1
                yield count,{
                    "repository_name": str(func['nwo']),
                    "function_path":str(func['path']),
                    "function_identifier": str(func['identifier']),
                    "language": str(func['language']),
                    "function": str(func['function']),
                    "docstring": str(func['docstring']),
                    "function_url": str(func['url']),
                    "context":str(func['context']),
                    "license":str(func['license']), 
                }