Exemple #1
0
    def __init__(self, log, config):
        '''Constructor'''
        self.actions = {
            "searchAction": self.searchAction,
            "entryChangeAction": self.entryChangeAction,
            "newAction": self.newEntryAction,
            "showEntryAction": self.entryClickedInVSearch,
            "closedAction": self.closeTabAction,
            "tabChangeAction": self.tabChangeAction,
            "deleteAction": self.deleteEntryAction,
            "pathChangeAction": self.changePathAction,
            "newImageAction": self.newImageAction,
            "imageSelectedAction": self.newFileOrImageSelectedAction,
            "addTagAction": self.newTagAction,
            "deleteTagAction": self.deleteTagAction,
            "deleteImageAction": self.deleteImageAction,
            "deleteFileAction": self.deleteFileAction,
            "newFileAction": self.newFileAction,
            "fileSelectedAction": self.newFileOrImageSelectedAction,
            "openFileAction": self.openFileAction,
            "openEntryOverviewAction": self.openEntryOverviewAction
        }
        if log != None:
            self.log = log
        else:
            self.log = Log("log.txt")

        self.config = ConfigFile(self.log, config)
        self.dbPath = self.config.getValue(self.configDataBase)
        self.tempFilePath = self.config.getValue(self.tempFilePath)
        self.view = View(self.log, self.dbPath, self.actions)
        self.model = Model(self.log, self.dbPath)

        self.log.add(self.log.Info, __file__, "init")
Exemple #2
0
    def test_select(self, mock_input):
        g = Geometria(2.00, 3.10, 4.00)
        v = View()
        area = v.select(g)
        figura = g.figuraName

        self.assertEqual(figura, 'Cuadrado')
        self.assertEqual(area, 4.0)
Exemple #3
0
 def menu():
     opmenu = 0  #variable que controla el menu principal de las operaciones
     while (opmenu != 6):
         print('▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼'.center(80, '▼'))
         print()
         print("::::::::::::::::::::::::::::::::::::::".center(80, " "))
         print(": ╔══════════════════════════════════════╗ :".center(
             80, ' '))
         print(": ║ SISTEMA SISTEMA AUTOMATIZADO PARA LA ║ :".center(
             80, ' '))
         print(": ║ ADMINISTRACIÓN Y GESTIÓN DEPRODUCTOS ║ :".center(
             80, ' '))
         print(": ╚══════════════════════════════════════╝ :".center(
             80, ' '))
         print("::::::::::::::::::::::::::::::::::::::".center(80, " "))
         print(
             "\n\t\t\t[1]  ► AGREGAR CLIENTE\n\t\t\t[2]  ► CONSULTAR CLIENTE"
             "\n\t\t\t[3]  ► LISTAR CLIENTES\n\t\t\t[4]  ► VENDER MUEBLE\n\t\t\t[5]  ► INGRESAR NUEVO MUEBLE\n"
             "\n\t\t\t[6]  ► SALIR\n")
         print('▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲'.center(80, '▲'))
         opmenu = input_rango("UD. PUEDE ELEGIR", 1, 6)
         print("▬▬▬▬▬▬▬▬".center(32, "▬"))
         if opmenu == 1:
             Controller.agregar_cliente()
         if opmenu == 2:
             View.leer_cedula()
         if opmenu == 3:
             Controller.listar_clientes()
         if opmenu == 4:
             Controller.vender()
         if opmenu == 5:
             Controller.agregar_mueble()
         if opmenu == 6:
             os.system('cls')
             print(
                 '..............------------... \n.............(   Adios!   ).. \n..............`--, ,-----´... \n.......@@@.......)/.......... '
             )
             print(
                 '.....@.....@.........,....... \n.....@[email protected]...... \n.......@@@.........o@@....... \n........@..........@......... \n.......@@@........@.......... '
             )
             print(
                 '......@.@..@.....@........... \n.....@..@.....@@............. \n....@...@.................... \n...@....@.................... \n..@.....@......... made ..... '
             )
             print(
                 '........@.........  by  ..... \n........@...... Ronaldo ..... \n.......@.@................... \n......@....@................. \n.....@......@................ '
             )
             print(
                 '....@........@............... \n...@..........@.............. \n.@@@..........@@@............ '
             )
Exemple #4
0
class DataLoader(object):
    def __init__(self):
        self.view = View()
        self.train = DatasetSplit()
        self.val = DatasetSplit()

    def load_data(self, train_path, val_path, delimiter, shuffle_data=False):
        self.view.print_to_screen('Loading data...')

        self.train.load_data(train_path, delimiter)
        train_texts = self.train.get_texts()
        train_labels = self.train.get_labels()
        train_images = self.train.get_images()

        self.val.load_data(val_path, delimiter)
        val_texts = self.val.get_texts()
        val_labels = self.val.get_labels()
        val_images = self.val.get_images()

        self.view.print_to_screen('Train/Dev split: {:d}/{:d}'.format(
            len(train_texts), len(val_texts)))

        if shuffle_data:
            train_texts, train_labels, train_images = shuffle(train_texts,
                                                              train_labels,
                                                              train_images,
                                                              random_state=10)

        self.set_training_data(train_texts, train_labels, train_images)
        self.set_val_data(val_texts, val_labels, val_images)

    def set_val_data(self, val_texts, val_labels, val_images):
        self.val.set_texts(val_texts)
        self.val.set_labels(val_labels)
        self.val.set_images(val_images)

    def set_training_data(self, train_texts, train_labels, train_images):
        self.train.set_texts(train_texts)
        self.train.set_labels(train_labels)
        self.train.set_images(train_images)

    def get_training_data(self):
        return self.train

    def get_val_data(self):
        return self.val
