-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathget_developer_stats.py
More file actions
220 lines (176 loc) · 6.81 KB
/
get_developer_stats.py
File metadata and controls
220 lines (176 loc) · 6.81 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
#! /usr/bin/env python
# example usage
# import src as CoreEngine
#
# You will need:
# - `main.db`. Default: ./output/main.db`
# - `ai_result_backup.db`. Default: ./output/ai_result_backup.db
# - trained model file. Default: `./output/rf_model.pkl`
# - domain_labels.json and subdomain_labels.json file.
# Default: `./data/domain_labels.json`, `./data/subdomain_labels.json`
# - configuration file: Default: None
import requests
import argparse
import os
import time
from dotenv import load_dotenv
import pandas as pd
import tqdm
import src as CoreEngine
load_dotenv()
# Override the Issue class to track the developer who closed the issue.
# Likewise, update the get issue function to fill in the developer fields
class _Issue(CoreEngine.issue_class.Issue):
def __init__(self, number: int,
title: str,
body: str = "",
dev_name: str = "",
dev_id: str = "" ):
super().__init__(number, title, body)
self.dev_name = dev_name
self.dev_id = dev_id
def get_issues(owner, repo, access_token, open_issues=True, max_count=None):
data = []
# GitHub API URL for fetching issues
url = f"https://api.github.com/repos/{owner}/{repo}/issues"
# Headers for authentication
if access_token is not None:
headers = {
"Authorization": f"token {access_token}",
"Accept": "application/vnd.github.v3+json",
}
else:
headers = { "Accept": "application/vnd.github.v3+json" }
if max_count is None: page_q = 100
else: page_q = 20
if open_issues:
params = {
"state": "open",
"per_page": page_q, # Number of issues per page (maximum is 100)
"page": 1, # Page number to start fetching from
}
else:
params = {
"state": "closed",
"per_page": page_q, # Number of issues per page (maximum is 100)
"page": 1, # Page number to start fetching from
}
issues = []
while True:
# fetch issues until error. When no max_count supplied
response = requests.get(url, headers=headers, params=params)
if response.status_code != 200:
print(f"Error: {response.status_code}")
break
issues_page = response.json()
if not issues_page:
break
issues.extend(issues_page)
if max_count is not None and max_count // page_q < params["page"]:
break
params["page"] += 1
# Add extracted issues to dataframe
for i in issues:
if i["body"] is None:
i["body"] = ""
cur_issue = _Issue( i["number"], i["title"],
i["body"], i["user"]["login"],
i["user"]["id"] )
data.append(cur_issue)
print(f"Total issues fetched: {len(issues)}")
return data
def get_cli_args():
"""
Get initializing arguments from CLI.
Returns:
str: path to file with arguments to program
"""
# establish positional argument capability
arg_parser = argparse.ArgumentParser( description="Get developer expertise"
"from contribution history")
# add repo input CLI arg
arg_parser.add_argument( "extractor_cfg_file", help="Path to JSON"
"configuration file")
args = arg_parser.parse_args()
return args.extractor_cfg_file
def get_developer_stats( repo_owner,
repo_name,
access_token, # github access token
openai_key, # open ai api key
limit ): # how many issues to mine
db = CoreEngine.DatabaseManager(
dbfile="./output/main.db",
cachefile="./ai_result_backup.db",
label_file="./data/subdomain_labels.json",
)
# Get the model (RF) The model is automatically detected by the model file.
external_rf = CoreEngine.External_Model_Interface(
openai_key,
db,
"./output/rf_model.pkl",
"./data/domain_labels.json",
"./data/subdomain_labels.json",
"./data/formatted_domain_labels.json",
f"example cache key-{repo_name}",
"./output/response_cache/",
)
data_out = {
"Issue Number": [],
"Issue Title": [],
"Issue Body": [],
"Is Open": [],
"RF Predictions": [],
"developer_name": [],
"developer_id": [],
}
print('Fetching closed issues...')
# Get closed issues
issues = get_issues(
owner=repo_owner,
repo=repo_name,
open_issues=False,
access_token=access_token,
max_count = limit,
)
print(f"Classifying {len(issues)} closed issues....")
for issue in tqdm.tqdm(issues, leave=False):
# issue is of type CoreEngine.Issue, issues closed.
try:
prediction_rf = external_rf.predict_issue(issue)
except:
continue
data_out["Issue Number"].append(issue.number)
data_out["Issue Title"].append(issue.title)
data_out["Issue Body"].append(issue.body.replace('"', "'"))
data_out["Is Open"].append(False)
data_out["RF Predictions"].append(prediction_rf)
# get developer information for each solved issue
data_out["developer_name"].append( issue.dev_name )
data_out["developer_id"].append( issue.dev_id )
data = pd.DataFrame(data=data_out)
data["Issue Body"] = data["Issue Body"].apply(CoreEngine.classifier.clean_text)
# # save the issues fetched, and their domain labels
# with open(f"output/{repo_owner}_{repo_name}_issue_extract.csv", "w") as file:
# data.to_csv(file)
# get the developer <--> domain <--> frequency mapping
df = data.explode('RF Predictions')
df = df.groupby( ['developer_name', 'developer_id', 'RF Predictions'] ).size().reset_index(name='frequency')
df = df.sort_values( by=[ 'developer_name', 'developer_id', 'frequency'], ascending=False )
df.rename( columns = {'RF Predictions': 'Domain'}, inplace=True )
# with open( f'output/{repo_owner}_{repo_name}_developer_information.csv', "w" ) as f:
# df.to_csv( f, index = False )
db.close()
return df
######## FOR USE FROM CLI #########
if __name__ == "__main__":
cfg_path = get_cli_args()
cfg_dict = CoreEngine.utils.read_jsonfile_into_dict(cfg_path)
repo_owner = cfg_dict["repo_owner"]
repo_name = cfg_dict["repo_name"]
access_token = cfg_dict["github_token"]
openai_key = cfg_dict["openai_key"]
limit = int(cfg_dict["limit"])
df = get_developer_stats( repo_owner, repo_name, access_token, openai_key,
limit )
with open( f'output/{repo_owner}_{repo_name}_developer_information.csv', "w" ) as f:
df.to_csv( f, index = False )