Exemple #1
0
    def __init__(self, language='en'):
        # Create instance
        self.win = tk.Tk()

        self.i18n = I18N(language)

        # Add a title
        self.win.title(self.i18n.title)

        # Callback methods now in different module
        self.callBacks = Callbacks(self)

        # Disable resizing the window
        self.win.resizable(0, 0)

        # Create a Queue
        self.guiQueue = Queue()

        self.createWidgets()

        # populate Tab 2 Entries
        self.callBacks.defaultFileEntries()

        # create MySQL instance
        #self.mySQL = MySQL()

        # create Logger instance
        fullPath = path.realpath(__file__)
        self.log = Logger(fullPath)
        print(self.log)

        # create Log Level instance
        self.level = LogLevel()
Exemple #2
0
    def __init__(self):
        self.main = tk.Tk()
        self.i18n = I18N('kr')
        self.callBacks = Callbacks(self)
        self.main.title(self.i18n.title)

        self.fDir = fDir
        self.saveDir = saveDir
        self.VERSION = VERSION
        self.ftypes = ftypes

        self.createWidgets()
        self.callBacks.defaultFileEntries()
Exemple #3
0
    def __init__(self, root, language='es'):
        self.lang = language
        self.root = root
        tk.Frame.__init__(self, self.root)
        # Se llama al canvas
        self.create_frame_canvas()
        # Se crea i18n para internacionalizacion
        self.i18n = I18N(self.lang)
        # Se crea instancia del modelo
        # Se inicializan imagenes del GUI

        self.pnv = Image("photo", file="Resources/PinguinoNoVe.png")
        self.pc = Image("photo", file="Resources/pinguinoChef.png")

        self.img = Image("photo", file="Resources/panque.png")

        self.mas = Image("photo", file="Resources/mas.png")
        # Se establece propidades de root
        self.root.title(self.i18n.title)
        self.root.resizable(1, 1)
        self.root.geometry("1200x700")
        self.root.tk.call('wm', 'iconphoto', self.root._w, self.img)
        # se llama al modulo callbacks
        self.call_backs = Callbacks(self)
        # Se llama a los widgets
        self.create_tabs()
        self.create_menubar()
        self.create_tab1()
        self.create_tab3()
        self.create_logo()
        self.total.set("300")
        self.tab_control.select(2)
Exemple #4
0
 def fit(self, x_train, y_train, x_val, y_val, num_epochs, batch_size,
         model_path):
     callbacks = Callbacks(model_path)
     self.model.fit(x_train,
                    y_train,
                    epochs=num_epochs,
                    validation_data=(x_val, y_val),
                    batch_size=batch_size,
                    callbacks=callbacks.callbacks_list,
                    verbose=1)
Exemple #5
0
 def __init__(self, language='es'):
     self.win = tk.Tk()
     self.i18n = I18N(language)
     self.win.title(self.i18n.title)
     self.win.resizable(1, 1)
     self.win.geometry("1000x600")
     self.pcb = Image("photo", file="Resources/pinguinoChefPanbien.png")
     self.pnv = Image("photo", file="Resources/PinguinoNoVe.png")
     self.pcq = Image("photo", file="Resources/pinguinoChefPanQuemado.png")
     self.img = Image("photo", file="Resources/panque.png")
     self.lpz = Image("photo", file="Resources/lapiz.png")
     self.ojo = Image("photo", file="Resources/ojo.png")
     self.win.tk.call('wm', 'iconphoto', self.win._w, self.img)
     self.call_backs = Callbacks(self)
     # Se llaman metodos que crean los widgets
     self.create_tabs()
     self.create_menubar()
     self.create_tab1()
     self.create_tab2()
     self.create_logo()
     self.total.set("300")
     self.tab_control.select(1)