Exemple #5
0
    def setUp(self):
        self.log = Log("testlog.txt")
        self.log.add = MagicMock()

        self.dummy1 = MagicMock()
        self.actions = {"fileSelectedAction": self.dummy1}
        self.dbPath = "arxads"

        self.view = View(log=self.log,
                         dbPath=self.dbPath,
                         actions=self.actions)
        self.view.menubar.enableButtonClose = MagicMock()
        self.view.menubar.enableButtonDelete = MagicMock()
        self.view.tabs.addEntry = MagicMock()
        self.view.tabs.grid = MagicMock()
        self.view.tabs.setSearch = MagicMock()
        self.view.tabs.removeEntry = MagicMock()
        self.view.tabs.hasTabs = MagicMock()
        self.view.menubar.disableButtonClose = MagicMock()
        self.view.menubar.disableButtonDelete = MagicMock()
        self.view.tabs.removeSearch = MagicMock()
        self.view.dbPath.changePath = MagicMock()
Exemple #6
0
class Controller():
    configDataBase = "databasepath"
    tempFilePath = "tempfilepath"

    def __init__(self, log, config):
        '''Constructor'''
        self.actions = {
            "searchAction": self.searchAction,
            "entryChangeAction": self.entryChangeAction,
            "newAction": self.newEntryAction,
            "showEntryAction": self.entryClickedInVSearch,
            "closedAction": self.closeTabAction,
            "tabChangeAction": self.tabChangeAction,
            "deleteAction": self.deleteEntryAction,
            "pathChangeAction": self.changePathAction,
            "newImageAction": self.newImageAction,
            "imageSelectedAction": self.newFileOrImageSelectedAction,
            "addTagAction": self.newTagAction,
            "deleteTagAction": self.deleteTagAction,
            "deleteImageAction": self.deleteImageAction,
            "deleteFileAction": self.deleteFileAction,
            "newFileAction": self.newFileAction,
            "fileSelectedAction": self.newFileOrImageSelectedAction,
            "openFileAction": self.openFileAction,
            "openEntryOverviewAction": self.openEntryOverviewAction
        }
        if log != None:
            self.log = log
        else:
            self.log = Log("log.txt")

        self.config = ConfigFile(self.log, config)
        self.dbPath = self.config.getValue(self.configDataBase)
        self.tempFilePath = self.config.getValue(self.tempFilePath)
        self.view = View(self.log, self.dbPath, self.actions)
        self.model = Model(self.log, self.dbPath)

        self.log.add(self.log.Info, __file__, "init")

    def run(self):
        entries = self.model.getAllEntriesSorted()
        self.view.drawOverview(entries)
        self.view.run()

    def searchAction(self, tag):
        self.log.add(self.log.Info, __file__, "search for : " + tag)
        results = self.model.getEntries(tag)
        self.view.drawSearch(results)

    def entryChangeAction(self, newName, newDescription):
        '''Simply calls update name from model with current entry'''
        self.view.removeEntry(self.model.currentEntry)
        self.model.updateNameOfEntry(self.model.currentEntry, newName)
        self.model.currentEntry.description = newDescription
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.model.currentEntry.name = newName
        self.view.drawEntry(self.model.currentEntry)

    def newEntryAction(self):
        '''Adds a new entry'''
        newNameText = "enter name"
        self.model.currentEntry = ModelEntry(self.log, newNameText)
        i = 0

        while self.model.hasEntry(self.model.currentEntry):
            i += 1
            newName = newNameText + str(i)
            self.model.currentEntry.name = newName

        self.model.openedEntries.append(self.model.currentEntry)
        self.model.addEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def entryClickedInVSearch(self, entryName):
        '''Shows the clicked entry'''
        foundEntry = self.model.getFoundEntry(entryName)
        if foundEntry != None:
            self.model.currentEntry = foundEntry
            self.model.openedEntries.append(foundEntry)
            self.view.drawEntry(foundEntry)

    def closeTabAction(self):
        '''Closes the currently active tab'''
        activeTab = self.view.getActiveTab()

        if activeTab == "Search":
            self.view.removeSearch()
            self.model.currentEntry = None
        else:
            self.model.openedEntries.remove(self.model.currentEntry)
            self.view.removeEntry(self.model.currentEntry)

    def tabChangeAction(self, activeTabName):
        '''Is called when tab focus changes'''
        # only do something when has a valid name
        if activeTabName != None:
            if activeTabName == "Overview":
                entries = self.model.getAllEntriesSorted()
                self.view.setDeleteButton(False)
                self.view.drawOverview(entries)
            if activeTabName == "Search":
                self.view.drawSearch(self.model.foundEntries)
            for e in self.model.openedEntries:
                if activeTabName == e.name:
                    self.model.currentEntry = e
                    self.view.setDeleteButton(True)

    def deleteEntryAction(self):
        '''Deletes the currently active entry'''
        self.model.removeEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)

    def changePathAction(self, newPath):
        '''Changes the database path'''
        self.dbPath = newPath
        self.config.setValue(self.configDataBase, self.dbPath)
        self.model = Model(self.log, self.dbPath)
        self.view.changeDbPath(self.dbPath)

    def newImageAction(self):
        '''Is called when user wants to add a new image 
        by button click'''
        self.view.showNewImageSelectDialog()

    def deleteImageAction(self, imageToDelete):
        '''Deletes image number imageToDelete of current entry'''
        del self.model.currentEntry.images[imageToDelete]
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def newTagAction(self, newTag):
        '''This action is called when user entered a new tag'''
        self.model.currentEntry.tags.append(newTag)
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def deleteTagAction(self, tagToDelete):
        '''Is called when user deletes a tag'''
        self.model.currentEntry.tags.remove(tagToDelete)
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def newFileAction(self):
        '''Is called when user wants to add a new file 
        by button click'''
        self.view.showNewFileSelectDialog()

    def newFileOrImageSelectedAction(self, filename):
        '''Is called when user has selected a new file/image. Method 
        adds the file/image to the model and shows it in view'''
        self.log.add(self.log.Info, __file__, filename + " selected")

        if os.path.exists(filename):
            if self.model.currentEntry.isSupportedImageFile(filename):
                self.addImage(filename)
            else:
                self.addFile(filename)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def deleteFileAction(self, fileToDelete):
        '''Deletes file in current entry'''
        del self.model.currentEntry.files[fileToDelete]
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def addFile(self, filename):
        '''Adds a file to currentEntry and updates the view'''
        f = open(filename, "rb")
        content = f.read()
        f.close()
        name = os.path.basename(filename)
        self.model.currentEntry.files[name] = content
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def addImage(self, filename):
        '''Adds an image to current entry and updates the view'''
        f = open(filename, "rb")
        content = f.read()
        f.close()
        name = os.path.basename(filename)
        self.model.currentEntry.images[name] = content
        self.model.updateContentOfEntry(self.model.currentEntry)
        self.view.removeEntry(self.model.currentEntry)
        self.view.drawEntry(self.model.currentEntry)

    def openFileAction(self, filename):
        '''Opens a file of current entry'''
        temppath = os.path.abspath(self.tempFilePath)
        if not os.path.exists(temppath):
            os.makedirs(temppath)

        path = temppath + "\\" + filename

        if filename in self.model.currentEntry.files:
            content = self.model.currentEntry.files[filename]
        elif filename in self.model.currentEntry.images:
            content = self.model.currentEntry.images[filename]
        else:
            self.log.add(self.log.Warning, __file__, filename + " not in db")
            return

        f = open(path, "wb")
        f.write(content)
        f.close()

        os.startfile(path)

    def openEntryOverviewAction(self, entryName):
        '''Opens the clicked entry, which is currently showed in overview'''
        entry = self.model.getEntryByName(entryName)
        if entry != None:
            self.model.currentEntry = entry
            self.model.openedEntries.append(entry)
            self.view.drawEntry(entry)
