ncoop57 commited on
Commit
0d05dc9
2 Parent(s): 132f788 b05f041

Merge branch 'main' of https://huggingface.co/datasets/ncoop56/athena_data into main

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