Uh oh!
There was an error while loading. Please reload this page.
forked from tech-srl/code2vec
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
Latest commit
217 lines (188 loc) · 8.95 KB
/
Copy pathcommon.py
File metadata and controls
217 lines (188 loc) · 8.95 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
importre
importnumpyasnp
importtensorflowastf
fromitertoolsimporttakewhile, repeat
fromtypingimportList, Optional, Tuple, Iterable
fromdatetimeimportdatetime
fromcollectionsimportOrderedDict
classcommon:
@staticmethod
defnormalize_word(word):
stripped=re.sub(r'[^a-zA-Z]', '', word)
iflen(stripped) ==0:
returnword.lower()
else:
returnstripped.lower()
@staticmethod
def_load_vocab_from_histogram(path, min_count=0, start_from=0, return_counts=False):
withopen(path, 'r') asfile:
word_to_index= {}
index_to_word= {}
word_to_count= {}
next_index=start_from
forlineinfile:
line_values=line.rstrip().split(' ')
iflen(line_values) !=2:
continue
word=line_values[0]
count=int(line_values[1])
ifcount<min_count:
continue
ifwordinword_to_index:
continue
word_to_index[word] =next_index
index_to_word[next_index] =word
word_to_count[word] =count
next_index+=1
result=word_to_index, index_to_word, next_index-start_from
ifreturn_counts:
result= (*result, word_to_count)
returnresult
@staticmethod
defload_vocab_from_histogram(path, min_count=0, start_from=0, max_size=None, return_counts=False):
ifmax_sizeisnotNone:
word_to_index, index_to_word, next_index, word_to_count= \
common._load_vocab_from_histogram(path, min_count, start_from, return_counts=True)
ifnext_index<=max_size:
results= (word_to_index, index_to_word, next_index)
ifreturn_counts:
results= (*results, word_to_count)
returnresults
# Take min_count to be one plus the count of the max_size'th word
min_count=sorted(word_to_count.values(), reverse=True)[max_size] +1
returncommon._load_vocab_from_histogram(path, min_count, start_from, return_counts)
@staticmethod
defload_json(json_file):
data= []
withopen(json_file, 'r') asfile:
forlineinfile:
current_program=common.process_single_json_line(line)
ifcurrent_programisNone:
continue
forelement, scopeincurrent_program.items():
data.append((element, scope))
returndata
@staticmethod
defload_json_streaming(json_file):
withopen(json_file, 'r') asfile:
forlineinfile:
current_program=common.process_single_json_line(line)
ifcurrent_programisNone:
continue
forelement, scopeincurrent_program.items():
yield (element, scope)
@staticmethod
defsave_word2vec_file(output_file, index_to_word, vocab_embedding_matrix: np.ndarray):
assertlen(vocab_embedding_matrix.shape) ==2
vocab_size, embedding_dimension=vocab_embedding_matrix.shape
output_file.write('%d %d\n'% (vocab_size, embedding_dimension))
forword_idxinrange(0, vocab_size):
assertword_idxinindex_to_word
word_str=index_to_word[word_idx]
output_file.write(word_str+' ')
output_file.write(' '.join(map(str, vocab_embedding_matrix[word_idx])) +'\n')
@staticmethod
defcalculate_max_contexts(file):
contexts_per_word=common.process_test_input(file)
returnmax(
[max(l, default=0) forlin [[len(contexts) forcontextsinprog.values()] forprogincontexts_per_word]],
default=0)
@staticmethod
defbinary_to_string(binary_string):
returnbinary_string.decode("utf-8")
@staticmethod
defbinary_to_string_list(binary_string_list):
return [common.binary_to_string(w) forwinbinary_string_list]
@staticmethod
defbinary_to_string_matrix(binary_string_matrix):
return [common.binary_to_string_list(l) forlinbinary_string_matrix]
@staticmethod
defload_file_lines(path):
withopen(path, 'r') asf:
returnf.read().splitlines()
@staticmethod
defsplit_to_batches(data_lines, batch_size):
forxinrange(0, len(data_lines), batch_size):
yielddata_lines[x:x+batch_size]
@staticmethod
deflegal_method_names_checker(special_words, name):
returnname!=special_words.OOVandre.match(r'^[a-zA-Z|]+$', name)
@staticmethod
deffilter_impossible_names(special_words, top_words):
result=list(filter(lambdaword: common.legal_method_names_checker(special_words, word), top_words))
returnresult
@staticmethod
defget_subtokens(str):
returnstr.split('|')
@staticmethod
defparse_prediction_results(raw_prediction_results, unhash_dict, special_words, topk: int=5) ->List['MethodPredictionResults']:
prediction_results= []
forsingle_method_predictioninraw_prediction_results:
current_method_prediction_results=MethodPredictionResults(single_method_prediction.original_name)
fori, predictedinenumerate(single_method_prediction.topk_predicted_words):
ifpredicted==special_words.OOV:
continue
suggestion_subtokens=common.get_subtokens(predicted)
current_method_prediction_results.append_prediction(
suggestion_subtokens, single_method_prediction.topk_predicted_words_scores[i].item())
topk_attention_per_context= [
(key, single_method_prediction.attention_per_context[key])
forkeyinsorted(single_method_prediction.attention_per_context,
key=single_method_prediction.attention_per_context.get, reverse=True)
][:topk]
forcontext, attentionintopk_attention_per_context:
token1, hashed_path, token2=context
ifhashed_pathinunhash_dict:
unhashed_path=unhash_dict[hashed_path]
current_method_prediction_results.append_attention_path(attention.item(), token1=token1,
path=unhashed_path, token2=token2)
prediction_results.append(current_method_prediction_results)
returnprediction_results
@staticmethod
deftf_get_first_true(bool_tensor: tf.Tensor) ->tf.Tensor:
bool_tensor_as_int32=tf.cast(bool_tensor, dtype=tf.int32)
cumsum=tf.cumsum(bool_tensor_as_int32, axis=-1, exclusive=False)
returntf.logical_and(tf.equal(cumsum, 1), bool_tensor)
@staticmethod
defcount_lines_in_file(file_path: str):
withopen(file_path, 'rb') asf:
bufgen=takewhile(lambdax: x, (f.raw.read(1024*1024) for_inrepeat(None)))
returnsum(buf.count(b'\n') forbufinbufgen)
@staticmethod
defsqueeze_single_batch_dimension_for_np_arrays(arrays):
assertall(arrayisNoneorisinstance(array, np.ndarray) orisinstance(array, tf.Tensor) forarrayinarrays)
returntuple(
NoneifarrayisNoneelsenp.squeeze(array, axis=0)
forarrayinarrays
)
@staticmethod
defget_first_match_word_from_top_predictions(special_words, original_name, top_predicted_words) ->Optional[Tuple[int, str]]:
normalized_original_name=common.normalize_word(original_name)
forsuggestion_idx, predicted_wordinenumerate(common.filter_impossible_names(special_words, top_predicted_words)):
normalized_possible_suggestion=common.normalize_word(predicted_word)
ifnormalized_original_name==normalized_possible_suggestion:
returnsuggestion_idx, predicted_word
returnNone
@staticmethod
defnow_str():
returndatetime.now().strftime("%Y%m%d-%H%M%S: ")
@staticmethod
defchunks(l, n):
"""Yield successive n-sized chunks from l."""
foriinrange(0, len(l), n):
yieldl[i:i+n]
@staticmethod
defget_unique_list(lst: Iterable) ->list:
returnlist(OrderedDict(((item, 0) foriteminlst)).keys())
classMethodPredictionResults:
def__init__(self, original_name):
self.original_name=original_name
self.predictions=list()
self.attention_paths=list()
defappend_prediction(self, name, probability):
self.predictions.append({'name': name, 'probability': probability})
defappend_attention_path(self, attention_score, token1, path, token2):
self.attention_paths.append({'score': attention_score,
'path': path,
'token1': token1,
'token2': token2})