Exemple #7
0
 def __init__(self, train_dataset, val_dataset):
     self.train_dataset = train_dataset
     self.val_dataset = val_dataset
     self.view = View()
Exemple #8
0
class ModelTrainer(object):
    def __init__(self, train_dataset, val_dataset):
        self.train_dataset = train_dataset
        self.val_dataset = val_dataset
        self.view = View()

    def train(self, training_params, model_params):

        patience = Patience(model_params.get_patience())
        best_accuracy = Accuracy(0)

        output_width = training_params.get_output_image_width()

        image_resizer = ImageManipulator(output_width)

        with tf.Graph().as_default():
            sess = tf.Session(config=tf.ConfigProto(
                allow_soft_placement=True, log_device_placement=False))
            with sess.as_default():

                cnn = TextImgCNN(
                    sequence_length=self.train_dataset.get_texts().shape[1],
                    num_classes=self.train_dataset.get_labels().shape[1],
                    vocab_size=training_params.get_no_of_words_to_keep(),
                    embedding_size=training_params.get_embedding_dim(),
                    filter_sizes=list(
                        map(int,
                            training_params.get_filter_sizes().split(','))),
                    num_filters=training_params.get_num_filters(),
                    output_image_width=output_width,
                    encoding_height=training_params.get_encoding_height(),
                    l2_reg_lambda=0.0)

                train_iterator, next_train_batch = CustomIterator.create_iterator(
                    self.train_dataset, training_params.get_batch_size())
                test_iterator, next_test_element = CustomIterator.create_iterator(
                    self.val_dataset, training_params.get_batch_size())

                global_step = tf.Variable(0,
                                          name='global_step',
                                          trainable=False)
                optimizer = tf.train.AdamOptimizer(1e-3)
                grads_and_vars = optimizer.compute_gradients(cnn.loss)
                train_op = optimizer.apply_gradients(grads_and_vars,
                                                     global_step=global_step)

                # Keep track of gradient values and sparsity (optional)
                grad_summaries = []
                for g, v in grads_and_vars:
                    if g is not None:
                        grad_hist_summary = tf.summary.histogram(
                            '{}/grad/hist'.format(v.name), g)
                        sparsity_summary = tf.summary.scalar(
                            '{}/grad/sparsity'.format(v.name),
                            tf.nn.zero_fraction(g))
                        grad_summaries.append(grad_hist_summary)
                        grad_summaries.append(sparsity_summary)
                grad_summaries_merged = tf.summary.merge(grad_summaries)

                out_dir = model_params.get_model_directory()

                self.view.print_to_screen('Writing to {}\n'.format(out_dir))

                # Summaries for loss and test_accuracy
                loss_summary = tf.summary.scalar('loss', cnn.loss)
                acc_summary = tf.summary.scalar('test_accuracy', cnn.accuracy)

                # Train Summaries
                train_summary_op = tf.summary.merge(
                    [loss_summary, acc_summary, grad_summaries_merged])
                train_summary_dir = os.path.join(out_dir, 'summaries', 'train')
                train_summary_writer = tf.summary.FileWriter(
                    train_summary_dir, sess.graph)

                # Dev summaries
                dev_summary_op = tf.summary.merge([loss_summary, acc_summary])

                saver = tf.train.Saver(tf.global_variables(), max_to_keep=1)

                file_logger = FileLogger(os.path.join(out_dir, 'result.txt'))
                file_logger.write_header(out_dir)

                sess.run(tf.global_variables_initializer())

                train_length = len(self.train_dataset.get_texts())

                no_of_training_batches = (train_length //
                                          training_params.get_batch_size()) + 1

                input_tensor = ModelTensor(cnn.input_x, cnn.input_y,
                                           cnn.input_mask,
                                           cnn.dropout_keep_prob)

                for epoch in range(model_params.get_no_of_epochs()):
                    sess.run(train_iterator.initializer)

                    for i in range(no_of_training_batches):
                        train_batch = sess.run(next_train_batch)

                        train_images_batch = image_resizer.preprocess_images(
                            train_batch[2])

                        feed_dict = FeedDictCreator.create_feed_dict(
                            input_tensor, train_batch, train_images_batch,
                            training_params.get_dropout_keep_probability())

                        _, step, summaries, loss, accuracy = sess.run([
                            train_op, global_step, train_summary_op, cnn.loss,
                            cnn.accuracy
                        ], feed_dict)

                        train_summary_writer.add_summary(summaries, step)
                        current_step = tf.train.global_step(sess, global_step)

                        training_result = TrainingResult(step, loss, accuracy)

                        self.view.print_to_screen(str(training_result))

                        if current_step % model_params.evaluate_every == 0:
                            self.view.print_to_screen('Evaluation:')

                            val_length = len(self.val_dataset.get_texts())
                            no_of_val_batches = (
                                val_length //
                                training_params.get_batch_size()) + 1

                            sess.run(test_iterator.initializer)
                            correct = 0

                            for i in range(no_of_val_batches):
                                test_batch = sess.run(next_test_element)
                                test_images_batch = image_resizer.preprocess_images(
                                    test_batch[2])

                                feed_dict = FeedDictCreator.create_feed_dict(
                                    input_tensor, test_batch,
                                    test_images_batch, 1)

                                step, summaries, loss, accuracy = sess.run([
                                    global_step, dev_summary_op, cnn.loss,
                                    cnn.accuracy
                                ], feed_dict)

                                correct += accuracy * len(test_images_batch)

                            test_accuracy = Accuracy(correct / val_length)

                            partial_result = PartialResult(
                                epoch, current_step, test_accuracy,
                                best_accuracy, patience)
                            self.view.print_to_screen(str(partial_result))
                            file_logger.write_partial_result_to_file(
                                partial_result)

                            if test_accuracy > best_accuracy:
                                best_accuracy.set_value(
                                    test_accuracy.get_value())
                                patience.reset_patience()
                                path = self.store_model(
                                    model_params, current_step, sess, saver)
                                self.view.print_to_screen(
                                    'Saved model checkpoint to {}\n'.format(
                                        path))
                            else:
                                patience.decrement_patience()

                        if patience.is_zero():
                            return

    @staticmethod
    def store_model(model_params, current_step, sess, saver):
        checkpoint_dir = os.path.abspath(
            os.path.join(model_params.get_model_directory(), 'checkpoints'))
        checkpoint_prefix = os.path.join(checkpoint_dir, 'model')
        return saver.save(sess, checkpoint_prefix, global_step=current_step)
