ncoop57 commited on
Commit
2a82acd
1 Parent(s): 7311d76

Add datasets loader script

Browse files
Files changed (1) hide show
  1. athena_data.py +233 -0
athena_data.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """TODO: Add a description here."""
16
+
17
+ import ast
18
+ import csv
19
+ import datasets
20
+ import function_parser
21
+ import json
22
+ import os
23
+ import sys
24
+
25
+ csv.field_size_limit(sys.maxsize)
26
+
27
+ from function_parser.language_data import LANGUAGE_METADATA
28
+ from function_parser.parsers.java_parser import JavaParser
29
+ from function_parser.process import DataProcessor
30
+ from git import Git, Repo
31
+ from glob import glob
32
+ from tree_sitter import Language
33
+
34
+ LANG = "java"
35
+ JAVA_LANG = Language(
36
+ os.path.join(function_parser.__path__[0], "tree-sitter-languages.so"), LANG
37
+ )
38
+ DataProcessor.PARSER.set_language(JAVA_LANG)
39
+ FUNC_PROCESSOR = DataProcessor(
40
+ language=LANG, language_parser=LANGUAGE_METADATA[LANG]["language_parser"]
41
+ )
42
+
43
+ # TODO: Add BibTeX citation
44
+ # Find for instance the citation on arxiv or on the dataset repo/website
45
+ _CITATION = """\
46
+ @InProceedings{huggingface:dataset,
47
+ title = {A great new dataset},
48
+ author={huggingface, Inc.
49
+ },
50
+ year={2020}
51
+ }
52
+ """
53
+
54
+ # TODO: Add description of the dataset here
55
+ # You can copy an official description
56
+ _DESCRIPTION = """\
57
+ This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
58
+ """
59
+
60
+ # TODO: Add a link to an official homepage for the dataset here
61
+ _HOMEPAGE = ""
62
+
63
+ # TODO: Add the licence for the dataset here if you can find it
64
+ _LICENSE = ""
65
+
66
+ # TODO: Add link to the official dataset URLs here
67
+ # The HuggingFace dataset library don't host the datasets but only point to the original files
68
+ # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
69
+ _URL = "https://huggingface.co/datasets/ncoop57/athena_data/resolve/main/repos-commits.zip"
70
+
71
+
72
+ # TODO: Name of the dataset usually match the script name with CamelCase instead of snake_case
73
+ class NewDataset(datasets.GeneratorBasedBuilder):
74
+ """TODO: Short description of my dataset."""
75
+
76
+ VERSION = datasets.Version("1.1.0")
77
+
78
+ # This is an example of a dataset with multiple configurations.
79
+ # If you don't want/need to define several sub-sets in your dataset,
80
+ # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.
81
+
82
+ # If you need to make complex sub-parts in the datasets with configurable options
83
+ # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
84
+ # BUILDER_CONFIG_CLASS = MyBuilderConfig
85
+
86
+ # You will be able to load one or the other configurations in the following list with
87
+ # data = datasets.load_dataset('my_dataset', 'first_domain')
88
+ # data = datasets.load_dataset('my_dataset', 'second_domain')
89
+ BUILDER_CONFIGS = [
90
+ datasets.BuilderConfig(name="meta_data", version=VERSION, description="This part of my dataset covers a first domain"),
91
+ datasets.BuilderConfig(name="repos_commits", version=VERSION, description="This part of my dataset covers a second domain"),
92
+ ]
93
+
94
+ DEFAULT_CONFIG_NAME = "meta_data" # It's not mandatory to have a default configuration. Just use one if it make sense.
95
+
96
+ def _info(self):
97
+ # TODO: This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset
98
+ if self.config.name == "meta_data": # This is the name of the configuration selected in BUILDER_CONFIGS above
99
+ features = datasets.Features(
100
+ {
101
+ "repo": datasets.Value("string"),
102
+ "parent_commit": datasets.Value("string"),
103
+ "commit": datasets.Value("string"),
104
+ "changes": datasets.Sequence(datasets.Sequence(datasets.Value("string"))),
105
+ # These are the features of your dataset like images, labels ...
106
+ }
107
+ )
108
+ elif self.config.name == "repos_commits":
109
+ features = datasets.Features(
110
+ {
111
+ "repo": datasets.Value("string"),
112
+ "parent_commit": datasets.Value("string"),
113
+ "commit": datasets.Value("string"),
114
+ "changes": datasets.Sequence(datasets.Value("string")),
115
+ "file_path": datasets.Value("string"),
116
+ "code": datasets.Value("string"),
117
+ "code_tokens": datasets.Sequence(datasets.Value("string")),
118
+ "docstring": datasets.Value("string"),
119
+ }
120
+ )
121
+ return datasets.DatasetInfo(
122
+ # This is the description that will appear on the datasets page.
123
+ description=_DESCRIPTION,
124
+ # This defines the different columns of the dataset and their types
125
+ features=features, # Here we define them above because they are different between the two configurations
126
+ # If there's a common (input, target) tuple from the features,
127
+ # specify them here. They'll be used if as_supervised=True in
128
+ # builder.as_dataset.
129
+ supervised_keys=None,
130
+ # Homepage of the dataset for documentation
131
+ homepage=_HOMEPAGE,
132
+ # License for the dataset if available
133
+ license=_LICENSE,
134
+ # Citation for the dataset
135
+ citation=_CITATION,
136
+ )
137
+
138
+ def _split_generators(self, dl_manager):
139
+ """Returns SplitGenerators."""
140
+ # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
141
+ # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
142
+
143
+ # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs
144
+ # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
145
+ # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
146
+ data_dir = dl_manager.download_and_extract(_URL)
147
+ data_dir = os.path.join(data_dir, "repos-commits")
148
+ if self.config.name == "repos_commits" and not os.path.exists(os.path.join(data_dir, "repos")):
149
+ # Clone all repositories
150
+ check_output(
151
+ [
152
+ "bash",
153
+ "clone.sh",
154
+ "repo_names.txt",
155
+ ],
156
+ cwd=data_dir,
157
+ )
158
+ return [
159
+ datasets.SplitGenerator(
160
+ name=datasets.Split.TRAIN,
161
+ # These kwargs will be passed to _generate_examples
162
+ gen_kwargs={
163
+ "data_dir": data_dir,
164
+ "file_path": os.path.join(data_dir, "processed_impact_methods.csv"),
165
+ },
166
+ ),
167
+ ]
168
+
169
+ def _generate_examples(
170
+ self, data_dir, file_path # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
171
+ ):
172
+ """ Yields examples as (key, example) tuples. """
173
+ # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
174
+ # The `key` is here for legacy reason (tfds) and is not important in itself.
175
+ with open(file_path, encoding="utf-8") as f:
176
+ csv_reader = csv.reader(f, quotechar='"', delimiter=",", quoting=csv.QUOTE_ALL, skipinitialspace=True)
177
+ next(csv_reader, None) # skip header
178
+ for row_id, row in enumerate(csv_reader):
179
+ repo, parent_commit, commit, changes = row
180
+ changes = ast.literal_eval(changes)
181
+ # print(changes)
182
+ if self.config.name == "meta_data":
183
+ yield row_id, {
184
+ "repo": repo,
185
+ "parent_commit": parent_commit,
186
+ "commit": commit,
187
+ "changes": changes,
188
+ }
189
+ elif self.config.name == "repos_commits":
190
+ repo_path = os.path.join(data_dir, "repos", repo)
191
+ # Otherwise, parse the project
192
+ g = Git(repo_path)
193
+ g.checkout(self.commit)
194
+
195
+ indexes = []
196
+ files = glob(f"{repo_path}/**/*.{LANGUAGE_METADATA[LANG]['ext']}")
197
+ sha = None
198
+ for f in files:
199
+ definitions = FUNC_PROCESSOR.get_function_definitions(str(f))
200
+ if definitions is None:
201
+ continue
202
+
203
+ nwo, path, functions = definitions
204
+ indexes.extend(
205
+ (
206
+ FUNC_PROCESSOR.extract_function_data(func, nwo, path, sha)
207
+ for func in functions
208
+ if len(func["function_tokens"]) > 1
209
+ )
210
+ )
211
+
212
+ df = pd.DataFrame(indexes)[
213
+ ["path", "function", "function_tokens", "docstring"]
214
+ ].rename(
215
+ columns={
216
+ "path": "file_path",
217
+ "function": "code",
218
+ "function_tokens": "code_tokens",
219
+ "docstring": "docstring",
220
+ }
221
+ )
222
+ for _, row in df.iterrows():
223
+ yield row_id, {
224
+ "repo": repo,
225
+ "parent_commit": parent_commit,
226
+ "commit": commit,
227
+ "changes": changes,
228
+ "file_path": row["file_path"],
229
+ "code": row["code"],
230
+ "code_tokens": row["code_tokens"],
231
+ "docstring": row["docstring"],
232
+ }
233
+ data = pd.concat([repo.definitions for repo in self.repos])