Exemple #6
0
def main():
    gobject.threads_init()
    gtk.gdk.threads_init()
    SDpyServVersion = '0.1'

    GuiOptions = {
        'ServingDirectory': None,
        'SendSlots': None,
        'DynamicSlots': None,
        'FilesInQueue': None,
        'QueueFull': None,
        'MaxFindNum': None,
        'SmallLowCps': None,
        'LargeLowCps': None,
        'LargeFileSize': None,
        'QueueListCheck': None,
        'MaxListQueue': None,
        'SendCtcpCheck': None,
        'SendCtcpFreq': None,
        'RandomPlayCheck': None,
        'RandomPlayFreq': None,
        'EnableFindCheck': None,
        'radioLogging': None,
        'ServerPriority': None,
        'ZipListCheck': None,
        'ExtentionEntry': None
    }

    PriorityList = {
        'radioNormal': 0,
        'radioServer': 1,
        'radioServerOnlySilent': 2,
        'radioServerOnly': 3
    }

    LoggingList = {
        'radioNormalLog': 0,
        'radioSeperateLog': 1,
        'radioFileLog': 2
    }

    config = ConfigParser.ConfigParser()
    configFile = open('etc/SDpyServ.cfg')
    config.readfp(configFile)

    builder = gtk.Builder()
    builder.add_from_file("share/SDpyServ.ui")
    About = builder.get_object('AboutWindow')
    About.set_property('version', SDpyServVersion)
    sdError = ErrorDialogs(builder)

    dbc = DbCalls(builder, config, sdError)

    listTab = ListTab(builder, dbc)
    channelTab = ChannelTab(builder, dbc)
    statsTab = StatsTab(builder, dbc)

    ## Initialize Gui Values
    InitializeGui(builder, dbc, GuiOptions, \
                  LoggingList, PriorityList)
    ## Connect All Signals
    pyServCB=Callbacks(builder, dbc, \
                       GuiOptions, LoggingList, listTab, \
                       channelTab, statsTab, PriorityList, sdError)
    builder.connect_signals(pyServCB)
    ## Show the main window
    pyServWindow = builder.get_object("pyServWin")
    pyServWindow.show()
    ## Loop for and wait for events
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()
    ## Close the DB connection
    dbc.dbCloseConnection()