Exemple #9
0
 def __init__(self):
     self.view = View()
     self.train = DatasetSplit()
     self.val = DatasetSplit()
 def __init__(self, train_dataset, val_dataset, root_dir, model_dir):
     self.train_dataset = train_dataset
     self.val_dataset = val_dataset
     self.root_dir = root_dir
     self.model_dir = model_dir
     self.view = View()
Exemple #11
0
    config['trace'] = True
    config['grid_size_X'] = args['grid_size_X']
    config['grid_size_Y'] = args['grid_size_Y']
    config['view'] = False
    config['seed'] = 0
else:
    config['view'] = True

trace_file = open("trace.csv", "w+") if config['trace'] else None

seed = None if config['seed'] == 0 else config['seed']
random.seed(seed)

env = EnvironmentAvatar(config['grid_size_X'], config['grid_size_Y'],
                        config['torus'])
view = View(env, config['canvas_size_X']) if config['view'] else None
sma = SMAAvatar(config, env, view, configAvatar, trace_file)


def test():
    while not sma.run():
        continue


if view != None:
    view.window.after(1000, test)
    view.window.mainloop()
else:
    test()

if trace_file != None:
Exemple #12
0
 def __init__(self):
     self.__model = Model()  # Fachada do modelo
     self.__view = View(self)  # Tela principal da aplicação
     self.__view.start()
