Uh oh!
There was an error while loading. Please reload this page.
forked from tech-srl/code2seq
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
Latest commit
145 lines (122 loc) · 5.71 KB
/
Copy pathcommon.py
File metadata and controls
145 lines (122 loc) · 5.71 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
importre
importsubprocess
importsys
classCommon:
internal_delimiter='|'
SOS='<S>'
EOS='</S>'
PAD='<PAD>'
UNK='<UNK>'
@staticmethod
defnormalize_word(word):
stripped=re.sub(r'[^a-zA-Z]', '', word)
iflen(stripped) ==0:
returnword.lower()
else:
returnstripped.lower()
@staticmethod
defload_histogram(path, max_size=None):
histogram= {}
withopen(path, 'r') asfile:
forlineinfile.readlines():
parts=line.split(' ')
ifnotlen(parts) ==2:
continue
histogram[parts[0]] =int(parts[1])
sorted_histogram= [(k, histogram[k]) forkinsorted(histogram, key=histogram.get, reverse=True)]
returndict(sorted_histogram[:max_size])
@staticmethod
defload_vocab_from_dict(word_to_count, add_values=[], max_size=None):
word_to_index, index_to_word= {}, {}
current_index=0
forvalueinadd_values:
word_to_index[value] =current_index
index_to_word[current_index] =value
current_index+=1
sorted_counts= [(k, word_to_count[k]) forkinsorted(word_to_count, key=word_to_count.get, reverse=True)]
limited_sorted=dict(sorted_counts[:max_size])
forword, countinlimited_sorted.items():
word_to_index[word] =current_index
index_to_word[current_index] =word
current_index+=1
returnword_to_index, index_to_word, current_index
@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
defbinary_to_string_3d(binary_string_tensor):
return [Common.binary_to_string_matrix(l) forlinbinary_string_tensor]
@staticmethod
deflegal_method_names_checker(name):
returnnotnamein [Common.UNK, Common.PAD, Common.EOS]
@staticmethod
deffilter_impossible_names(top_words):
result=list(filter(Common.legal_method_names_checker, top_words))
returnresult
@staticmethod
defunique(sequence):
returnlist(set(sequence))
@staticmethod
defparse_results(result, pc_info_dict, topk=5):
prediction_results= {}
results_counter=0
forsingle_methodinresult:
original_name, top_suggestions, top_scores, attention_per_context=list(single_method)
current_method_prediction_results=PredictionResults(original_name)
ifattention_per_contextisnotNone:
word_attention_pairs= [(word, attention) forword, attentionin
zip(top_suggestions, attention_per_context) if
Common.legal_method_names_checker(word)]
forpredicted_word, attention_timestepinword_attention_pairs:
current_timestep_paths= []
forcontext, attentionin [(key, attention_timestep[key]) forkeyin
sorted(attention_timestep, key=attention_timestep.get, reverse=True)][
:topk]:
ifcontextinpc_info_dict:
pc_info=pc_info_dict[context]
current_timestep_paths.append((attention.item(), pc_info))
current_method_prediction_results.append_prediction(predicted_word, current_timestep_paths)
else:
forpredicted_seqintop_suggestions:
filtered_seq= [wordforwordinpredicted_seqifCommon.legal_method_names_checker(word)]
current_method_prediction_results.append_prediction(filtered_seq, None)
prediction_results[results_counter] =current_method_prediction_results
results_counter+=1
returnprediction_results
@staticmethod
defcompute_bleu(ref_file_name, predicted_file_name):
withopen(predicted_file_name) aspredicted_file:
pipe=subprocess.Popen(["perl", "scripts/multi-bleu.perl", ref_file_name], stdin=predicted_file,
stdout=sys.stdout, stderr=sys.stderr)
classPredictionResults:
def__init__(self, original_name):
self.original_name=original_name
self.predictions=list()
defappend_prediction(self, name, current_timestep_paths):
self.predictions.append(SingleTimeStepPrediction(name, current_timestep_paths))
classSingleTimeStepPrediction:
def__init__(self, prediction, attention_paths):
self.prediction=prediction
ifattention_pathsisnotNone:
paths_with_scores= []
forattention_score, pc_infoinattention_paths:
path_context_dict= {'score': attention_score,
'path': pc_info.longPath,
'token1': pc_info.token1,
'token2': pc_info.token2}
paths_with_scores.append(path_context_dict)
self.attention_paths=paths_with_scores
classPathContextInformation:
def__init__(self, context):
self.token1=context['name1']
self.longPath=context['path']
self.shortPath=context['shortPath']
self.token2=context['name2']
def__str__(self):
return'%s,%s,%s'% (self.token1, self.shortPath, self.token2)