-
Notifications
You must be signed in to change notification settings - Fork 0
/
DenseNetController.py
410 lines (330 loc) · 13.3 KB
/
DenseNetController.py
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 7.0
# in conjunction with Tcl version 8.6
# Dec 26, 2021 02:12:51 AM +0200 platform: Windows NT
import os
import sys
# root_folder = os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# sys.path.append(root_folder)
# print (root_folder)
import shutil
import tkinter as tk
import tkinter.messagebox as box
import tkinter.ttk as ttk
import webbrowser as browser
from tkinter import filedialog, font
from tkinter.constants import *
from tkinter.filedialog import askopenfilename
import DenseNetGui
import PreProcess
import source
import TestModel
import TrainModel
from source import GishaText_9, GitHub
def createWindow(width: int, height: int, title: str, root):
# Create Window Instance and compute position and dimensions
if root == None:
window = tk.Tk()
else:
window = tk.Toplevel(root, bg="white")
geometry_settings = "%dx%d+%d+%d" % (
width, height, (window.winfo_screenwidth() - width) / 2, (window.winfo_screenheight() - height) / 2)
# Basic Window Settings
window.geometry(geometry_settings)
window.wm_resizable(False, False)
window.wm_title(title)
# Return Instance
return window
'''create the instruction window from the menu'''
def InstructionsWindow(root: tk.Toplevel, lebelString, about_header, about_footer, width, height):
instructions = createWindow(width, height, lebelString, root)
# About Window Content
header = tk.Label(master=instructions, text=about_header, font=GishaText_9, bg="white").pack(fill='both')
repository_link = tk.Label(master=instructions, text="link for GitHub", fg="Blue", cursor="hand2", bg="white")
repository_link.bind("<Button-1>", lambda e: browser.open_new(GitHub))
footer = tk.Label(master=instructions, text=about_footer, font=GishaText_9, bg="white").pack(fill='both')
# Display About Window
repository_link.pack()
instructions.mainloop()
def createDirs():
DataPath=os.path.join(source.MainPath,'data')
DataSetPath=os.path.join(DataPath,'data_set')
FeatureVectorsPath=os.path.join(DataPath,'feature_vectors')
LabelsPath=os.path.join(DataPath,'labels')
ResultsPath=os.path.join(source.MainPath,'results')
GraphPath=os.path.join(source.MainPath,'graph')
try:
if not os.path.isdir(DataPath):
os.mkdir(os.path.join(source.MainPath,'data'))
if not os.path.isdir(DataSetPath):
os.mkdir(DataSetPath)
if not os.path.isdir(FeatureVectorsPath):
os.mkdir(FeatureVectorsPath)
if not os.path.isdir(LabelsPath):
os.mkdir(LabelsPath)
if not os.path.isdir(ResultsPath):
os.mkdir(ResultsPath)
if not os.path.isdir(GraphPath):
os.mkdir(GraphPath)
except Exception as e:
print("Error while trying to create folders: "+str(e))
def main(*args):
'''Main entry point for the application.'''
global root
root = tk.Tk()
root.protocol('WM_DELETE_WINDOW', root.destroy)
# Creates a toplevel widget.
global _top1, Gui
_top1 = root
# os.chdir("../")
source.MainPath=os.getcwd()
source.initPath()
createDirs()
# os.chdir("Gui")
Gui = DenseNetGui.Toplevel1(_top1)
root.mainloop()
def ExitFunc(*args):
root.destroy()
sys.stdout.flush()
def ExportPreProccessing(*args):
# os.chdir('../')
MainPath = os.getcwd()
directory_path_string = filedialog.askdirectory(initialdir=os.getcwd(), title="request_string")
if ValiditeFolders(MainPath,"PreProcessing"):
if not copyFolder('data',directory_path_string , MainPath) or \
not copyFolder('graph', directory_path_string, MainPath):
print("Error")
printError("Error while trying to export files !")
else:
printInfo("Export Is Done !")
def ExportTraining(*args):
# os.chdir('../')
MainPath = os.getcwd()
directory_path_string = filedialog.askdirectory(initialdir=os.getcwd(), title="request_string")
if ValiditeFolders(MainPath,"Training"):
if not copyFolder('data',directory_path_string , MainPath) or \
not copyFolder('graph', directory_path_string, MainPath) or \
not copyFolder('results', directory_path_string, MainPath):
print("Error")
printError("Error while trying to export files !")
else:
printInfo("Export Is Done !")
def LoadNewGraph(*args):
source.Graph_absoloute_path = askopenfilename(initialdir="C:/Users/",
filetypes=(("Text File", "*.txt"), ("All Files", "*.*")),
title="Choose a Graph."
)
source.set_graph_file_name(os.path.basename(source.Graph_absoloute_path))
try:
shutil.copy(source.Graph_absoloute_path, os.path.join(source.MainPath,'graph',source.Graph_name))
updateOutputData("Graph file is loaded successfully : " + source.Graph_name)
except FileNotFoundError as e:
printError("Graph file is not loaded !")
updateOutputData("Graph file is not loaded !")
except Exception as e:
print("Error while trying to copy the imported graph file into MainPath/graph: "+str(e))
updateOutputData("Graph file is not loaded !")
printError("Error while trying to copy the imported graph file into MainPath/graph: "+str(e))
sys.stdout.flush()
def validateFields():
ErrorMessage = "You Must set all the Fields"
K = Gui.TCombobox1.get()
Dimenstion = Gui.Dimenstion_entry.get()
Distance = Gui.DistanceEntry.get()
RemovedEdgePrecentage = Gui.RemovedEdgePrecentage_entry.get()
Missing_Fields = False
if K == "":
ErrorMessage = ErrorMessage + "\nK is empty"
Missing_Fields = True
if Dimenstion == "":
ErrorMessage = ErrorMessage + "\nDimenstion is empty"
Missing_Fields = True
if Distance == "":
ErrorMessage = ErrorMessage + "\nH-hop Distance is empty"
Missing_Fields = True
if RemovedEdgePrecentage == "":
ErrorMessage = ErrorMessage + "\nRemoved Edge Precentage is empty"
Missing_Fields = True
if source.Graph_name == "":
ErrorMessage = ErrorMessage + "\nGraph is not loaded"
Missing_Fields = True
if Missing_Fields:
printError(ErrorMessage)
return False
else:
source.K = int(K)
try:
if int(Distance) <= 0:
printError("H-hop Distance must be bigger then zero")
return False
source.distance = int(Distance)
source.percentage_of_negative_class_additions = 1 - float(RemovedEdgePrecentage)
if int(Dimenstion) <= 0 :
printError("Dimension of features must be bigger then zero")
return False
source.DimensionOfFeatures = Dimenstion
except ValueError as e:
printError("You must insert an integer number at Dimension of features,H-hop Distance")
return False
if 0 > float(RemovedEdgePrecentage) or float(RemovedEdgePrecentage) > 1:
printError("RemovedEdgePrecentage must be in range [ 0, 1 ]")
return False
source.percentage_of_edges_to_remove = float(RemovedEdgePrecentage)
return True
def RunPreProccessing(*args):
if validateFields():
try:
Gui.TProgressbar1['maximum'] = 100
except Exception as e:
print(e)
source.progress_cnt = source.progress_cnt + 1
Gui.TProgressbar1['value'] = source.progress_cnt % int(100)
Gui.TProgressbar1.update()
PreProcess.runPreProcess(source.Graph_absoloute_path)
#sys.stdout.flush()
'''initialize the progress bar Max value'''
def InitProgressBar(*args):
path=str(os.getcwd())
size=0
for arg in args:
size=arg
try:
Gui.TProgressbar1['maximum'] = size + 20
except Exception as e:
printError(e)
print("Error while Initialize Progress Bar"+str(e))
'''Update the progress bar'''
def updateProgressBar(size,end):
try:
if end == 0 :
source.progress_cnt = source.progress_cnt + 1
Gui.TProgressbar1['value'] = source.progress_cnt % int(size+20)
Gui.TProgressbar1.update()
else:
Gui.TProgressbar1['value'] = int(size + 20)
Gui.TProgressbar1.update()
Gui.PreProccessingList.insert("end","Pre Processing stage is Done")
printInfo("Pre Processing stage is Done")
except Exception as e:
print(e)
printError(e)
return
if __name__ == '__main__':
DenseNetGui.start_up()
def updateOutputData(data):
Gui.PreProccessingList.insert("end",data)
def printError(ErrorMessage):
box.showerror('Error', ErrorMessage)
def printInfo(data):
box.showinfo('info', data)
def copyFolder(folder_name, MainPath, directory_path):
src = os.path.join(directory_path, folder_name)
dst = os.path.join(MainPath,folder_name)
if os.path.isdir(dst):
shutil.rmtree(dst)
try:
shutil.copytree(src,dst)
except Exception as e:
print(e)
printError(e)
print("Error while copy the folder:"+folder_name+ "to the path: " +dst)
printError("Error while copy the folder:"+folder_name+ "to the path: " +dst)
return False
return True
def TrainImportData():
# os.chdir('../')
directory_path_string = filedialog.askdirectory(initialdir=os.getcwd(), title="request_string")
if ValiditeFolders(directory_path_string,"Training_import"):
MainPath=os.getcwd()
if not copyFolder('data',MainPath,directory_path_string) or \
not copyFolder('graph', MainPath, directory_path_string) :
print("Error")
# os.chdir('Gui')
def LoadImportData():
# os.chdir('../')
directory_path_string = filedialog.askdirectory(initialdir=os.getcwd(), title="request_string")
if ValiditeFolders(directory_path_string,"Test"):
MainPath=os.getcwd()
if not copyFolder('data',MainPath,directory_path_string) or \
not copyFolder('graph', MainPath, directory_path_string) or \
not copyFolder('results', MainPath, directory_path_string): \
print("Error")
# os.chdir('Gui')
def RunTraining():
source.TrainModel = True
Gui.TrainingList.delete(0,END)
Epoch_num=""
Batch_size=""
# os.chdir('../')
try:
if Gui.epoch_entry.get() != "":
Epoch_num = int(Gui.epoch_entry.get())
if Gui.batchCombobox.get() != "":
Batch_size = int(Gui.batchCombobox.get())
ErrorMessage = "You Must set all Fields"
validateFields = False
if Batch_size == "":
ErrorMessage= ErrorMessage + "\nyou must set Batch Size Field"
validateFields = True
if validateFields:
print (ErrorMessage)
printError(ErrorMessage)
else:
if int(Epoch_num) <= 0 :
printError("Epoch Number size must be bigger then zero")
return
source.batch_size=Batch_size
source.n_epochs=Epoch_num
TrainModel.startTrain()
except ValueError as e:
printError("You must insert an integer number at Epoch number")
# os.chdir('Gui')
def ValiditeFolders(path,Usage) :
ErrorMessage = "seems that you have missing folders"
try:
DirectortList=os.listdir(path)
except FileNotFoundError as e:
if not e.filename == "":
printError("Error while trying to import file/directory\n"+str(e.filename))
else:
return False
except Exception as e:
print("Error while trying to import Data: "+str(e))
missFolder=False
if "data" not in DirectortList:
ErrorMessage= ErrorMessage + "\ndata folder Not found"
print ("data folder Not found")
missFolder=True
if "graph" not in DirectortList:
ErrorMessage = ErrorMessage + "\ngraph folder Not found"
print("graph folder Not found")
missFolder = True
if "results" not in DirectortList and (Usage=="Training" or Usage=="Test"):
ErrorMessage = ErrorMessage + "\nresults folder Not found"
print("results folder Not found")
missFolder = True
if missFolder:
printError(ErrorMessage)
return False
else:
return True
def UpdateTrainingListBox(data):
Gui.TrainingList.insert("end", data)
Gui.TrainingList.see("end")
Gui.TrainingList.update()
def UpdateLoadListBox(data):
Gui.LoadList.insert("end", data)
Gui.LoadList.see("end")
Gui.LoadList.update()
def ExportTrainResults():
ExportTraining()
def getEpoches():
return int(Gui.epoch_entry.get())
def RunTest():
source.TrainModel = False
TestModel.RunLoadModel()
def ExportTestResults():
ExportTraining()
def getTrainModelStatus():
return source.TrainModel