Exemple #13
0
class Controller:

    __model = None  # Fachada do modelo
    __view = None  # Tela principal da aplicação
    '''
       Método construtor.
    '''
    def __init__(self):
        self.__model = Model()  # Fachada do modelo
        self.__view = View(self)  # Tela principal da aplicação
        self.__view.start()

    def __adicionar_multiplos_elementos(self, lista_de_elementos):
        for elemento in lista_de_elementos:
            self.__adicionar_unico_elemento(elemento)

    def __adicionar_unico_elemento(self, elemento):
        self.__model.adicionar_elemento_na_lista(elemento)
        self.__view.adicionar_elemento_na_lista(elemento.get_nome(),
                                                elemento.get_tipo())

    # Callbacks da interface
    '''
        Método que recebe um nome e a entrada de uma gramática e a adiciona no sistema, mostrando erro caso aconteça.
        \:param nome é o nome da gramática que será criada.
        \:param entrada é a representação textual da gramática.
        \:return True se a operação foi bem sucedida, False caso contrário.
    '''

    def cb_nova_gramatica(self, nome, entrada):
        try:
            gr = self.__model.criar_gramatica(nome, entrada)
            self.__adicionar_unico_elemento(gr)
            return True
        except FormatError as e:
            self.__view.mostrar_aviso(e.get_message())
            return False
        except Exception:
            self.__view.mostrar_aviso("Erro ao criar gramática.")
            return False

    '''
        Método que recebe um nome e a entrada de uma expressão e a adiciona no sistema, mostrando erro caso aconteça.
        \:param nome é o nome da expressão que será criada.
        \:param entrada é a representação textual da expressão.
        \:return True se a operação foi bem sucedida, False caso contrário.
    '''

    def cb_nova_expressao(self, nome, entrada):
        try:
            er = self.__model.criar_expressao(nome, entrada)
            self.__adicionar_unico_elemento(er)
            return True
        except ExpressionParsingError as e:
            self.__view.mostrar_aviso(e.get_message())
            return False
        except Exception:
            self.__view.mostrar_aviso("Erro ao criar expressão.")
            return False

    '''
        Método que recebe um índice e remove esse objeto da lista.
        \:param indice é o índice do elemento na lista.
    '''

    def cb_remover_elemento(self, indice):
        self.__model.remover_elemento(indice)
        self.__view.remover_elemento_da_lista(indice)

    '''
        Método que é chamado ao alterar o elemento selecionado na lista.
        \:param indice é o índice do elemento na lista.
    '''

    def cb_alterar_elemento_selecionado(self, indice):
        elemento = None
        if indice is not None:
            elemento = self.__model.obter_elemento_por_indice(indice)
        self.__view.atualiza_elemento_selecionado(indice, elemento)

    '''
        Método que é chamado ao requisitar a conversao e um elemento para uma gramática regular.
        \:param indice é o índice do elemento na lista.
    '''

    def cb_converter_para_gr(self, indice):
        elementos_novos = self.__model.transformar_elemento_em_gr(indice)
        self.__adicionar_multiplos_elementos(elementos_novos)

    '''
        Método que é chamado ao requisitar a conversao e um elemento para uma gramática regular.
        \:param indice é o índice do elemento na lista.
    '''

    def cb_converter_para_af(self, indice):
        elemento_novo = self.__model.transformar_elemento_em_af(indice)
        self.__adicionar_unico_elemento(elemento_novo)

    '''
        Método que é chamado ao requisitar uma operação entre dois elementos.
        \:param indice_um é o índice na lista do primeiro elemento da operação.
        \:param indice_dois é o índice na lista do segundo elemento da operação.
        \:param operacao é o índice da operacao selecionada.
    '''

    def cb_aplica_operacao(self, indice_um, indice_dois, operacao):
        if operacao >= 3 or indice_dois is not None:
            try:
                elementos_novos = self.__model.operacao_elementos(
                    indice_um, indice_dois, operacao)
                self.__adicionar_multiplos_elementos(elementos_novos)
            except AFNDError as e:
                self.__view.mostrar_aviso(e.get_message())
        else:
            self.__view.mostrar_aviso(
                "Você precisa selecionar um segundo\nelemento para aplicar a operação."
            )

    '''
        Método que é chamado ao requisitar uma operação entre duas gramáticas regulares.
        \:param indice_um é o índice na lista da primeira gramática da operação.
        \:param indice_dois é o índice na lista da segunda gramática da operação.
        \:param operacao é o índice da operacao selecionada.
    '''

    def cb_aplica_operacao_gr(self, indice_um, indice_dois, operacao):
        if operacao == 2 or indice_dois is not None:
            elementos_novos = self.__model.operacao_gr(indice_um, indice_dois,
                                                       operacao)
            self.__adicionar_unico_elemento(elementos_novos)
        else:
            self.__view.mostrar_aviso(
                "Você precisa selecionar uma segunda\ngramática para aplicar a operação."
            )

    '''
        Obtem um automato equivalente determinístico.
        \:param indice é o índice do autômato na lista.
    '''

    def cb_determiniza_af(self, indice):
        try:
            novo_elemento = self.__model.determiniza_af(indice)
            self.__adicionar_unico_elemento(novo_elemento)
        except Exception:
            self.__view.mostrar_aviso("O autômato ja é determinístico.")

    '''
        Obtem um automato equivalente minimo.
        \:param indice é o índice do autômato na lista.
    '''

    def cb_minimiza_af(self, indice):
        try:
            novo_elemento = self.__model.minimiza_af(indice)
            self.__adicionar_unico_elemento(novo_elemento)
        except Exception:
            self.__view.mostrar_aviso(
                "É preciso que o autômato seja determinístico.")

    '''
        Informa se dada sentença é reconhecida por um autômato especificado.
        \:param indice é o índice do autômato na lista.
        \:param sentenca é a sentença que será reconhecida.
    '''

    def cb_reconhecimento(self, indice, sentenca):
        try:
            if self.__model.reconhecimento(indice, sentenca):
                self.__view.mostrar_aviso(
                    "A sentença \"" + sentenca +
                    "\" é reconhecida pelo autômato.",
                    "Reconhecimento de Sentença")
            else:
                self.__view.mostrar_aviso(
                    "A sentença \"" + sentenca +
                    "\" não é reconhecida pelo autômato.",
                    "Reconhecimento de Sentença")
        except AFNDError:
            self.__view.mostrar_aviso(
                "O autômato precisa ser determinístico para reconhecer uma sentença."
            )
        except Exception:
            self.__view.mostrar_aviso("Erro ao reconhecer sentença.")

    '''
        Obtem as sentenças de um autoômato finito com determinado tamanho.
        \:param indice é o índice do autômato na lista.
        \:param tamanho é o tamanho das sentenças que serão enumeradas.
    '''

    def cb_enumeracao(self, indice, tamanho):
        try:
            sentencas = self.__model.enumeracao(indice, tamanho)
            if sentencas:
                self.__view.mostrar_lista(sentencas, tamanho)
            else:
                self.__view.mostrar_aviso("Nenhuma sentença de tamanho " +
                                          tamanho + " é reconhecida.")
        except ValueError:
            self.__view.mostrar_aviso(
                "O tamanho da sentença deve ser um inteiro.")
        except AFNDError:
            self.__view.mostrar_aviso(
                "O autômato precisa ser determinístico para enumerar sentenças."
            )
        except Exception:
            self.__view.mostrar_aviso("Erro ao enumerar sentenças.")

    '''
        Altera um elemento.
        \:param indice é o índice do autômato na lista.
        \:param tamanho é o tamanho das sentenças que serão enumeradas.
    '''

    def cb_alterar_elemento(self, indice):
        elemento = self.__model.obter_elemento_por_indice(indice)
        try:
            sucesso = self.__view.abrir_janela_edicao_de_elemento(
                elemento.get_nome(), elemento.to_string(), elemento.get_tipo())
            if sucesso:
                self.__view.reposiciona_elemento_editado(indice)
                self.__model.reposiciona_elemento_editado(indice)
                self.cb_alterar_elemento_selecionado(indice)
        except Exception:
            self.__view.mostrar_aviso("O elemento não foi alterado.")

    def cb_duplica_elemento(self, indice):
        copia = self.__model.duplicar(indice)
        self.__adicionar_unico_elemento(copia)

    def cb_salvar_elemento(self, indice):
        elemento = self.__model.obter_elemento_por_indice(indice)
        if elemento.get_tipo() is not TipoElemento.AF:
            caminho = self.__view.salvar_arquivo(elemento.get_nome())
            resultado = self.__model.salvar_elemento(caminho, indice)
            if resultado:
                self.__view.mostrar_aviso("Elemento salvo com sucesso.",
                                          titulo="Sucesso")
            else:
                self.__view.mostrar_aviso("Falha ao salvar arquivo.")
        else:
            self.__view.mostrar_aviso(
                "Não é possível salvar autômatos finitos.")

    def cb_carregar_gr(self, caminho):
        try:
            conteudo = self.__model.carregar_elemento(caminho)
            nome_elemento = self.__model.nome_arquivo(caminho)
            resultado = self.cb_nova_gramatica(nome_elemento, conteudo)
            if resultado:
                self.__view.mostrar_aviso("Gramática carregada com sucesso.",
                                          titulo="Sucesso")
        except Exception:
            self.__view.mostrar_aviso("Erro ao carregar arquivo.")

    def cb_carregar_er(self, caminho):
        try:
            conteudo = self.__model.carregar_elemento(caminho)
            nome_elemento = self.__model.nome_arquivo(caminho)
            resultado = self.cb_nova_expressao(nome_elemento, conteudo)
            if resultado:
                self.__view.mostrar_aviso("Expressão carregada com sucesso.",
                                          titulo="Sucesso")
        except Exception:
            self.__view.mostrar_aviso("Erro ao carregar arquivo.")