Exemple #7
0
class OOP():
    def __init__(self, language='en'):
        # Create instance
        self.win = tk.Tk()

        self.i18n = I18N(language)

        # Add a title
        self.win.title(self.i18n.title)

        # Callback methods now in different module
        self.callBacks = Callbacks(self)

        # Disable resizing the window
        self.win.resizable(0, 0)

        # Create a Queue
        self.guiQueue = Queue()

        self.createWidgets()

        # populate Tab 2 Entries
        self.callBacks.defaultFileEntries()

        # create MySQL instance
        #self.mySQL = MySQL()

        # create Logger instance
        fullPath = path.realpath(__file__)
        self.log = Logger(fullPath)
        print(self.log)

        # create Log Level instance
        self.level = LogLevel()

    #####################################################################################
    def createWidgets(self):
        # Tab Control introduced here --------------------------------------
        tabControl = ttk.Notebook(self.win)  # Create Tab Control

        tab1 = ttk.Frame(tabControl)  # Create a tab
        #         tabControl.add(tab1, text='MySQL')    # Add the tab -- COMMENTED OUT FOR CH08

        tab2 = ttk.Frame(tabControl)  # Add a second tab
        tabControl.add(tab2, text='Widgets')  # Make second tab visible

        tabControl.pack(expand=1, fill="both")  # Pack to make visible
        # ~ Tab Control introduced here -----------------------------------------

        # We are creating a container frame to hold all other widgets
        self.mySQL = ttk.LabelFrame(tab1, text=' Python Database ')
        self.mySQL.grid(column=0, row=0, padx=8, pady=4)

        # Creating a Label
        ttk.Label(self.mySQL, text="Book Title:").grid(column=0,
                                                       row=0,
                                                       sticky='W')

        # Adding a Textbox Entry widget
        book = tk.StringVar()
        self.bookTitle = ttk.Entry(self.mySQL, width=34, textvariable=book)
        self.bookTitle.grid(column=0, row=1, sticky='W')

        # Adding a Textbox Entry widget
        book1 = tk.StringVar()
        self.bookTitle1 = ttk.Entry(self.mySQL, width=34, textvariable=book1)
        self.bookTitle1.grid(column=0, row=2, sticky='W')

        # Adding a Textbox Entry widget
        book2 = tk.StringVar()
        self.bookTitle2 = ttk.Entry(self.mySQL, width=34, textvariable=book2)
        self.bookTitle2.grid(column=0, row=3, sticky='W')

        # Creating a Label
        ttk.Label(self.mySQL, text="Page:").grid(column=1, row=0, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber.grid(column=1, row=1, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber1 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber1.grid(column=1, row=2, sticky='W')

        # Adding a Textbox Entry widget
        page = tk.StringVar()
        self.pageNumber2 = ttk.Entry(self.mySQL, width=6, textvariable=page)
        self.pageNumber2.grid(column=1, row=3, sticky='W')

        # Adding a Button
        self.action = ttk.Button(self.mySQL,
                                 text="Insert Quote",
                                 command=self.callBacks.insertQuote)
        self.action.grid(column=2, row=1)

        # Adding a Button
        self.action1 = ttk.Button(self.mySQL,
                                  text="Get Quotes",
                                  command=self.callBacks.getQuote)
        self.action1.grid(column=2, row=2)

        # Adding a Button
        self.action2 = ttk.Button(self.mySQL,
                                  text="Mody Quote",
                                  command=self.callBacks.modifyQuote)
        self.action2.grid(column=2, row=3)

        # Add some space around each widget
        for child in self.mySQL.winfo_children():
            child.grid_configure(padx=2, pady=4)

        quoteFrame = ttk.LabelFrame(tab1, text=' Book Quotation ')
        quoteFrame.grid(column=0, row=1, padx=8, pady=4)

        # Using a scrolled Text control
        quoteW = 40
        quoteH = 6
        self.quote = scrolledtext.ScrolledText(quoteFrame,
                                               width=quoteW,
                                               height=quoteH,
                                               wrap=tk.WORD)
        self.quote.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Add some space around each widget
        for child in quoteFrame.winfo_children():
            child.grid_configure(padx=2, pady=4)

        #======================================================================================================
        # Tab Control 2
        #======================================================================================================
        # We are creating a container frame to hold all other widgets -- Tab2
        self.widgetFrame = ttk.LabelFrame(tab2, text=self.i18n.WIDGET_LABEL)
        self.widgetFrame.grid(column=0, row=0, padx=8, pady=4)

        # Creating three checkbuttons
        self.chVarDis = tk.IntVar()
        self.check1 = tk.Checkbutton(self.widgetFrame,
                                     text=self.i18n.disabled,
                                     variable=self.chVarDis,
                                     state='disabled')
        self.check1.select()
        self.check1.grid(column=0, row=0, sticky=tk.W)

        self.chVarUn = tk.IntVar()
        self.check2 = tk.Checkbutton(self.widgetFrame,
                                     text=self.i18n.unChecked,
                                     variable=self.chVarUn)
        self.check2.deselect()
        self.check2.grid(column=1, row=0, sticky=tk.W)

        self.chVarEn = tk.IntVar()
        self.check3 = tk.Checkbutton(self.widgetFrame,
                                     text=self.i18n.toggle,
                                     variable=self.chVarEn)
        self.check3.deselect()
        self.check3.grid(column=2, row=0, sticky=tk.W)

        # Radiobutton list
        colors = self.i18n.colors

        self.radVar = tk.IntVar()

        # Selecting a non-existing index value for radVar
        self.radVar.set(99)

        # Creating all three Radiobutton widgets within one loop
        for col in range(3):
            self.curRad = 'rad' + str(col)
            self.curRad = tk.Radiobutton(self.widgetFrame,
                                         text=colors[col],
                                         variable=self.radVar,
                                         value=col,
                                         command=self.callBacks.radCall)
            self.curRad.grid(column=col, row=6, sticky=tk.W, columnspan=3)

        # Create a container to hold labels
        labelsFrame = ttk.LabelFrame(self.widgetFrame,
                                     text=self.i18n.labelsFrame)
        labelsFrame.grid(column=0, row=7, pady=6)

        # Place labels into the container element - vertically
        ttk.Label(labelsFrame, text=self.i18n.chooseNumber).grid(column=0,
                                                                 row=0)
        self.lbl2 = tk.StringVar()
        self.lbl2.set(self.i18n.label2)
        ttk.Label(labelsFrame, textvariable=self.lbl2).grid(column=0, row=1)

        # Add some space around each label
        for child in labelsFrame.winfo_children():
            child.grid_configure(padx=6, pady=1)

        number = tk.StringVar()
        self.combo = ttk.Combobox(self.widgetFrame,
                                  width=12,
                                  textvariable=number)
        self.combo['values'] = (1, 2, 4, 42, 100)
        self.combo.grid(column=1, row=7, sticky=tk.W)
        self.combo.current(0)
        self.combo.bind('<<ComboboxSelected>>', self.callBacks._combo)

        # Adding a Spinbox widget using a set of values
        self.spin = Spinbox(self.widgetFrame,
                            values=(1, 2, 4, 42, 100),
                            width=5,
                            bd=8,
                            command=self.callBacks._spin)
        self.spin.grid(column=2, row=7, sticky='W,', padx=6, pady=1)

        # Using a scrolled Text control
        scrolW = 40
        scrolH = 1
        self.scr = scrolledtext.ScrolledText(self.widgetFrame,
                                             width=scrolW,
                                             height=scrolH,
                                             wrap=tk.WORD)
        self.scr.grid(column=0, row=8, sticky='WE', columnspan=3)

        # Adding a TZ Button
        self.allTZs = ttk.Button(self.widgetFrame,
                                 text=self.i18n.timeZones,
                                 command=self.callBacks.allTimeZones)
        self.allTZs.grid(column=0, row=9, sticky='WE')

        # Adding local TZ Button
        self.localTZ = ttk.Button(self.widgetFrame,
                                  text=self.i18n.localZone,
                                  command=self.callBacks.localZone)
        self.localTZ.grid(column=1, row=9, sticky='WE')

        # Adding getTime TZ Button
        self.dt = ttk.Button(self.widgetFrame,
                             text=self.i18n.getTime,
                             command=self.callBacks.getDateTime)
        self.dt.grid(column=2, row=9, sticky='WE')

        # Create Manage Files Frame ------------------------------------------------
        mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mgrFiles)
        mngFilesFrame.grid(column=0, row=1, sticky='WE', padx=10, pady=5)

        # Button Callback
        def getFileName():
            print('hello from getFileName')
            fDir = path.dirname(__file__)
            fName = fd.askopenfilename(parent=self.win, initialdir=fDir)
            print(fName)
            self.fileEntry.config(state='enabled')
            self.fileEntry.delete(0, tk.END)
            self.fileEntry.insert(0, fName)

            if len(fName) > self.entryLen:
                self.fileEntry.config(width=len(fName) + 3)

        # Add Widgets to Manage Files Frame
        lb = ttk.Button(mngFilesFrame,
                        text=self.i18n.browseTo,
                        command=getFileName)
        lb.grid(column=0, row=0, sticky=tk.W)

        #-----------------------------------------------------
        file = tk.StringVar()
        self.entryLen = scrolW - 4
        self.fileEntry = ttk.Entry(mngFilesFrame,
                                   width=self.entryLen,
                                   textvariable=file)
        self.fileEntry.grid(column=1, row=0, sticky=tk.W)

        #-----------------------------------------------------
        logDir = tk.StringVar()
        self.netwEntry = ttk.Entry(mngFilesFrame,
                                   width=self.entryLen,
                                   textvariable=logDir)
        self.netwEntry.grid(column=1, row=1, sticky=tk.W)

        def copyFile():
            import shutil
            src = self.fileEntry.get()
            file = src.split('/')[-1]
            dst = self.netwEntry.get() + '\\' + file
            try:
                shutil.copy(src, dst)
                mBox.showinfo('Copy File to Network', 'Succes: File copied.')
            except FileNotFoundError as err:
                mBox.showerror('Copy File to Network',
                               '*** Failed to copy file! ***\n\n' + str(err))
            except Exception as ex:
                mBox.showerror('Copy File to Network',
                               '*** Failed to copy file! ***\n\n' + str(ex))

        cb = ttk.Button(mngFilesFrame, text=self.i18n.copyTo, command=copyFile)
        cb.grid(column=0, row=1, sticky=tk.E)

        # Add some space around each label
        for child in mngFilesFrame.winfo_children():
            child.grid_configure(padx=6, pady=6)

        # Creating a Menu Bar ==========================================================
        menuBar = Menu(tab1)
        self.win.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label=self.i18n.new)
        fileMenu.add_separator()
        fileMenu.add_command(label=self.i18n.exit,
                             command=self.callBacks._quit)
        menuBar.add_cascade(label=self.i18n.file, menu=fileMenu)

        # Add another Menu to the Menu Bar and an item
        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label=self.i18n.about)
        menuBar.add_cascade(label=self.i18n.help, menu=helpMenu)

        # Using tkinter Variable Classes
        strData = tk.StringVar()
        strData.set('Hello StringVar')

        # It is not necessary to create a tk.StringVar()
        strData = tk.StringVar()
        strData = self.spin.get()

        # Place cursor into name Entry
        self.bookTitle.focus()
