diff --git a/PyBox/Pybox.py b/PyBox/Pybox.py new file mode 100644 index 0000000..cde5b62 --- /dev/null +++ b/PyBox/Pybox.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +""" +pybox: This is a software bundle containing Python and lots of Python packages preinstalled +#######################Run this script to start the app######################## +-> Serve your app to any PC or Mac. +--------- +@author: maikherbig +""" +__version__ = "0.1.0" #version number of pybox + +import os,sys,gc + +import pyqtgraph as pg +from pyqtgraph.Qt import QtCore, QtWidgets, QtGui +from pyqtgraph import Qt +import pybox_start + +print("PyBox version: "+__version__) + +#suppress warnings/info from tensorflow +os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' + +#determine the Operating system +if not sys.platform.startswith("win"): + from multiprocessing import freeze_support + freeze_support() +# Make sure to get the right icon file on win,linux and mac +if sys.platform=="darwin": + icon_suff = ".icns" +else: + icon_suff = ".ico" + +##########################Optional: Splash-screen ############################# +##################(Only use it if you also have a frontend)#################### +try: + splashapp = QtWidgets.QApplication(sys.argv) + # Create and display the splash screen + splash = pybox_start.splashscreen(icon_suff) +except: + pass + +########################Required: some script to execute####################### +pybox_start.pybox_start()#Could be a banner. Or, you could put your whole script into pybox_start and only exectute this + +##############################Optional: GUI#################################### +#import frontend #import frontend very late such that the splashscreen loads fast + +dir_root = os.path.dirname(pybox_start.__file__)#ask the module for its origin +def main(): + app,MainWindow = pybox_start.pybox_main(icon_suff) + + try: + splash.finish(MainWindow) + except: + pass + + ret = app.exec_() + sys.exit(ret) + +if __name__ == '__main__': + try: + main() + except: + pass + + + + + + diff --git a/PyBox/all_imports.py b/PyBox/all_imports.py new file mode 100644 index 0000000..5903212 --- /dev/null +++ b/PyBox/all_imports.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- +""" +aid_imports +list of each import +--------- +@author: maikherbig +""" + +import os,shutil,json,re,urllib +import numpy as np +import dclab +import h5py,time +import gc,tempfile +import pandas as pd +import tensorflow as tf +from tensorflow.python.tools import optimize_for_inference_lib +import keras +from keras.models import load_model,Model +from keras.layers import Dense,Activation +from keras import backend as K + +import keras_metrics #side package for precision, recall etc during training +global keras_metrics + +from keras2onnx import convert_keras +from onnx import save_model as save_onnx +from mmdnn.conversion._script import convertToIR,IRToCode,convert +import coremltools +import cv2 +import pyqtgraph as pg +from pyqtgraph.Qt import QtCore, QtWidgets, QtGui +import sys,traceback,ast +from pyqtgraph.Qt import QtWidgets +from scipy import ndimage +from tensorflow.python.client import device_lib + + +import pyqtgraph as pg +from pyqtgraph import Qt + +import pybox_start + +import io,platform +import copy +from stat import S_IREAD,S_IRGRP,S_IROTH,S_IWRITE,S_IWGRP,S_IWOTH + +from tensorboard import program +from tensorboard import default + +from tensorflow.python.client import device_lib + +from scipy import misc +from sklearn import metrics,preprocessing +import matplotlib.pyplot as plt +import PIL +import openpyxl,xlrd +import psutil + +from keras.models import model_from_json,model_from_config,clone_model +from keras.preprocessing.image import load_img +from keras.utils import np_utils,multi_gpu_model +from keras.utils.conv_utils import convert_kernel +from keras2onnx import convert_keras +from onnx import save_model as save_onnx + +import frontend + +from keras.models import Sequential +from keras.layers import Add,Concatenate,Input,Dense,Dropout,Flatten,Activation,Conv2D,MaxPooling2D,BatchNormalization,GlobalAveragePooling2D,GlobalMaxPooling2D,concatenate +from keras.layers.merge import add +from keras import regularizers +from keras.engine.topology import get_source_inputs +import keras_applications diff --git a/PyBox/art/icon_main.icns b/PyBox/art/icon_main.icns new file mode 100644 index 0000000..49f1a48 Binary files /dev/null and b/PyBox/art/icon_main.icns differ diff --git a/PyBox/art/icon_main.ico b/PyBox/art/icon_main.ico new file mode 100644 index 0000000..3651afc Binary files /dev/null and b/PyBox/art/icon_main.ico differ diff --git a/PyBox/art/icon_main.png b/PyBox/art/icon_main.png new file mode 100644 index 0000000..413e732 Binary files /dev/null and b/PyBox/art/icon_main.png differ diff --git a/PyBox/art/icon_main.svg b/PyBox/art/icon_main.svg new file mode 100644 index 0000000..41157bf --- /dev/null +++ b/PyBox/art/icon_main.svg @@ -0,0 +1,141 @@ + +image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PyBox/art/icon_splash.ico b/PyBox/art/icon_splash.ico new file mode 100644 index 0000000..3651afc Binary files /dev/null and b/PyBox/art/icon_splash.ico differ diff --git a/PyBox/art/icon_splashe.icns b/PyBox/art/icon_splashe.icns new file mode 100644 index 0000000..49f1a48 Binary files /dev/null and b/PyBox/art/icon_splashe.icns differ diff --git a/PyBox/backend.py b/PyBox/backend.py new file mode 100644 index 0000000..92850c6 --- /dev/null +++ b/PyBox/backend.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +""" +backend +--------- +@author: maikherbig +""" +import os,shutil,json +import io,sys +import frontend +dir_root = os.path.dirname(frontend.__file__)#ask the module for its origin + + +def run_python(code): + codeOut = io.StringIO() + out,error = "","" + # capture output + sys.stdout = codeOut + try: + exec(code,globals()) + except Exception as e: + error = str(e) + # restore stdout + sys.stdout = sys.__stdout__ + out = codeOut.getvalue() + codeOut.close() + + return out,error + + + + diff --git a/PyBox/frontend.py b/PyBox/frontend.py new file mode 100644 index 0000000..a87f743 --- /dev/null +++ b/PyBox/frontend.py @@ -0,0 +1,301 @@ +# -*- coding: utf-8 -*- +""" +frontend of pybox +--------- +@author: maikherbig +""" +#Continue starting the app +from PyQt5 import QtCore, QtGui, QtWidgets +import traceback,io,os,psutil,time,sys +import all_imports +import backend #Optionally: outsource some of the functions to backend to keep frontend clean +dir_root = os.path.dirname(all_imports.__file__)#ask the module for its origin + +try: + _fromUtf8 = QtCore.QString.fromUtf8 +except AttributeError: + def _fromUtf8(s): + return s + +try: + _encoding = QtWidgets.QApplication.UnicodeUTF8 + def _translate(context, text, disambig): + return QtWidgets.QApplication.translate(context, text, disambig, _encoding) +except AttributeError: + def _translate(context, text, disambig): + return QtWidgets.QApplication.translate(context, text, disambig) + + +class WorkerSignals(QtCore.QObject): + ''' + Code inspired from here: https://www.learnpyqt.com/courses/concurrent-execution/multithreading-pyqt-applications-qthreadpool/ + + Defines the signals available from a running worker thread. + Supported signals are: + finished + No data + error + `tuple` (exctype, value, traceback.format_exc() ) + result + `object` data returned from processing, anything + progress + `int` indicating % progress + history + `dict` containing keras model history.history resulting from .fit + ''' + finished = QtCore.pyqtSignal() + error = QtCore.pyqtSignal(tuple) + result = QtCore.pyqtSignal(object) + progress = QtCore.pyqtSignal(int) + history = QtCore.pyqtSignal(dict) + +class Worker(QtCore.QRunnable): + ''' + Code inspired/copied from: https://www.learnpyqt.com/courses/concurrent-execution/multithreading-pyqt-applications-qthreadpool/ + Worker thread + Inherits from QRunnable to handler worker thread setup, signals and wrap-up. + :param callback: The function callback to run on this worker thread. Supplied args and + kwargs will be passed through to the runner. + :type callback: function + :param args: Arguments to pass to the callback function + :param kwargs: Keywords to pass to the callback function + ''' + def __init__(self, fn, *args, **kwargs): + super(Worker, self).__init__() + + # Store constructor arguments (re-used for processing) + self.fn = fn + self.args = args + self.kwargs = kwargs + self.signals = WorkerSignals() + + # Add the callback to our kwargs + self.kwargs['progress_callback'] = self.signals.progress + self.kwargs['history_callback'] = self.signals.history + + @QtCore.pyqtSlot() + def run(self): + ''' + Initialise the runner function with passed args, kwargs. + ''' + + # Retrieve args/kwargs here; and fire processing using them + try: + result = self.fn(*self.args, **self.kwargs) + except: + traceback.print_exc() + exctype, value = sys.exc_info()[:2] + self.signals.error.emit((exctype, value, traceback.format_exc())) + else: + self.signals.result.emit(result) # Return the result of the processing + finally: + self.signals.finished.emit() # Done + +class Ui_MainWindow(object): + def setupUi(self, MainWindow): + MainWindow.setObjectName("MainWindow") + MainWindow.resize(782, 650) + + + + self.centralwidget = QtWidgets.QWidget(MainWindow) + self.centralwidget.setObjectName("centralwidget") + self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) + self.gridLayout.setObjectName("gridLayout") + self.verticalLayout_python_1 = QtWidgets.QVBoxLayout() + self.verticalLayout_python_1.setObjectName("verticalLayout_python_1") + self.groupBox_pythonMenu = QtWidgets.QGroupBox(self.centralwidget) + self.groupBox_pythonMenu.setMaximumSize(QtCore.QSize(16777215, 71)) + self.groupBox_pythonMenu.setObjectName("groupBox_pythonMenu") + self.gridLayout_40 = QtWidgets.QGridLayout(self.groupBox_pythonMenu) + self.gridLayout_40.setObjectName("gridLayout_40") + self.horizontalLayout_pythonMenu = QtWidgets.QHBoxLayout() + self.horizontalLayout_pythonMenu.setObjectName("horizontalLayout_pythonMenu") + self.label_pythonCurrentFile = QtWidgets.QLabel(self.groupBox_pythonMenu) + self.label_pythonCurrentFile.setObjectName("label_pythonCurrentFile") + self.horizontalLayout_pythonMenu.addWidget(self.label_pythonCurrentFile) + self.lineEdit_pythonCurrentFile = QtWidgets.QLineEdit(self.groupBox_pythonMenu) + self.lineEdit_pythonCurrentFile.setEnabled(False) + self.lineEdit_pythonCurrentFile.setObjectName("lineEdit_pythonCurrentFile") + self.horizontalLayout_pythonMenu.addWidget(self.lineEdit_pythonCurrentFile) + self.gridLayout_40.addLayout(self.horizontalLayout_pythonMenu, 0, 0, 1, 1) + self.verticalLayout_python_1.addWidget(self.groupBox_pythonMenu) + self.splitter_python_1 = QtWidgets.QSplitter(self.centralwidget) + self.splitter_python_1.setOrientation(QtCore.Qt.Horizontal) + self.splitter_python_1.setObjectName("splitter_python_1") + self.groupBox_pythonEditor = QtWidgets.QGroupBox(self.splitter_python_1) + self.groupBox_pythonEditor.setObjectName("groupBox_pythonEditor") + self.gridLayout_38 = QtWidgets.QGridLayout(self.groupBox_pythonEditor) + self.gridLayout_38.setObjectName("gridLayout_38") + self.verticalLayout_editor_1 = QtWidgets.QVBoxLayout() + self.verticalLayout_editor_1.setObjectName("verticalLayout_editor_1") + self.horizontalLayout_editor_1 = QtWidgets.QHBoxLayout() + self.horizontalLayout_editor_1.setObjectName("horizontalLayout_editor_1") + self.pushButton_pythonInOpen = QtWidgets.QPushButton(self.groupBox_pythonEditor) + self.pushButton_pythonInOpen.setObjectName("pushButton_pythonInOpen") + self.horizontalLayout_editor_1.addWidget(self.pushButton_pythonInOpen) + self.pushButton_pythonSaveAs = QtWidgets.QPushButton(self.groupBox_pythonEditor) + self.pushButton_pythonSaveAs.setObjectName("pushButton_pythonSaveAs") + self.horizontalLayout_editor_1.addWidget(self.pushButton_pythonSaveAs) + self.pushButton_pythonInClear = QtWidgets.QPushButton(self.groupBox_pythonEditor) + self.pushButton_pythonInClear.setObjectName("pushButton_pythonInClear") + self.horizontalLayout_editor_1.addWidget(self.pushButton_pythonInClear) + self.pushButton_pythonInRun = QtWidgets.QPushButton(self.groupBox_pythonEditor) + self.pushButton_pythonInRun.setObjectName("pushButton_pythonInRun") + self.horizontalLayout_editor_1.addWidget(self.pushButton_pythonInRun) + self.verticalLayout_editor_1.addLayout(self.horizontalLayout_editor_1) + self.plainTextEdit_pythonIn = QtWidgets.QPlainTextEdit(self.groupBox_pythonEditor) + self.plainTextEdit_pythonIn.setObjectName("plainTextEdit_pythonIn") + self.verticalLayout_editor_1.addWidget(self.plainTextEdit_pythonIn) + self.gridLayout_38.addLayout(self.verticalLayout_editor_1, 0, 0, 1, 1) + self.groupBox_pythonConsole = QtWidgets.QGroupBox(self.splitter_python_1) + self.groupBox_pythonConsole.setObjectName("groupBox_pythonConsole") + self.gridLayout_39 = QtWidgets.QGridLayout(self.groupBox_pythonConsole) + self.gridLayout_39.setObjectName("gridLayout_39") + self.verticalLayout_console_1 = QtWidgets.QVBoxLayout() + self.verticalLayout_console_1.setObjectName("verticalLayout_console_1") + self.horizontalLayout_console_1 = QtWidgets.QHBoxLayout() + self.horizontalLayout_console_1.setObjectName("horizontalLayout_console_1") + self.pushButton_pythonOutClear = QtWidgets.QPushButton(self.groupBox_pythonConsole) + self.pushButton_pythonOutClear.setObjectName("pushButton_pythonOutClear") + self.horizontalLayout_console_1.addWidget(self.pushButton_pythonOutClear) + self.pushButton_pythonOutRun = QtWidgets.QPushButton(self.groupBox_pythonConsole) + self.pushButton_pythonOutRun.setObjectName("pushButton_pythonOutRun") + self.horizontalLayout_console_1.addWidget(self.pushButton_pythonOutRun) + self.verticalLayout_console_1.addLayout(self.horizontalLayout_console_1) + self.textBrowser_pythonOut = QtWidgets.QTextBrowser(self.groupBox_pythonConsole) + self.textBrowser_pythonOut.setEnabled(True) + self.textBrowser_pythonOut.setObjectName("textBrowser_pythonOut") + self.verticalLayout_console_1.addWidget(self.textBrowser_pythonOut) + self.gridLayout_39.addLayout(self.verticalLayout_console_1, 0, 0, 1, 1) + self.verticalLayout_python_1.addWidget(self.splitter_python_1) + self.gridLayout.addLayout(self.verticalLayout_python_1, 0, 0, 1, 1) + + + MainWindow.setCentralWidget(self.centralwidget) + self.menubar = QtWidgets.QMenuBar(MainWindow) + self.menubar.setGeometry(QtCore.QRect(0, 0, 782, 26)) + self.menubar.setObjectName("menubar") + MainWindow.setMenuBar(self.menubar) + + self.statusbar = QtWidgets.QStatusBar(MainWindow) + self.statusbar.setObjectName("statusbar") + MainWindow.setStatusBar(self.statusbar) + self.statusbar_cpuRam = QtWidgets.QLabel("CPU: xx% RAM: xx% ") + self.statusbar.addPermanentWidget(self.statusbar_cpuRam) + + + + + ############################Variables################################## + ####################################################################### + #Initilaize some variables which are lateron filled in the program + self.threadpool = QtCore.QThreadPool() + self.threadpool_single_queue = 0 #count nr. of threads in queue; + + #Start running show_cpu_ram function and run it all the time + worker_cpu_ram = Worker(self.cpu_ram_worker) + self.threadpool.start(worker_cpu_ram) + + self.retranslateUi(MainWindow) + QtCore.QMetaObject.connectSlotsByName(MainWindow) + + + + + ######################Connections###################################### + self.pushButton_pythonInRun.clicked.connect(self.pythonInRun) + self.pushButton_pythonInClear.clicked.connect(self.pythonInClear) + self.pushButton_pythonSaveAs.clicked.connect(self.pythonInSaveAs) + self.pushButton_pythonInOpen.clicked.connect(self.pythonInOpen) + self.pushButton_pythonOutClear.clicked.connect(self.pythonOutClear) + self.pushButton_pythonOutRun.clicked.connect(self.pythonInRun) + + + + def retranslateUi(self, MainWindow): + _translate = QtCore.QCoreApplication.translate + MainWindow.setWindowTitle(_translate("MainWindow", "PyBox")) + self.groupBox_pythonEditor.setTitle(_translate("MainWindow", "Editor")) + self.label_pythonCurrentFile.setText(_translate("MainWindow", "Current file:")) + + self.pushButton_pythonInOpen.setText(_translate("MainWindow", "Open file..")) + self.pushButton_pythonSaveAs.setText(_translate("MainWindow", "Save as...")) + self.pushButton_pythonInClear.setText(_translate("MainWindow", "Clear")) + self.pushButton_pythonInRun.setText(_translate("MainWindow", "Run")) + self.groupBox_pythonConsole.setTitle(_translate("MainWindow", "Console")) + self.pushButton_pythonOutClear.setText(_translate("MainWindow", "Clear")) + self.pushButton_pythonOutRun.setText(_translate("MainWindow", "Run")) + + #####################Python Editor/Console################################# + def pythonInRun(self): + self.threadpool_single_queue += 1 + if self.threadpool_single_queue == 1: + worker = Worker(self.pythonInRun_Worker) + self.threadpool.start(worker) + + def pythonInRun_Worker(self,progress_callback,history_callback): + code = self.plainTextEdit_pythonIn.toPlainText() + out,error = backend.run_python(code) + text_out = "Out:\n"+out + text_error = "Error:\n"+error + + #Print both to textBrowser_pythonOut + self.textBrowser_pythonOut.append(text_out) + if len(error)>0: + self.textBrowser_pythonOut.append(text_error) + + self.threadpool_single_queue = 0 #reset thread counter + + def pythonInClear(self): + self.plainTextEdit_pythonIn.clear() + self.lineEdit_pythonCurrentFile.clear() + + def pythonInSaveAs(self): + filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save code', dir_root,"Python file (*.py)") + filename = filename[0] + if len(filename)==0: + return + #add the suffix .csv + if not filename.endswith(".py"): + filename = filename +".py" + + code = self.plainTextEdit_pythonIn.toPlainText() + + myfile = open(filename,'w')#Open the file with writing permission + myfile.write(code) + myfile.close() + self.lineEdit_pythonCurrentFile.setText(filename) + + def pythonInOpen(self): + filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open Python file', dir_root,"Python file (*.py)") + filename = filename[0] + if not filename.endswith(".py"): + return + if not os.path.isfile(filename): + msg = QtWidgets.QMessageBox() + msg.setIcon(QtWidgets.QMessageBox.Information) + msg.setText("File not found") + msg.setWindowTitle("File not found") + msg.setStandardButtons(QtWidgets.QMessageBox.Ok) + msg.exec_() + return + with open(filename, 'r') as myfile: + data = myfile.read() + + self.plainTextEdit_pythonIn.clear() + self.plainTextEdit_pythonIn.insertPlainText(data) + self.lineEdit_pythonCurrentFile.setText(filename) + + def pythonOutClear(self): + self.textBrowser_pythonOut.clear() + + #Show cpu and ram usage on the status bar + def cpu_ram_worker(self,progress_callback,history_callback): + while True: + cpu,ram = psutil.cpu_percent(),psutil.virtual_memory().percent + self.statusbar_cpuRam.setText("CPU: "+str(cpu)+"% RAM: "+str(ram)+"%") + time.sleep(2) + + + diff --git a/PyBox/icon_main.icns b/PyBox/icon_main.icns new file mode 100644 index 0000000..49f1a48 Binary files /dev/null and b/PyBox/icon_main.icns differ diff --git a/PyBox/icon_main.ico b/PyBox/icon_main.ico new file mode 100644 index 0000000..3651afc Binary files /dev/null and b/PyBox/icon_main.ico differ diff --git a/PyBox/pybox_0.1.0_GPU.spec b/PyBox/pybox_0.1.0_GPU.spec new file mode 100644 index 0000000..8d2be24 --- /dev/null +++ b/PyBox/pybox_0.1.0_GPU.spec @@ -0,0 +1,37 @@ +# -*- mode: python ; coding: utf-8 -*- + +block_cipher = None + + +a = Analysis(['PyBox.py'], + pathex=['C:\\Users\\s7378965\\anaconda3\\envs\\PyBox_0.1.0'], + binaries=[], + datas=[], + hiddenimports=['pywt','pywt._extensions._cwt','pywrap_tensorflow','_pywrap_tensorflow_internal','aid_imports'], + hookspath=[], + runtime_hooks=[], + excludes=['model_zoo','aid_backbone','aid_bin','aid_start','aid_dl','aid_frontend','aid_img','partial_trainability.py'], + win_no_prefer_redirects=False, + win_private_assemblies=False, + cipher=block_cipher, + noarchive=False) +pyz = PYZ(a.pure, a.zipped_data, + cipher=block_cipher) +exe = EXE(pyz, + a.scripts, + [], + exclude_binaries=True, + name='PyBox_0.1.0', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + console=True , icon='icon_main.ico') +coll = COLLECT(exe, + a.binaries, + a.zipfiles, + a.datas, + strip=False, + upx=True, + upx_exclude=[], + name='PyBox_0.1.0') diff --git a/PyBox/pybox_start.py b/PyBox/pybox_start.py new file mode 100644 index 0000000..ad12696 --- /dev/null +++ b/PyBox/pybox_start.py @@ -0,0 +1,176 @@ +# -*- coding: utf-8 -*- +""" +pybox_start.py +only a banner and some functions to check the keras version +intentionally lightweight script to speed up the start of PyBox +--------- +@author: maikherbig +""" + +import os,shutil,json,sys +import pyqtgraph as pg +from pyqtgraph.Qt import QtCore, QtWidgets, QtGui +from pyqtgraph import Qt +import pybox_start #import the module itself only to find out the directory +dir_root = os.path.dirname(pybox_start.__file__)#ask the module for its origin + +def splashscreen(icon_suff): + """ + Use this function to define a splashscreen + + Parameters + ---------- + icon_suff: str Either ".ico" for Windows/Linux, or ".icns" for MacOS + + Returns + ---------- + QtWidgets.QSplashScreen + """ + + # Create and display the splash screen + splash_pix = os.path.join(dir_root,"art","icon_splash"+icon_suff) + splash_pix = QtGui.QPixmap(splash_pix) + splash = QtWidgets.QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) + splash.setMask(splash_pix.mask()) + splash.show() + return splash + +def banner(): + #generated using: https://www.patorjk.com/software/taag/ + text = """ + _____ ____ + | __ \ | _ \ + | |__) | _| |_) | _____ __ + | ___/ | | | _ < / _ \ \/ / + | | | |_| | |_) | (_) > < + |_| \__, |____/ \___/_/\_\ + __/ | + |___/ +is starting... +""" + print(text) + + +def keras_json_replace(keras_json_path,json_exists=True): + if json_exists: + #Inform user! + print("I found a keras.json file in your home-directory which has options AID does not accept.\ + This file will be copied to keras_beforeAID_x.json and a new keras.json\ + is written with valid options for AID.") + i=0 + while os.path.isfile(os.path.expanduser('~')+os.sep+'.keras'+os.sep+'keras_beforeAID_'+str(i)+'.json'): + i+=1 + shutil.copy(keras_json_path, os.path.expanduser('~')+os.sep+'.keras'+os.sep+'keras_beforeAID_'+str(i)+'.json') + + #Write new keras.json: + with open(os.path.expanduser('~')+os.sep+'.keras'+os.sep+'keras.json','w') as f: + new_settings = """{\n "image_dim_ordering": "tf", \n "epsilon": 1e-07, \n "floatx": "float32", \n "backend": "tensorflow"\n}""" + f.write(new_settings) + +def keras_json_check(keras_json_path): + if os.path.isfile(keras_json_path): + with open(keras_json_path, 'r') as keras_json: + keras_json=keras_json.read() + keras_json = json.loads(keras_json) + keys_keras_json = keras_json.keys() #contained keys + keys_expected = ['image_dim_ordering','backend','epsilon','floatx'] #expected keys + #are those keys present in keys_keras_json? + keys_present = [key in keys_expected for key in keys_keras_json] + keys_present = all(keys_present) #are all true? + checks = [] + if keys_present==True:#all keys are there, now check if the value is correct + checks.append( keras_json['image_dim_ordering']=="tf" ) + checks.append( keras_json['backend']=="tensorflow" ) + checks.append( keras_json['epsilon']==1e-07 ) + checks.append( keras_json['floatx']=="float32" ) + checks = all(checks) #are all true? + if checks==True: + #keras.json is fine, no need to overwrite it + return + else:#some values are different. AID need to write new keras.json + keras_json_replace(keras_json_path) + + else:#some keys are missing + keras_json_replace(keras_json_path) + + else:#there exists NO keras.json! Very likely the user opened AID for the first time :) + #Welcome the user + print("A warm welcome to your first session of PyBox :)") + keras_json_replace(keras_json_path,False) + +def pybox_start(): + banner() #show a fancy banner in console + + #BEFORE importing tensorflow or anything from keras: make sure the keras.json has + #certain properties + keras_json_path = os.path.expanduser('~')+os.sep+'.keras'+os.sep+'keras.json' + if not os.path.isdir(os.path.expanduser('~')+os.sep+'.keras'): + os.mkdir(os.path.expanduser('~')+os.sep+'.keras') + + keras_json_check(keras_json_path)#check the keras.json + + from tensorflow.python.client import device_lib + devices = device_lib.list_local_devices() + device_types = [devices[i].device_type for i in range(len(devices))] + + #Get the number of CPU cores and GPUs + cpu_nr = os.cpu_count() + gpu_nr = device_types.count("GPU") + print("Nr. of GPUs detected: "+str(gpu_nr)) + + print("Found "+str(len(devices))+" device(s):") + print("------------------------") + for i in range(len(devices)): + print("Device "+str(i)+": "+devices[i].name) + print("Device type: "+devices[i].device_type) + print("Device description: "+devices[i].physical_device_desc) + print("------------------------") + + #Split CPU and GPU into two lists of devices + devices_cpu = [] + devices_gpu = [] + for dev in devices: + if dev.device_type=="CPU": + devices_cpu.append(dev) + elif dev.device_type=="GPU": + devices_gpu.append(dev) + else: + print("Unknown device type:"+str(dev)+"\n") + + from keras import backend as K + if 'GPU' in device_types: + keras_gpu_avail = K.tensorflow_backend._get_available_gpus() + if len(keras_gpu_avail)>0: + print("Following GPU is used:") + print(keras_gpu_avail) + print("------------------------") + else: + print("TensorFlow detected GPU, but Keras didn't") + print("------------------------") + + +def pybox_main(icon_suff): + """ + Function defines the main loop (starts GUI) + + Parameters + ---------- + icon_suff: str Either ".ico" for Windows/Linux, or ".icns" for MacOS + + Returns + ---------- + QtWidgets.QApplication + QtWidgets.QMainWindow + """ + + import frontend #frontend.py contains most of the "intelligence" + global app + app = QtWidgets.QApplication(sys.argv) + app.setWindowIcon(QtGui.QIcon(os.path.join(dir_root,"art","icon_main"+icon_suff))) + MainWindow = QtWidgets.QMainWindow() + ui = frontend.Ui_MainWindow() + ui.setupUi(MainWindow) + MainWindow.show() + return app,MainWindow + + \ No newline at end of file