Exemple #14
0
from model.Geometria import Geometria
from view.View import View

# from Geometria_.model.Geometria import Geometria
# from Geometria_.view.View import View

if __name__ == '__main__':
    g = Geometria(2.00, 3.10, 4.00)
    v = View()
    v.select(g)
 def iniciarVista(self):
     vista = View(self)
     vista.iniciarVista()
class EncodingExtractor(object):

    def __init__(self, train_dataset, val_dataset, root_dir, model_dir):
        self.train_dataset = train_dataset
        self.val_dataset = val_dataset
        self.root_dir = root_dir
        self.model_dir = model_dir
        self.view = View()

    def extract(self, extraction_parameters):
        checkpoint_dir = os.path.abspath(os.path.join(self.model_dir, 'checkpoints'))
        checkpoint_file = tf.train.latest_checkpoint(checkpoint_dir)
        batch_size = extraction_parameters.get_batch_size()

        image_resizer = ImageManipulator(extraction_parameters.get_output_image_width())

        val_length = len(self.val_dataset.get_texts())
        no_of_val_batches = (val_length // batch_size) + 1

        graph = tf.Graph()
        with graph.as_default():
            sess = tf.Session()
            with sess.as_default():
                self.view.print_to_screen('Loading latest checkpoint: {}'.format(checkpoint_file))
                saver = tf.train.import_meta_graph('{}.meta'.format(checkpoint_file))
                saver.restore(sess, checkpoint_file)

                train_iterator, train_next_element = CustomIterator.create_iterator(self.train_dataset, batch_size)
                val_iterator, val_next_element = CustomIterator.create_iterator(self.val_dataset, batch_size)

                sess.run(train_iterator.initializer)
                sess.run(val_iterator.initializer)

                # Get the placeholders from the graph by name
                input_x = graph.get_operation_by_name('input_x').outputs[0]
                dropout_keep_prob = graph.get_operation_by_name('dropout_keep_prob').outputs[0]
                input_mask = graph.get_operation_by_name('input_mask').outputs[0]

                # Tensors we want to evaluate
                input_y = graph.get_operation_by_name('input_y').outputs[0]
                accuracy = graph.get_operation_by_name('accuracy/accuracy').outputs[0]
                sum = graph.get_operation_by_name('sum').outputs[0]

                input_tensor = ModelTensor(input_x, input_y, input_mask, dropout_keep_prob)

                correct = 0
                for i in range(no_of_val_batches):
                    val_batch = sess.run(val_next_element)
                    path_list = [el.decode('UTF-8') for el in val_batch[2]]

                    test_images_batch = image_resizer.preprocess_images(val_batch[2])
                    feed_dict = FeedDictCreator.create_feed_dict(input_tensor, val_batch, test_images_batch, 1)

                    acc, img_sum = sess.run([accuracy, sum], feed_dict)

                    correct += acc * batch_size
                    thread = Thread(target=self.embedding_to_image,
                                    args=(self.root_dir, img_sum, path_list, extraction_parameters))
                    thread.start()

                self.compute_and_print_accuracy(correct, val_length, 'Test')

                train_length = len(self.train_dataset.get_texts())
                no_of_train_batches = (train_length // batch_size) + 1

                correct = 0
                for i in range(no_of_train_batches):
                    train_batch = sess.run(train_next_element)
                    path_list = [el.decode('UTF-8') for el in train_batch[2]]

                    train_images_batch = image_resizer.preprocess_images(train_batch[2])
                    feed_dict = FeedDictCreator.create_feed_dict(input_tensor, train_batch, train_images_batch, 1)

                    acc, img_sum = sess.run([accuracy, sum], feed_dict)

                    correct += acc * batch_size
                    thread = Thread(target=self.embedding_to_image,
                                    args=(self.root_dir, img_sum, path_list, extraction_parameters))
                    thread.start()

                self.compute_and_print_accuracy(correct, train_length, 'Train')

    def embedding_to_image(self, root_dir, img_sum, test_img, extraction_parameters):
        x = extraction_parameters.get_separator_size()
        y = extraction_parameters.get_separator_size()
        encoding_height = extraction_parameters.get_encoding_height()
        superpixels_per_row = extraction_parameters.get_superpixel_per_row()
        superpixel_w = extraction_parameters.get_superpixel_w()
        output_image_width = extraction_parameters.get_output_image_width()
        superpixel_h = extraction_parameters.get_superpixel_h()

        for image, path in zip(img_sum, test_img):
            dir_names = path.split('/')[-3:]
            full_path = os.path.join(root_dir,
                                     os.path.join(dir_names[0], dir_names[1], dir_names[2].replace('.jpg', '.png')))

            img = cv2.imread(path, cv2.IMREAD_COLOR)
            img = cv2.resize(img, (extraction_parameters.get_image_w(), extraction_parameters.get_image_h()))

            assert extraction_parameters.get_separator_size() + superpixels_per_row * superpixel_w \
                   <= extraction_parameters.get_image_w(), 'the image width is smaller than the visual word width'

            text_encoding_crop = image[0:encoding_height, 0:output_image_width, :]
            word_features = np.reshape(text_encoding_crop,
                                       (output_image_width * encoding_height * 3))  # C-like index ordering

            sp_i = 0  # superpixel index

            # write the embedding
            for row in list(
                    range(y, int(y + extraction_parameters.get_superpixel_per_col() * superpixel_h), superpixel_h)):
                spw = 0  # counter for superpixels in row
                for col in list(range(x, int(x + superpixels_per_row * superpixel_w), superpixel_w)):
                    ptl = sp_i * 3
                    ptr = (sp_i + 1) * 3
                    bgr = word_features[ptl:ptr]
                    if len(bgr) == 0:
                        break
                    elif len(bgr) < 3:
                        c = bgr.copy()
                        c.resize(1, 3)
                        bgr = c

                    row_start = row
                    row_end = row + superpixel_w
                    for srow in range(row_start, row_end):
                        for scol in range(col, col + superpixel_h):
                            img[srow, scol] = bgr * 255

                    sp_i += 1
                    spw += 1

            cv2.imwrite(full_path, img)

    def compute_and_print_accuracy(self, correct, split_dataset_length, phase):
        test_accuracy = correct / split_dataset_length
        self.view.print_to_screen(
            '{} accuracy: {} / {} = {}'.format(phase, int(correct), split_dataset_length, test_accuracy))
    factory = OrganismFactory()

    # add one human
    org = factory.createOrganism(SpeciesEnum.HUMAN,
                                 model.getFreePositionInWorld())
    org.world = model
    model.addOrganism(org)
    # add the rest
    for sp in SpeciesEnum:
        propName = "number_of_{0}".format(sp.name.lower())
        if propName in globals():
            propValInt = globals()[propName]
            # print(propValInt)
            if propName and not propName == "number_of_human":
                for i in range(0, propValInt):
                    org = factory.createOrganism(
                        sp, model.getFreePositionInWorld())
                    if org:
                        org.world = model
                        model.addOrganism(org)

    # --------------
    #   Simple MVC
    # --------------
    app = wx.App(False)
    ogl.OGLInitialize()
    view = View(None)
    controller = Controller(app, model, view)

    app.MainLoop()
 def iniciarVista(self):
     vista = View(self)
     #vista.iniciarVista()
     #vista.initViewAlumnos()
     vista.iniciarVista()
Exemple #19
0
class TestView(unittest.TestCase):
    def setUp(self):
        self.log = Log("testlog.txt")
        self.log.add = MagicMock()

        self.dummy1 = MagicMock()
        self.actions = {"fileSelectedAction": self.dummy1}
        self.dbPath = "arxads"

        self.view = View(log=self.log,
                         dbPath=self.dbPath,
                         actions=self.actions)
        self.view.menubar.enableButtonClose = MagicMock()
        self.view.menubar.enableButtonDelete = MagicMock()
        self.view.tabs.addEntry = MagicMock()
        self.view.tabs.grid = MagicMock()
        self.view.tabs.setSearch = MagicMock()
        self.view.tabs.removeEntry = MagicMock()
        self.view.tabs.hasTabs = MagicMock()
        self.view.menubar.disableButtonClose = MagicMock()
        self.view.menubar.disableButtonDelete = MagicMock()
        self.view.tabs.removeSearch = MagicMock()
        self.view.dbPath.changePath = MagicMock()

    def tearDown(self):
        pass

    def testDrawEntry(self):
        e = "test"
        self.view.drawEntry(e)
        self.view.menubar.enableButtonClose.assert_called_once()
        self.view.menubar.enableButtonDelete.assert_called_once()
        self.view.tabs.addEntry.assert_called_once_with(e)
        self.view.tabs.grid.assert_called()

    def testDrawSearch(self):
        e = "test"
        self.view.drawSearch(e)
        self.view.menubar.enableButtonClose.assert_called_once()
        self.view.tabs.setSearch(e)
        self.view.tabs.grid.assert_called()

    def testRemoveEntry(self):
        e = "test"
        self.view.tabs.hasTabs.return_value = True
        self.view.removeEntry(e)
        self.view.tabs.removeEntry.assert_called_with(e)

        self.view.tabs.hasTabs.return_value = False
        self.view.removeEntry(e)
        self.view.tabs.removeEntry.assert_called_with(e)
        self.view.menubar.disableButtonClose.assert_called_once()
        self.view.menubar.disableButtonDelete.assert_called_once()

    def testRemoveSearch(self):
        self.view.tabs.hasTabs.return_value = True
        self.view.removeSearch()
        self.view.tabs.removeSearch.assert_called()

        self.view.tabs.hasTabs.return_value = False
        self.view.removeSearch()
        self.view.menubar.disableButtonClose.assert_called_once()

    def testSetDeleteButton(self):
        self.view.setDeleteButton(True)
        self.view.menubar.enableButtonDelete.assert_called_once()
        self.view.menubar.disableButtonDelete.assert_not_called()

        self.view.menubar.enableButtonDelete.reset_mock()
        self.view.setDeleteButton(False)
        self.view.menubar.enableButtonDelete.assert_not_called()
        self.view.menubar.disableButtonDelete.assert_called_once()

    def testChangeDbPath(self):
        newPath = "dsaf"
        self.view.changeDbPath(newPath)
        self.view.dbPath.changePath.assert_called_once_with(newPath)

    def testShowFileDialog(self):
        #filename = "filenameblabla"
        #self.view.showFileDialog()
        #self.dummy1.assert_called_once_with(filename)
        #todo
        pass

    def testGetActiveTab(self):
        self.view.tabs.getNameOfActiveTab = MagicMock()
        self.view.getActiveTab()
        self.view.tabs.getNameOfActiveTab.assert_called_once()