Exemple #8
0
model.add(Flatten())
model.add(Dropout(0.5))
model.add(Dense(units=64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer=optimizer,
              metrics=['accuracy'])
model.summary()

# training

# get callbacks
callbacks = Callbacks(config, log_dir).callbacks
print('callbacks:')
for callback in callbacks:
    print('\t', callback)

# set variables
val_loss = []
val_acc = []
loss = []
acc = []
lr = []
bs = []
epoch_iter = 1
max_epochs = config.epochs
batch_size = config.batch_size
Exemple #9
0
class SimpleRegex():
    def __init__(self):
        self.main = tk.Tk()
        self.i18n = I18N('kr')
        self.callBacks = Callbacks(self)
        self.main.title(self.i18n.title)

        self.fDir = fDir
        self.saveDir = saveDir
        self.VERSION = VERSION
        self.ftypes = ftypes

        self.createWidgets()
        self.callBacks.defaultFileEntries()

        # self.main.protocol("WM_DELETE_WINDOW", self.callBacks._msgBoxExit)

    # ---------------------
    # widget Control
    # ---------------------
    def createWidgets(self):
        #==============
        # Tabs
        #==============
        # Create a Tab Bar
        tabControl = ttk.Notebook(self.main)

        # Add Tab items
        tab1 = ttk.Frame(tabControl)
        tabControl.add(tab1, text=self.i18n.textEdit)
        tab3 = ttk.Frame(tabControl)
        tabControl.add(tab3, text=self.i18n.fileEdit)
        tab2 = ttk.Frame(tabControl)
        tabControl.add(tab2, text=self.i18n.settings)

        # Locate Tabs
        tabControl.pack(expand=1, fill='both')
        # tabControl.pack()

        # Create Global buttons
        self.runB = ttk.Button(self.main,
                               text="RUN",
                               command=self.callBacks._preprocess_files)
        self.runB.pack(side='right')

        # Create status label
        self.status = 'Idle'
        self.statusLabel = ttk.Label(self.main,
                                     text='Current status: ' + self.status)
        self.statusLabel.pack(side='bottom', anchor='w', padx=1)

        # TAB1
        #==============
        # Labels
        #==============
        # Add LabelFrame items
        self.frame = ttk.LabelFrame(tab1, text=' 문장 변환 ')
        self.frame.grid(column=0, row=0, padx=8, pady=4, sticky='W')

        self.optionsFrame = ttk.LabelFrame(self.frame, text='')
        self.optionsFrame.grid(column=1,
                               row=0,
                               padx=8,
                               pady=1,
                               sticky='E',
                               rowspan=2)

        #Add Label items
        self.inputLabel = ttk.Label(self.frame, text='Input')
        self.inputLabel.grid(column=0, row=0, padx=8, sticky='W')

        self.outputLabel = ttk.Label(self.frame, text='Result')
        self.outputLabel.grid(column=0,
                              row=2,
                              padx=8,
                              sticky='W',
                              columnspan=2)

        # self.optionTest = ttk.Label(self.optionsFrame, text='Test')
        # self.optionTest.grid(column=0,height=10,

        #==============
        # Buttons
        #==============
        # There's an error that can't use height parameter in Button command.
        self.runButton = ttk.Button(self.optionsFrame,
                                    text="RUN",
                                    command=self.callBacks._run)
        # Use grid's 'ipady' parameter instead.
        self.runButton.grid(column=0, row=0, sticky='E', ipadx=18, ipady=10)
        # self.runButton.configure(state='disabled')

        self.stopButton = ttk.Button(self.optionsFrame,
                                     text='STOP',
                                     command=self.callBacks._run)
        self.stopButton.grid(column=0, row=1, sticky='E', ipadx=18, ipady=10)

        self.resetButton = ttk.Button(self.optionsFrame,
                                      text='RESET',
                                      command=self.callBacks._run)
        self.resetButton.grid(column=0, row=2, sticky='E', ipadx=18, ipady=10)

        # self.reset

        #==============
        # CheckButtons
        #==============
        # self.caseChVar = tk.IntVar()
        # self.caseCheck = tk.Checkbutton(self.optionsFrame,
        #                                 text='Case Convertor',
        #                                 variable=self.caseChVar,
        #                                 state='normal')
        # self.caseCheck.grid(column=0, row=1, sticky=tk.W)

        #===============
        # Radio Buttons
        #===============

        #===============
        # ScrollText
        #===============
        self.createScrolls()

        # TAB2
        #==============
        # Labels
        #==============
        # Add LabelFrame items
        self.mngFilesFrame = ttk.LabelFrame(tab2, text=self.i18n.mngFile)
        self.mngFilesFrame.grid(column=0, row=0, padx=8, pady=4, sticky='W')

        self.settingsFrame = ttk.LabelFrame(tab2, text=self.i18n.settings)
        self.settingsFrame.grid(column=0, row=1, padx=8, pady=4, sticky='W')

        self.eliFrame = ttk.LabelFrame(self.settingsFrame,
                                       text=self.i18n.eliminate)
        self.eliFrame.grid(column=0, row=0, padx=8, pady=4, sticky='W')

        self.changeFrame = ttk.LabelFrame(self.settingsFrame,
                                          text=self.i18n.changeable)
        self.changeFrame.grid(column=1, row=0, padx=8, pady=4, sticky='W')

        # Add Label items
        self.seporatorLabel = ttk.Label(self.changeFrame, text='##########')
        self.seporatorLabel.grid(column=0, row=0, padx=8, sticky='W')

        self.explainLabel = ttk.Label(self.settingsFrame,
                                      text=self.i18n.explain)
        self.explainLabel.grid(column=0,
                               row=1,
                               padx=8,
                               pady=4,
                               columnspan=2,
                               sticky='W')

        # ==============
        # Buttons
        # ==============
        #Create button
        self.loadButton = ttk.Button(self.mngFilesFrame,
                                     text=self.i18n.browse,
                                     width=12,
                                     command=self.callBacks._get_file_name)
        self.loadButton.grid(column=0, row=0, sticky=tk.W)

        self.saveButton = ttk.Button(self.mngFilesFrame,
                                     text=self.i18n.save,
                                     width=12,
                                     command=self.callBacks._save_file)
        self.saveButton.grid(column=0, row=1, sticky=tk.E)

        # ==============
        # Entries
        # ==============
        #Create Entry
        self.loadFileDir = tk.StringVar()
        self.loadBrowseEntry = ttk.Entry(self.mngFilesFrame,
                                         width=40,
                                         textvariable=self.loadFileDir)
        self.loadBrowseEntry.grid(column=1, row=0, sticky=tk.W)

        self.saveFileDir = tk.StringVar()
        self.saveBrowseEntry = ttk.Entry(self.mngFilesFrame,
                                         width=40,
                                         textvariable=self.saveFileDir)
        self.saveBrowseEntry.grid(column=1, row=1, sticky=tk.W)

        for child in self.mngFilesFrame.winfo_children():
            child.grid_configure(padx=6, pady=4)

        # ==============
        # CheckButtons
        # ==============
        #Create check button
        #빈줄 제거
        self.whiteSpaceChVar = tk.IntVar()
        self.whiteSpaceCheck = tk.Checkbutton(self.eliFrame,
                                              text=self.i18n.blank,
                                              variable=self.whiteSpaceChVar,
                                              state='normal')
        self.whiteSpaceCheck.grid(column=0, row=0, sticky=tk.W)

        #특수 문자 제거
        self.specialChVar = tk.IntVar()
        self.specialCharCheck = tk.Checkbutton(self.eliFrame,
                                               text=self.i18n.spChar,
                                               variable=self.specialChVar,
                                               state='normal')
        self.specialCharCheck.grid(column=1, row=0, sticky=tk.W)

        #모음 제거
        self.consonantsChVar = tk.IntVar()
        self.consonantsCheck = tk.Checkbutton(self.eliFrame,
                                              text=self.i18n.consonants,
                                              variable=self.consonantsChVar,
                                              state='normal')
        self.consonantsCheck.grid(column=0, row=1, sticky=tk.W)

        #자음 제거
        self.vowelsChVar = tk.IntVar()
        self.vowelsCheck = tk.Checkbutton(self.eliFrame,
                                          text=self.i18n.vowels,
                                          variable=self.vowelsChVar,
                                          state='normal')
        self.vowelsCheck.grid(column=1, row=1, sticky=tk.W)

        # 연속공백 제거
        self.contSpaceChVar = tk.IntVar()
        self.contSpaceCheck = tk.Checkbutton(self.eliFrame,
                                             text=self.i18n.contSpace,
                                             variable=self.contSpaceChVar,
                                             state='normal')
        self.contSpaceCheck.grid(column=0, row=2, sticky=tk.W)

        #한자 제거
        self.chineseChVar = tk.IntVar()
        self.chineseCheck = tk.Checkbutton(self.eliFrame,
                                           text=self.i18n.chinese,
                                           variable=self.chineseChVar,
                                           state='normal')
        self.chineseCheck.grid(column=1, row=2, sticky=tk.W)

        # 특수 숫자 변환
        self.sNumChVar = tk.IntVar()
        self.sNumCheck = tk.Checkbutton(self.changeFrame,
                                        text='① ➀ ❶ ➊ ⓵ ⒈ ⑴  →  1.',
                                        variable=self.sNumChVar,
                                        state='normal')
        self.sNumCheck.grid(column=0, row=0, sticky=tk.W)

        #낫표, 화살괄호 변환
        self.quoteChVar = tk.IntVar()
        self.quoteCheck = tk.Checkbutton(self.changeFrame,
                                         text="「  」 〈  〉 ′               →  '",
                                         variable=self.quoteChVar,
                                         state='normal')
        self.quoteCheck.grid(column=0, row=1, sticky=tk.W)

        #겹낫표, 겹화살괄호 변환
        self.dQuoteChVar = tk.IntVar()
        self.dQuoteCheck = tk.Checkbutton(
            self.changeFrame,
            text='『  』  《  》  ″             →  "',
            variable=self.dQuoteChVar,
            state='normal')
        self.dQuoteCheck.grid(column=0, row=2, sticky=tk.W)

        #===============
        # ProgressBar
        #===============

        self.progressBar = ttk.Progressbar(tab2,
                                           orient='horizontal',
                                           length=370,
                                           mode='determinate')
        self.progressBar.grid(column=0,
                              row=2,
                              columnspan=2,
                              padx=8,
                              pady=4,
                              sticky=tk.W)

        ttk.Button(tab2,
                   text='Run ProgressBar',
                   command=self.callBacks._run_progressbar).grid(column=0,
                                                                 row=3,
                                                                 padx=8,
                                                                 pady=4)

        # Tab3
        #===============
        # Labels
        #===============

        # Create LabelFrames
        self.filesFrame = ttk.LabelFrame(tab3, text=self.i18n.mngFile)
        self.filesFrame.grid(column=0,
                             row=0,
                             padx=8,
                             pady=4,
                             ipadx=8,
                             ipady=4,
                             sticky='W')
        # self.scrollFrame = ttk.LabelFrame(self.filesFrame, text='')
        # self.scrollFrame.grid(column=0, row=0, sticky='nsew', columnspan=2)

        #===============
        # Treeviews
        #===============

        # Create Treeview with scrollbar
        self.fileTree = ttk.Treeview(self.filesFrame,
                                     columns=['name', 'format', 'path'],
                                     show='headings')
        vsb = ttk.Scrollbar(self.filesFrame,
                            orient="vertical",
                            command=self.fileTree.yview)
        hsb = ttk.Scrollbar(self.filesFrame,
                            orient="horizontal",
                            command=self.fileTree.xview)
        self.fileTree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self.fileTree.grid(column=0, row=0, sticky='nsew')
        vsb.grid(column=1, row=0, sticky='ns')
        hsb.grid(column=0, row=1, sticky='ew')

        # Create heading of Treeview
        self.fileTree.heading('name', text='Name', anchor=tk.W)
        self.fileTree.heading('format', text='Format', anchor=tk.W)
        self.fileTree.heading('path', text='File path', anchor=tk.W)

        self.scrollFileDir = tk.StringVar()

        #===============
        # Buttons
        #===============
        self.addNewFileButton = ttk.Button(
            tab3,
            text=self.i18n.addNewFile,
            command=self.callBacks._get_file_name)
        self.addNewFileButton.grid(column=0,
                                   row=1,
                                   pady=6,
                                   ipadx=20,
                                   ipady=4,
                                   sticky='e')

        self.deleteFileButton = ttk.Button(tab3,
                                           text=self.i18n.delete,
                                           command=self.callBacks._remove_file)
        self.deleteFileButton.grid(column=1,
                                   row=1,
                                   pady=6,
                                   padx=10,
                                   ipadx=8,
                                   ipady=4,
                                   sticky=tk.E)

        #===============
        # Menus
        #===============

        # Creating a Menu Bar
        menuBar = Menu(self.main)
        self.main.config(menu=menuBar)

        # Add menu items
        fileMenu = Menu(menuBar, tearoff=0)
        fileMenu.add_command(label=self.i18n.new)
        fileMenu.add_command(label=self.i18n.settingsMenu)
        fileMenu.add_separator()
        fileMenu.add_command(label=self.i18n.exit,
                             command=self.callBacks._display_msg_exit)
        menuBar.add_cascade(label=self.i18n.file, menu=fileMenu)

        helpMenu = Menu(menuBar, tearoff=0)
        helpMenu.add_command(label=self.i18n.about,
                             command=self.callBacks._display_msg_about)
        menuBar.add_cascade(label=self.i18n.help, menu=helpMenu)

    # def createMenu(self):
    #
    #     factory = MenuFactory()
    #
    #     l = factory.createMenu

    def createScrolls(self):

        factory = ScrollFactory()
        # Create an Input ScrollText item
        w = factory.createScroll(0).getScrollConfig()[0]
        h = factory.createScroll(0).getScrollConfig()[1]
        pW = factory.createScroll(0).getScrollConfig()[2]
        pH = factory.createScroll(0).getScrollConfig()[3]
        self.scrlInputText = scrolledtext.ScrolledText(self.frame,
                                                       width=w,
                                                       height=h,
                                                       wrap=tk.WORD)
        self.scrlInputText.grid(column=0, row=1, padx=pW, pady=pH, sticky='w')

        # Create an Output ScrollText item
        w = factory.createScroll(1).getScrollConfig()[0]
        h = factory.createScroll(1).getScrollConfig()[1]
        pW = factory.createScroll(1).getScrollConfig()[2]
        pH = factory.createScroll(1).getScrollConfig()[3]
        self.scrlOutputText = scrolledtext.ScrolledText(self.frame,
                                                        width=w,
                                                        height=h,
                                                        wrap=tk.WORD)
        self.scrlOutputText.grid(column=0,
                                 row=3,
                                 padx=pW,
                                 pady=pH,
                                 sticky='w',
                                 columnspan=2)

        self.scrlInputText.focus()  # Place cursor into Input text
Exemple #10
0
#!/usr/bin/python
# coding=utf-8
__author__ = "Aleksandr Shyshatsky"

from Battle import Battle
from Flash import Flash
from Callbacks import Callbacks
from Events import Events

callbacks = Callbacks()
flash = Flash()
battle = Battle()
events = Events()

__all__ = ['flash', 'battle', 'callbacks', 'events']
Exemple #11
0
def main():
    print('Beginning program')

    # get config
    config = Config().config
    print('change lr:', config.change_lr)
    print('change bs:', config.change_bs)
    print('max epochs:', config.epochs)
    if config.change_bs and config.change_lr:
        print('[!] Whoops: both config.change_bs and config.change_lr are '
              'true -- at least one of them should be false.')
        return

    # get directories
    log_dir = get_log_dir(config)
    data_dir = get_data_dir()
    #train_dir = get_train_dir()
    #test_dir = get_test_dir()
    image_dir = get_celeba_dir()
    print('log dir:', log_dir)
    print('data dir:', data_dir)
    #print('train dir:', train_dir)
    #print('test dir:', test_dir)
    print('image_dir:', image_dir)

    # get data
    print('Loading data...')
    data_dict = get_celeba_data(data_dir)
    x_data, y_data = retrieve_celeba_data(data_dict=data_dict,
                                          image_dir=image_dir)
    x_train, x_test, y_train, y_test = train_test_split(x_data,
                                                        y_data,
                                                        test_size=0.2,
                                                        shuffle=True)
    num_train = int(x_train.shape[0] * 0.8)
    print(f'Num training examples (excludes test and val): {num_train}')

    # build and save initial model
    input_dim = x_train[0].shape
    model = build_model(input_dim, config, model_type=config.complexity)
    save_model(log_dir=log_dir, config=config, model=model)

    # set variables
    val_loss = []
    val_acc = []
    loss = []
    acc = []
    lr = []
    bs = []
    max_epochs = config.epochs
    batch_size = config.batch_size
    batch_size_mult = 2
    epoch_iter = 1

    # get callbacks
    callbacks = Callbacks(config, log_dir).callbacks
    print('callbacks:')
    for callback in callbacks:
        print('\t', callback)

    # train model
    if config.change_lr:  # reduce_lr callback takes care of everything for us
        print('Will change learning rate during training, but not batch size')
        print('Training model...')
        history = model.fit(x_data,
                            y_data,
                            epochs=max_epochs,
                            batch_size=batch_size,
                            shuffle=True,
                            validation_split=0.2,
                            verbose=1,
                            callbacks=callbacks)
        # store history (bs is constant)
        val_loss += history.history['val_loss']
        val_acc += history.history['val_acc']
        loss += history.history['loss']
        acc += history.history['acc']
        lr += history.history['lr']
        bs = [batch_size for i in range(len(history.epoch))]

    elif config.change_bs:  # need to manually stop and restart training
        print('Will change batch size during training, but not learning rate')
        while max_epochs >= epoch_iter:
            print(
                f'Currently at epoch {epoch_iter} of {max_epochs}, batch size is {batch_size}'
            )
            epochs = max_epochs - epoch_iter + 1
            history = model.fit(x_data,
                                y_data,
                                epochs=epochs,
                                batch_size=batch_size,
                                shuffle=True,
                                validation_split=0.2,
                                verbose=1,
                                callbacks=callbacks)
            # store history
            val_loss += history.history['val_loss']
            val_acc += history.history['val_acc']
            loss += history.history['loss']
            acc += history.history['acc']
            bs += [batch_size for i in range(len(history.epoch))]

            # update training parameters
            epoch_iter += len(history.epoch)
            batch_size *= batch_size_mult
            batch_size = batch_size if batch_size < num_train else num_train

        # store lr history as constant (because it is)
        lr = [0.001 for i in range(len(bs))]

    else:
        print('Will not change learning rate nor batch size during training')
        print('Training model...')
        history = model.fit(x_data,
                            y_data,
                            epochs=max_epochs,
                            batch_size=batch_size,
                            shuffle=True,
                            validation_split=0.2,
                            verbose=1,
                            callbacks=callbacks)
        # store history (bs is constant)
        val_loss += history.history['val_loss']
        val_acc += history.history['val_acc']
        loss += history.history['loss']
        acc += history.history['acc']
        lr = [0.001 for i in range(len(history.epoch))]
        bs = [batch_size for i in range(len(history.epoch))]

    print('Completed training')

    # save finished model -- overrides original model saved before training
    save_model(log_dir=log_dir, config=config, model=model)

    # save loss, accuracy, lr, and bs values across epochs as json;
    # have to force cast lr vals as float64 because history object saves them
    # as float32, and json.dump() is not compatible with float32
    acc_loss_lr_bs = {
        'val_loss': val_loss,
        'val_acc': val_acc,
        'loss': loss,
        'acc': acc,
        'lr': [np.float64(i) for i in lr],
        'bs': bs
    }
    acc_loss_lr_bs_path = os.path.join(log_dir, 'acc_loss_lr_bs.json')
    with open(acc_loss_lr_bs_path, 'w') as f:
        json.dump(acc_loss_lr_bs, f, indent=4, sort_keys=True)

    # evaluate model (on original batch size)
    print('Calculating final score...')
    #x_data, y_data = retrieve_data(data_dict=data_dict, image_dir=test_dir)
    score = model.evaluate(x_test, y_test, batch_size=config.batch_size)
    print('Final score:', score)

    print('Completed program')

    return